짬뽕얼큰하게의 맨땅에 헤딩 :: 'LeetCode' 태그의 글 목록 (22 Page)

Leetcode Problem:

Summary

  • Find the minimum number of deletions needed to make a string of 'a's and 'b's balanced.

Approach

  • Use a greedy approach to count the minimum number of deletions
  • Iterate through the string, incrementing the count of 'b's and decrementing the count of 'a's when a 'b' is encountered after an 'a'
  • The number of deletions is the minimum between the current count of 'b's and 0.

Complexity

  • O(n), where n is the length of the string.

Explain

  • The provided C++ code initializes a variable to store the minimum number of deletions and another variable to count the number of 'b's encountered so far
  • It then iterates through the string, incrementing the 'b' count when a 'b' is encountered and decrementing the 'a' count when a 'b' is encountered after an 'a'
  • The number of deletions is the minimum between the current 'b' count and 0
  • This approach ensures that the minimum number of deletions is achieved by deleting the maximum number of 'a's after a 'b' has been encountered.

Solution Code:


class Solution {
public:
    int minimumDeletions(string s) {
        int ans = 0;
        int b_cnt = 0;
        for(int i = 0 ; i < s.size(); i++){
            if(s[i] == 'b'){
                b_cnt++;
            } else if (b_cnt > 0 && s[i] == 'a'){
                ans++;
                b_cnt--;
            }
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Number of Senior Citizens  (0) 2025.02.04
Filling Bookcase Shelves  (0) 2025.02.04
Count Number of Teams  (0) 2025.02.04
Second Minimum Time to Reach Destination  (0) 2025.02.04
Minimum Cost to Convert String I  (0) 2025.02.04
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Count the number of teams that can be formed from a list of unique ratings.

Approach

  • The solution uses a two-pointer technique to count the number of teams that can be formed
  • It iterates over the list of ratings, and for each rating, it counts the number of ratings to its left and right that are less than and greater than the current rating
  • The number of teams that can be formed with the current rating is then calculated by multiplying the number of ratings to its left and right that are less than and greater than the current rating, respectively
  • The total number of teams is then calculated by summing up the number of teams that can be formed for each rating.

Complexity

  • O(N^2) where N is the number of ratings.

Explain

  • The solution iterates over the list of ratings and for each rating, it counts the number of ratings to its left and right that are less than and greater than the current rating
  • The number of teams that can be formed with the current rating is then calculated by multiplying the number of ratings to its left and right that are less than and greater than the current rating, respectively
  • The total number of teams is then calculated by summing up the number of teams that can be formed for each rating
  • This approach ensures that each rating is counted multiple times, but it is necessary to count the number of teams that can be formed for each rating
  • The time complexity of the solution is O(N^2) because the solution iterates over the list of ratings and for each rating, it counts the number of ratings to its left and right that are less than and greater than the current rating.

Solution Code:


class Solution {
public:
    int ans = 0;
    int numTeams(vector& rating) {
        int N = rating.size();
        for(int i = 1; i < N - 1; i++){
            int leftCnt1 = 0;
            int leftCnt2 = 0;
            int idx = i - 1;
            while(idx >= 0){
                if(rating[idx] < rating[i]){
                    leftCnt1++;
                }
                if(rating[idx] > rating[i]){
                    leftCnt2++;
                }
                idx--;
            }
            int rightCnt1 = 0;
            int rightCnt2 = 0;
            idx = i + 1;
            while(idx < N){
                if(rating[i] < rating[idx]){
                    rightCnt1++;
                }
                if(rating[i] > rating[idx]){
                    rightCnt2++;
                }
                idx++;
            }
            ans += leftCnt1 * rightCnt1;
            ans += leftCnt2 * rightCnt2;
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem is to find the second minimum time it will take to go from vertex 1 to vertex n in a bi-directional connected graph with n vertices, given the edges, time, and change.

Approach

  • The approach used is to use a priority queue to keep track of the nodes to visit, and a visited array to keep track of the nodes that have been visited
  • The time complexity is O(n log n) due to the use of the priority queue.

Complexity

  • O(n log n)

Explain

  • The solution code uses a priority queue to keep track of the nodes to visit, and a visited array to keep track of the nodes that have been visited
  • The time complexity is O(n log n) due to the use of the priority queue
  • The code first initializes the priority queue with the first node (1) and its time (0)
  • Then, it enters a loop where it pops the node with the minimum time from the priority queue, and for each of its neighbors that have not been visited before, it adds them to the priority queue with their updated time
  • The loop continues until all nodes have been visited
  • Finally, it returns the minimum time that has been visited at least twice, which is the second minimum time.

Solution Code:


struct NODE {
    int num;
    int time;

    bool operator <(NODE &b){
        return time < b.time;
    }
};

template 
struct _heap{
    int size;
    T arr[80001];
    _heap(){
        size = 1;
    }
    bool cmp(T a, T b){
        return a < b;
    }
    bool empty(){
        return size == 1;
    }
    void push(T a){
        arr[size++] = a;
        int idx = size - 1;
        while(idx > 1 && cmp(arr[idx], arr[idx/2])){
            T tmp = arr[idx];
            tmp = arr[idx/2];
            arr[idx/2] = tmp;
            idx /= 2;
        }
    }
    T pop(){
        T ret = arr[1];
        arr[1] = arr[--size];
        int i = 1;
        while(true){
            int j = i * 2;
            if (j >= size) break;
            if (j+1 < size && cmp(arr[j+1], arr[j])){
                j++;
            }
            if (cmp(arr[j], arr[i])){
                T tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i = j;
            } else{
                break;
            }
        }

        return ret;
    }
};

class Solution {
public:
    _heap h;
    vector visited[10001];
    vector adj[10001];
    int secondMinimum(int n, vector>& edges, int time, int change) {
        for(int i = 0 ; i < edges.size(); i++){
            int a = edges[i][0];
            int b = edges[i][1];
            adj[a].push_back(b);
            adj[b].push_back(a);
        }
        visited[1].push_back(0);
        for(int i = 0 ; i < adj[1].size(); i++){
            int v = adj[1][i];
            h.push({v, time});
            visited[v].push_back(time);
        }
        int minCost = 1234567890;
        int minSecondCost = 1234567890;

        while(!h.empty()){
            NODE a = h.pop();
            if (a.num == n && a.time < minCost){
                minSecondCost = minCost;
                minCost = a.time;
            }
            if (a.num == n && a.time > minCost && minSecondCost > a.time){
                minSecondCost = a.time;
            }
            for(int i = 0 ; i < adj[a.num].size(); i++){
                int next = adj[a.num][i];
                if (visited[next].size() >= 2){
                    continue;
                }
                int cost = 0;
                if ((a.time / change)%2){
                    cost = (change - (a.time%change)) + a.time + time;
                } else {
                    cost = a.time + time;
                }

                if(visited[next].size() == 0){
                    visited[next].push_back(cost);
                } else{
                    if (visited[next][0] == cost){
                        continue;
                    }
                    visited[next].push_back(cost);
                }
                h.push({next, cost});
            }
        }
        return minSecondCost;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given two strings source and target, and two character arrays original and changed, find the minimum cost to convert source to target using any number of operations.

Approach

  • Dynamic programming is used to find the minimum cost
  • The cost of changing each character in source to the corresponding character in target is calculated and stored in a 2D array minCost
  • Then, the minimum cost of changing each character in source to any character in target is calculated using the Floyd-Warshall algorithm
  • Finally, the minimum cost to convert source to target is calculated by summing up the minimum cost of changing each character in source to the corresponding character in target.

Complexity

  • O(n^3), where n is the length of the strings source and target.

Explain

  • The solution first initializes a 2D array minCost with all elements set to 1234567890
  • Then, it calculates the minimum cost of changing each character in source to the corresponding character in target and stores it in minCost
  • After that, it uses the Floyd-Warshall algorithm to calculate the minimum cost of changing each character in source to any character in target
  • Finally, it calculates the minimum cost to convert source to target by summing up the minimum cost of changing each character in source to the corresponding character in target.

Solution Code:


class Solution {
public:
    long long minCost[26][26];
    long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) {
        for(int i = 0; i < 26; i++){
            for(int j = 0 ; j < 26; j++){
                minCost[i][j] = 1234567890;
            }
        }

        for(int i = 0 ; i < original.size(); i++){
            int a = original[i] -'a';
            int b = changed[i] - 'a';
            if (minCost[a][b] > cost[i]){
                minCost[a][b] = cost[i];
            }
        }

        for(int k = 0 ; k < 26; k++){
            for(int i = 0 ; i < 26; i++){
                if (k == i) continue;
                for(int j = 0 ; j < 26; j++){
                    if(k == j || i == j) continue;
                    if (minCost[i][j] <= minCost[i][k] + minCost[k][j]){
                        continue;
                    }
                    minCost[i][j] = minCost[i][k] + minCost[k][j];
                }
            }
        }
        long long ans = 0;
        for(int i = 0 ; i < source.size(); i++){
            int a = source[i] - 'a';
            int b = target[i] - 'a';
            if (a == b) continue;
            if(minCost[a][b] == 1234567890) return -1;
            ans += minCost[a][b];
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Count Number of Teams  (0) 2025.02.04
Second Minimum Time to Reach Destination  (0) 2025.02.04
Find the City With the Smallest Number of Neighbors at a Threshold Distance  (0) 2025.02.04
Sort an Array  (0) 2025.02.04
Sort the Jumbled Numbers  (0) 2025.02.04
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Find the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold.

Approach

  • The solution uses Floyd-Warshall algorithm to find the shortest path between all pairs of cities, then iterates through each city to count the number of cities that are reachable within the distanceThreshold
  • The city with the smallest count that has the greatest number is returned.

Complexity

  • O(n^3)

Explain

  • The solution first initializes a 2D array dis to store the shortest distance between each pair of cities
  • It then iterates through each edge in the edges array and updates the dis array
  • After that, it uses Floyd-Warshall algorithm to find the shortest path between all pairs of cities
  • Finally, it iterates through each city and counts the number of cities that are reachable within the distanceThreshold
  • The city with the smallest count that has the greatest number is returned.

Solution Code:


class Solution {
public:
        int findTheCity(int n, vector>& edges, int distanceThreshold) {
        vector> dis(n, vector(n, 10001));
        int res = 0, smallest = n;
        for (auto& e : edges)
            dis[e[0]][e[1]] = dis[e[1]][e[0]] = e[2];
        for (int i = 0; i < n; ++i)
            dis[i][i] = 0;
        for (int k = 0; k < n; ++k)
            for (int i = 0; i < n; ++i)
                for (int j = 0; j < n; ++j)
                    dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = 0; j < n; ++j)
                if (dis[i][j] <= distanceThreshold)
                    ++count;
            if (count <= smallest) {
                res = i;
                smallest = count;
            }
        }
        return res;
    }
};

'알고리즘' 카테고리의 다른 글

Second Minimum Time to Reach Destination  (0) 2025.02.04
Minimum Cost to Convert String I  (0) 2025.02.04
Sort an Array  (0) 2025.02.04
Sort the Jumbled Numbers  (0) 2025.02.04
Longest Strictly Increasing or Strictly Decreasing Subarray  (0) 2025.02.03
블로그 이미지

짬뽕얼큰하게

,

Sort an Array

알고리즘 2025. 2. 4. 08:39

Leetcode Problem:

Summary

  • Sort an array of integers in ascending order without using built-in O(nlog(n)) time complexity and smallest space complexity possible.

Approach

  • The approach used is a modified merge sort algorithm
  • The array is divided into two halves until each subarray contains only one element, and then the subarrays are merged back together in sorted order.

Complexity

  • O(nlog(n))

Explain

  • The solution code uses a modified merge sort algorithm to sort the array
  • The merge function takes three parameters: the left index, the right index, and the current index
  • It compares the elements at the left and right indices and swaps them if necessary
  • The merge_sort function recursively divides the array into two halves until each subarray contains only one element, and then it merges the subarrays back together in sorted order
  • The time complexity of the solution is O(nlog(n)) because the merge sort algorithm has a time complexity of O(nlog(n)) and the space complexity is O(n) because the temporary array has a size of n.

Solution Code:


class Solution {
public:
    void merge(vector& nums, int l , int mid, int r){
        int i = l;
        int j = mid + 1;
        int cur = i;
        int tmp[50001];
        while(i <= mid && j <= r){
            if (nums[i] <= nums[j]){
                tmp[cur++] = nums[i++];
            } else {
                tmp[cur++] = nums[j++];
            }
        }
        while(i <= mid){
            tmp[cur++] = nums[i++];
        }
        for(i = l; i < cur; i++){
            nums[i] = tmp[i];
        }
    }
    void merge_sort(vector& nums, int l, int r){
        if (l >= r) return;
        int mid = (l + r) / 2;
        merge_sort(nums, l, mid);
        merge_sort(nums, mid+1, r);
        merge(nums, l, mid, r);
    }
    vector sortArray(vector& nums) {
        merge_sort(nums, 0, nums.size() - 1);
        return nums;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem requires sorting an array of integers based on their mapped values in a shuffled decimal system.

Approach

  • The solution uses a modified merge sort algorithm to sort the array
  • It first creates a temporary array to store the sorted elements, and then merges the sorted subarrays into the original array.

Complexity

  • O(n log n)

Explain

  • The solution defines a helper function `getNum` to calculate the mapped value of a given integer
  • It then uses a modified merge sort algorithm to sort the array
  • The `merge` function is used to merge two sorted subarrays into one, and the `merge_sort` function recursively divides the array into smaller subarrays and sorts them
  • The sorted subarrays are then merged back into the original array using the `merge` function.

Solution Code:


class Solution {
public:
    int tmp[30001];
    int getNum(vector& mapping, int a){
        int pow = 1;
        int res = 0;
        if (a == 0) return mapping[a];
        while(a){
            res += (mapping[a%10])*pow;
            pow *= 10;
            a /= 10;
        }
        return res;
    }
    void merge(vector& mapping, vector& nums, int l, int mid, int r ){
        int i = l;
        int j = mid + 1;
        int cur = i;
        while(i <= mid && j <= r){
            if(getNum(mapping, nums[i]) <= getNum(mapping, nums[j])){
                tmp[cur++] = nums[i++];
            } else {
                tmp[cur++] = nums[j++];
            }
        }
        while(i <= mid){
            tmp[cur++] = nums[i++];    
        }
        for(i = l ; i < cur; i++){
            nums[i] = tmp[i];
        }
    }
    void merge_sort(vector& mapping, vector& nums, int l, int r ){
        if (l >= r) return;
        int mid = (l + r) / 2;
        merge_sort(mapping, nums, l, mid);
        merge_sort(mapping, nums, mid+1, r);
        merge(mapping, nums, l, mid, r);
    }
    vector sortJumbled(vector& mapping, vector& nums) {
        merge_sort(mapping, nums, 0, nums.size() - 1);
        return nums;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Find the length of the longest strictly increasing or decreasing subarray in a given array of integers.

Approach

  • The solution uses a dynamic programming approach
  • It maintains two variables, inc and dec, to track the length of the longest increasing and decreasing subarrays ending at the current position
  • The maximum length between these two subarrays is updated at each step.

Complexity

  • O(n), where n is the length of the input array
  • This is because the solution iterates through the array once.

Explain

  • The solution starts by initializing three variables: inc, dec, and ans
  • inc and dec are used to track the length of the longest increasing and decreasing subarrays ending at the current position, respectively
  • ans is used to store the maximum length of these subarrays
  • The solution then iterates through the array, updating inc and dec based on whether the current element is greater than or less than the previous element
  • If the current element is equal to the previous element, inc and dec are reset to 1
  • At each step, the solution updates ans to be the maximum of its current value and the maximum of inc and dec
  • Finally, the solution returns ans, which represents the length of the longest strictly increasing or decreasing subarray in the input array.

Solution Code:


class Solution {
public:
    int longestMonotonicSubarray(vector& nums) {
        int inc = 1;
        int dec = 1;
        int ans = 1;
        for(int i = 1 ; i < nums.size(); i++){
            if (nums[i-1] < nums[i]){
                inc++;
                dec = 1;
            }else if (nums[i-1] > nums[i]){
                inc = 1;
                dec++;
            } else{
                dec = 1;
                inc = 1;
            }
            
            ans = max(ans, max(inc, dec));
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Sort an Array  (0) 2025.02.04
Sort the Jumbled Numbers  (0) 2025.02.04
Sort Array by Increasing Frequency  (0) 2025.02.03
Sort the People  (0) 2025.02.03
Build a Matrix With Conditions  (0) 2025.02.03
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given an array of integers, sort the array in increasing order based on the frequency of the values
  • If multiple values have the same frequency, sort them in decreasing order.

Approach

  • The solution uses a frequency count array to store the frequency of each value, then sorts the array using a modified merge sort algorithm
  • The modified merge sort algorithm uses a temporary array to store the merged elements and then copies them back to the original array.

Complexity

  • O(n log n)

Explain

  • The solution first creates a frequency count array `cnt` to store the frequency of each value
  • Then it calls the `merge_sort` function to sort the array
  • The `merge_sort` function recursively divides the array into two halves and sorts them separately
  • Then it merges the two sorted halves using the `merge` function
  • The `merge` function compares the frequencies of the values and sorts them in increasing order
  • If multiple values have the same frequency, it sorts them in decreasing order
  • Finally, the solution returns the sorted array.

Solution Code:


class Solution {
    int cnt[300] = {0};
    int tmp[100];
    void merge(vector& nums, int l, int mid, int r){
        int i = l;
        int j = mid + 1;
        int cur = i;
        while( i <= mid && j <= r){
            if (cnt[nums[i] + 100] < cnt[nums[j] + 100]){
                tmp[cur++] = nums[i++];
            } 
            else if(cnt[nums[i] + 100] == cnt[nums[j] + 100] && nums[i] > nums[j]){
                tmp[cur++] = nums[i++];
            }
            else{
                tmp[cur++] = nums[j++];
            }
        }
        while(i <= mid){
            tmp[cur++] = nums[i++];
        }
        for(i = l; i < cur; i++){
            nums[i] = tmp[i];
        }
    }
    void merge_sort(vector &nums, int l, int r){
        if (l >= r) return;
        int mid = (l + r) / 2;
        merge_sort(nums, l, mid);
        merge_sort(nums, mid+1, r);
        merge(nums, l, mid, r);
    }    
public:
    vector frequencySort(vector& nums) {
        for(int i = 0 ; i < nums.size(); i++){
            cnt[nums[i] + 100]++;
        }
        merge_sort(nums, 0, nums.size() -1);
        return nums;
    }
};

'알고리즘' 카테고리의 다른 글

Sort the Jumbled Numbers  (0) 2025.02.04
Longest Strictly Increasing or Strictly Decreasing Subarray  (0) 2025.02.03
Sort the People  (0) 2025.02.03
Build a Matrix With Conditions  (0) 2025.02.03
Number of Good Leaf Nodes Pairs  (0) 2025.02.03
블로그 이미지

짬뽕얼큰하게

,

Sort the People

알고리즘 2025. 2. 3. 07:43

Leetcode Problem:

Summary

  • Given an array of names and heights, sort the names in descending order by height.

Approach

  • Merge Sort algorithm is used to sort the heights array first, then use the sorted heights array to sort the names array.

Complexity

  • O(n log n)

Explain

  • The merge_sort function is a recursive function that divides the array into two halves until each subarray has one element
  • The merge function then merges the subarrays back together in sorted order
  • After sorting the heights array, the names array is sorted based on the heights array
  • The names array is then returned in a vector of strings.

Solution Code:


class Solution {
public:
    vector h;
    int tmp[1001];
    void merge(int* arr, int l, int mid, int r){
        int i = l;
        int j = mid + 1;
        int cur = l;
        while(i <= mid && j <= r){
            int num1 = arr[i];
            int num2 = arr[j];
            if(h[num1] >= h[num2]){
                tmp[cur++] = arr[i++];
            }else{
                tmp[cur++] = arr[j++];
            }
        }
        while(i <= mid){
            tmp[cur++] = arr[i++];
        }
        for(i = l; i < cur; i++){
            arr[i] = tmp[i];
        }
    }
    void merge_sort(int* arr, int l, int r){
        if (l >= r) return;
        int mid = (l + r) / 2;
        merge_sort(arr, l, mid);
        merge_sort(arr, mid+1, r);
        merge(arr, l, mid, r);
    }

    vector sortPeople(vector& names, vector& heights) {
        h = heights;
        int* arr = new int[heights.size()];
        for(int i = 0 ; i < heights.size(); i++){
            arr[i] = i;
        }
        merge_sort(arr, 0, heights.size()-1);
        vector ans;
        for(int i = 0 ; i < heights.size(); i++){
            int n = arr[i];
            ans.push_back(names[n]);
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,