koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: '분류 전체보기' 카테고리의 글 목록 (21 Page)

Leetcode Problem:

Summary

  • Find the kth smallest distance among all pairs of integers in an array.

Approach

  • Binary Search: The solution uses a binary search approach to find the kth smallest distance
  • It sorts the array and then uses two pointers (l and r) to represent the range of possible distances
  • The solution iterates through the range, calculating the number of pairs that have a distance less than or equal to the current mid value
  • If the number of pairs is greater than or equal to k, the solution updates the answer and moves the right pointer to the left
  • Otherwise, it moves the left pointer to the right.

Complexity

  • O(N log N + log k) where N is the length of the array
  • The sorting operation takes O(N log N) time, and the binary search takes O(log k) time.

Explain

  • The solution first sorts the array in ascending order
  • It then initializes two pointers, l and r, to represent the range of possible distances
  • The solution iterates through the range, calculating the number of pairs that have a distance less than or equal to the current mid value
  • If the number of pairs is greater than or equal to k, the solution updates the answer and moves the right pointer to the left
  • Otherwise, it moves the left pointer to the right
  • The solution repeats this process until the left pointer is greater than the right pointer
  • The final answer is the smallest distance that results in k pairs.

Solution Code:


class Solution {
public:
    int smallestDistancePair(vector& nums, int k) {
        sort(nums.begin(), nums.end());
        int N = nums.size();
        int l = 0;
        int r = 1000000;
        int ans = 0;
        while(l <= r ){
            int mid = (l + r) / 2;
            int left = 0;
            int right = 0;
            int cnt = 0;
            int beforeRight = 0;
            while(right < N){
                while(right < N && nums[right] - nums[left] <= mid){
                    right++;
                }
                int NN = right - left;
                cnt += (NN * (NN-1))/2;
                if (left != 0){
                    NN = (beforeRight - left);
                    cnt -= (NN * (NN-1))/2;
                }
                beforeRight = right;
                while(left < right && nums[right] - nums[left] > mid){
                    left++;
                }
            }
            if (cnt >= k){
                if (cnt == k){
                    ans = mid;
                }
                ans = mid;
                r = mid - 1;
            } else{
                l = mid + 1;
            }
        }
        return ans;
    }
};

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

Maximum Distance in Arrays  (0) 2025.02.10
Count Number of Bad Pairs  (0) 2025.02.09
Combination Sum II  (0) 2025.02.09
Kth Largest Element in a Stream  (0) 2025.02.09
Minimum Number of Days to Disconnect Island  (0) 2025.02.09
블로그 이미지

짬뽕얼큰하게

,

Combination Sum II

알고리즘 2025. 2. 9. 08:47

Leetcode Problem:

Summary

  • Find all unique combinations in candidates where the candidate numbers sum to target.

Approach

  • Depth-First Search (DFS) with backtracking, utilizing a counter array to track the availability of each candidate number.

Complexity

  • O(N * target), where N is the number of candidates

Explain

  • The solution uses a DFS approach with backtracking to explore all possible combinations
  • It maintains a counter array to track the availability of each candidate number
  • The dfs function recursively tries to add each candidate number to the current combination, and backtracks if the sum exceeds the target or if the candidate number is no longer available
  • The solution also ensures that duplicate combinations are not included by using a history array to keep track of the candidate numbers added to the current combination.

Solution Code:


class Solution {
public:
    int cnt[31];
    void dfs(vector>& ans, vector& history, int cur, int sum, int target){
        if(sum == target){
            vector tmp;
            for(int i = 0 ; i < history.size(); i++){
                tmp.push_back(history[i]);
            }
            ans.push_back(tmp);
            return;
        }
        if (sum > target) return;

        for(int i = cur; i <= target; i++){
            if(cnt[i] <= 0) continue;
            cnt[i]--;
            history.push_back(i);
            dfs(ans, history, i, sum + i, target);
            cnt[i]++;
            history.pop_back();
        }
    }
    vector> combinationSum2(vector& candidates, int target) {
        for(int i = 0 ; i < candidates.size(); i++){
            if (candidates[i] > 30) continue;
            cnt[candidates[i]]++;
        }
        vector> ans;
        vector history;
        dfs(ans, history, 0, 0, target);
        return ans;
    }
};

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

Count Number of Bad Pairs  (0) 2025.02.09
Find K-th Smallest Pair Distance  (0) 2025.02.09
Kth Largest Element in a Stream  (0) 2025.02.09
Minimum Number of Days to Disconnect Island  (0) 2025.02.09
Regions Cut By Slashes  (0) 2025.02.09
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Implement a class to track the kth highest test score from applicants in real-time.

Approach

  • Use two heaps, a min heap and a max heap, to store the scores
  • The max heap stores the k largest scores, and the min heap stores the remaining scores
  • When a new score is added, if the min heap is not full, push the score into the min heap
  • If the min heap is full and the new score is larger than the smallest score in the min heap, pop the smallest score from the min heap and push the new score into the min heap
  • If the new score is smaller than the smallest score in the min heap, push the new score into the max heap
  • The kth highest score is the top of the max heap.

Complexity

  • O(log n) for push and pop operations, where n is the number of scores.

Explain

  • The provided C++ code implements the KthLargest class using two heaps, a min heap and a max heap
  • The min heap stores the k largest scores, and the max heap stores the remaining scores
  • When a new score is added, if the min heap is not full, push the score into the min heap
  • If the min heap is full and the new score is larger than the smallest score in the min heap, pop the smallest score from the min heap and push the new score into the min heap
  • If the new score is smaller than the smallest score in the min heap, push the new score into the max heap
  • The kth highest score is the top of the max heap
  • The time complexity of the push and pop operations is O(log n), where n is the number of scores.

Solution Code:


bool maxCmp(int a, int b){
    return a > b;
}
bool minCmp(int a, int b){
    return a < b;
}
struct _heap{
    int arr[40000];
    int size;
    bool (*cmp)(int , int);
    _heap(){
        size = 1;
    }
    void setCmp(bool (*compare)(int, int)){
        cmp = compare;
    }
    void push(int a){
        arr[size++] = a;
        int idx = size - 1;
        while(idx > 1 && cmp(arr[idx], arr[idx/2])){
            int tmp = arr[idx];
            arr[idx] = arr[idx/2];
            arr[idx/2] = tmp;
            idx/=2;
        }
    }
    int pop(){
        int 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])){
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i = j;
            } else {
                break;
            }
        }
        return ret;
    }
    bool empty(){
        return size == 1;
    }
};

class KthLargest {
public:
    _heap minHeap;
    _heap maxHeap;
    int K;
    vector tmp;
    KthLargest(int k, vector& nums) {
        K = k;
        minHeap.setCmp(minCmp);
        maxHeap.setCmp(maxCmp);
        for(int i = 0 ; i < nums.size(); i++){
            maxHeap.push(nums[i]);
        }
        while(k--){
            if (!maxHeap.empty())
                minHeap.push(maxHeap.pop());
        }
    }
    
    int add(int val) {
        if (minHeap.size <= K){
           minHeap.push(val); 
        }
        else if (minHeap.arr[1] < val){
            maxHeap.push(minHeap.pop());
            minHeap.push(val);
        } else {
            maxHeap.push(val);
        }
        
        return minHeap.arr[1];
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */

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

Find K-th Smallest Pair Distance  (0) 2025.02.09
Combination Sum II  (0) 2025.02.09
Minimum Number of Days to Disconnect Island  (0) 2025.02.09
Regions Cut By Slashes  (0) 2025.02.09
Find the Number of Distinct Colors Among the Balls  (0) 2025.02.07
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • This is a problem of finding the minimum number of days to disconnect a grid of land and water cells.

Approach

  • The solution uses a breadth-first search (BFS) approach to find the number of islands in the grid, and then iteratively tries to disconnect the islands by changing the land cells to water cells
  • The time complexity is O(R*C) for the BFS and O(R*C) for the iterative process, resulting in a total time complexity of O(R*C).

Complexity

  • O(R*C)

Explain

  • The solution first defines the grid size and the map of land and water cells
  • It then defines a helper function to perform BFS and find the number of islands
  • The main function iteratively tries to disconnect the islands by changing the land cells to water cells, and returns the minimum number of days required to disconnect the grid
  • The time complexity is dominated by the BFS and iterative process, which is O(R*C) for each call
  • The space complexity is also O(R*C) for the visited matrix and the recursive call stack.

Solution Code:


class Solution {
public:
    int R;
    int C;
    vector> map;
    void fill(int r, int c, bool visited[][31]){
        if (r < 0 || r >= R || c < 0 || c >= C || map[r][c] == 0 || map[r][c] == 3 || visited[r][c]){
            return;
        }
        visited[r][c]  = true;
        fill(r + 1, c, visited);
        fill(r, c + 1, visited);
        fill(r - 1, c, visited);
        fill(r, c - 1, visited);
    }
    int getIsland(){
        bool visited[31][31];
        int cnt = 0;
        for(int i = 0 ; i < R; i++){
            for(int j = 0 ; j < C; j++){
                visited[i][j] = false;
            }
        }
        for(int i = 0 ; i < R; i++){
            for(int j = 0 ; j < C; j++){
                if(map[i][j] == 1 && !visited[i][j]){
                    cnt++;
                    fill(i, j, visited);
                }
            }
        }
        return cnt;
    }
    bool closeWater(int r, int c){
        int dy[] = {1, 0, -1, 0};
        int dx[] = {0, 1, 0, -1};
        for(int i = 0 ;i  < 4; i++){
            int nr = r + dy[i];
            int nc = c + dx[i];
            if(nr < 0 || nr >= R || nc < 0 || nc >= C){
                return true;
            }
            if (map[nr][nc] == 0){
                return true;
            }
        }
        return false;
    }
    int minDays(vector>& grid) {
        R = grid.size();
        C = grid[0].size();
        map = grid;
        int ans = 0;
        int island_cnt = getIsland();
        while(island_cnt == 1){
            for(int i = 0 ; i < R; i++){
                for(int j = 0 ; j < C; j++){
                    if(map[i][j] == 0) continue;
                    map[i][j] = 0;
                    int tmpCnt = getIsland();
                    if(tmpCnt != 1) return ans + 1;
                    map[i][j] = 1;
                }
            }
           
            return 2;
        }
        
        return ans;
    }
};

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

Combination Sum II  (0) 2025.02.09
Kth Largest Element in a Stream  (0) 2025.02.09
Regions Cut By Slashes  (0) 2025.02.09
Find the Number of Distinct Colors Among the Balls  (0) 2025.02.07
Tuple with Same Product  (0) 2025.02.07
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given an n x n grid represented as a string array, return the number of regions.

Approach

  • The solution uses a 3D array to store the visited states of the grid cells
  • It then uses a recursive DFS function to fill in the visited states of the neighboring cells
  • The number of regions is incremented each time a new region is found.

Complexity

  • O(n^2) where n is the size of the grid.

Explain

  • The solution first converts the input grid into a 3D array where each cell represents a state in the DFS
  • The states are defined as follows: - 0: not visited - 1: visited - 2: outside the grid The solution then uses a recursive DFS function to fill in the visited states of the neighboring cells
  • If a cell is not visited and is outside the grid, it increments the number of regions and marks the cell as visited
  • Finally, it returns the number of regions.

Solution Code:


class Solution {
public:
    int map[128][128];
    bool visited[128][128];
    int R, C;
    int ans = 0;
    void fill(int r, int c){
        if (r < 0 || r >= R || c < 0 || c >= C || map[r][c] == 1 || visited[r][c]){
            return;
        }
        visited[r][c] = true;
        fill(r + 1, c);
        fill(r, c + 1);
        fill(r - 1, c);
        fill(r, c - 1);
    }
    int regionsBySlashes(vector& grid) {
        R = grid.size();
        C = grid[0].length();
        for(int r = 0 ; r < R; r++){
            for(int c = 0; c < C; c++){
                if (grid[r][c] == '/'){
                    map[3*r][3*c+2] = 1;
                    map[3*r+1][3*c+1] = 1;
                    map[3*r+2][3*c] = 1;
                } else if (grid[r][c] == '\\'){
                    map[3*r][3*c] = 1;
                    map[3*r+1][3*c+1] = 1;
                    map[3*r+2][3*c+2] = 1;

                }
            }
        }
        R *= 3;
        C *= 3;
        for(int r = 0 ; r < R; r++){
            for(int c = 0 ; c < C; c++){
                if (map[r][c] == 0 && !visited[r][c]) {
                    fill(r, c);
                    ans++;
                }
            }
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given a limit and a 2D array of queries, find the number of distinct colors among the balls after each query.

Approach

  • The solution uses two unordered maps to keep track of the color count and the current color of each ball
  • It iterates over the queries, updating the color count and current color of each ball, and pushes the number of distinct colors to the result vector.

Complexity

  • O(n), where n is the number of queries

Explain

  • The solution starts by initializing two unordered maps, colorCnt to store the count of each color and curColor to store the current color of each ball
  • It also initializes a variable colornum to store the number of distinct colors
  • Then, it iterates over the queries, updating the color count and current color of each ball
  • If the current color of a ball is the same as its query color, it pushes the current number of distinct colors to the result vector and continues to the next query
  • If the current color of a ball is not the same as its query color, it decrements the count of the current color and increments the count of the query color
  • Finally, it pushes the updated number of distinct colors to the result vector.

Solution Code:


class Solution {
public:
    vector queryResults(int limit, vector>& queries) {
        unordered_map colorCnt;
        unordered_map curColor;
        vector ans;
        int colornum = 0;
        for(int i = 0 ; i < queries.size(); i++){
            int idx = queries[i][0];
            int color = queries[i][1];
            if(curColor[idx] == color){
                ans.push_back(colornum);
                continue;
            }
            if (colorCnt[curColor[idx]] > 0){
                colorCnt[curColor[idx]]--;
                if(colorCnt[curColor[idx]] == 0){
                    colornum--;
                }
            }
            if(colorCnt[color] == 0){
                colornum++;
            }
            curColor[idx] = color;
            colorCnt[color]++;
             
            ans.push_back(colornum);
        }
        return ans;
    }
};

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

Minimum Number of Days to Disconnect Island  (0) 2025.02.09
Regions Cut By Slashes  (0) 2025.02.09
Tuple with Same Product  (0) 2025.02.07
Check if One String Swap Can Make Strings Equal  (0) 2025.02.05
Magic Squares In Grid  (1) 2025.02.05
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given an array of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of the array and a!= b!= c!= d.

Approach

  • The approach used is to first filter out duplicate numbers from the input array
  • Then, for each pair of numbers in the filtered array, calculate their product and store them in a vector
  • Finally, count the number of tuples that have the same product by iterating over the vector and using a variable to keep track of the current product and the count of tuples with the same product.

Complexity

  • O(n^2 log n) where n is the length of the input array

Explain

  • The code first initializes a boolean array to keep track of duplicate numbers
  • It then iterates over the input array and pushes each number into the boolean array if it's not already present
  • This step is necessary to filter out duplicate numbers
  • After that, the code sorts the filtered array and iterates over it to calculate the products of each pair of numbers
  • The products are stored in a vector
  • Finally, the code counts the number of tuples that have the same product by iterating over the vector and using a variable to keep track of the current product and the count of tuples with the same product
  • The time complexity of this approach is O(n^2 log n) due to the sorting step.

Solution Code:


class Solution {
public:
    bool num[10001];
    int tupleSameProduct(vector& nums) {
        vector nums2;
        for(int i = 0 ; i < nums.size(); i++){
            if(num[nums[i]]){
                continue;
            }
            nums2.push_back(nums[i]);
            num[nums[i]] = true;
        }
        sort(nums2.begin(), nums2.end());
        vector nums3;
        for(int i = 0 ; i < nums2.size(); i++){
            for(int j = i+1 ; j < nums2.size(); j++){
                nums3.push_back(nums2[i] * nums2[j]);
            }
        }
        int ans = 0;
        sort(nums3.begin(), nums3.end());
        int cnt = 1;
        int cur = nums3[0];
        for(int i = 1 ; i < nums3.size();i++){
            cout << nums3[i] << endl;
            if(cur != nums3[i]){
                if(cnt >= 2){
                    ans += (cnt * (cnt - 1))/2 * 8;
                }
                cnt = 0;
            }
            cnt++;
            cur = nums3[i];
        }
        if(cnt >= 2){
            ans += (cnt * (cnt - 1))/2 * 8;
        }
        return ans;
    }
};

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

Regions Cut By Slashes  (0) 2025.02.09
Find the Number of Distinct Colors Among the Balls  (0) 2025.02.07
Check if One String Swap Can Make Strings Equal  (0) 2025.02.05
Magic Squares In Grid  (1) 2025.02.05
Spiral Matrix III  (0) 2025.02.05
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given two strings of equal length, determine if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings.

Approach

  • This solution works by first finding all the indices where the two strings differ
  • If there are no differences, the strings are already equal, so the function returns true
  • If there are exactly two differences, the function checks if swapping the characters at these indices would result in equal strings
  • If so, the function returns true; otherwise, it returns false.

Complexity

  • O(n), where n is the length of the input strings, because the solution makes a single pass through the strings to find the differences.

Explain

  • The solution uses a vector to store the indices where the two strings differ
  • It then checks if there are exactly two differences
  • If so, it checks if swapping the characters at these indices would result in equal strings by comparing the characters at the two indices in both strings
  • If the characters are the same, the function returns true; otherwise, it returns false.

Solution Code:


class Solution {
public:
    vector diffIdx;
    bool areAlmostEqual(string s1, string s2) {
        for(int i = 0 ; i < s1.size(); i++){
            if(s1[i] != s2[i]){
                diffIdx.push_back(i);
            }
        }
        if(diffIdx.size() == 0) return true;
        if(diffIdx.size() != 2) return false;
        if(s1[diffIdx[0]] != s2[diffIdx[1]]){
            return false;
        }
        if(s1[diffIdx[1]] != s2[diffIdx[0]]){
            return false;
        }
        return true;
    }
};

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

Find the Number of Distinct Colors Among the Balls  (0) 2025.02.07
Tuple with Same Product  (0) 2025.02.07
Magic Squares In Grid  (1) 2025.02.05
Spiral Matrix III  (0) 2025.02.05
Integer to English Words  (0) 2025.02.05
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Count the number of 3x3 magic square subgrids in a given grid.

Approach

  • The approach used is to iterate over the grid and for each possible 3x3 subgrid, check if it is a magic square by verifying the sums of rows, columns, and diagonals
  • If all conditions are met, increment the counter.

Complexity

  • O(R*C*(R*C)) where R is the number of rows and C is the number of columns in the grid.

Explain

  • The solution iterates over the grid and checks each 3x3 subgrid
  • For each subgrid, it checks if all numbers are distinct and within the range 1-9
  • Then, it calculates the sums of rows, columns, and diagonals and checks if they are all equal
  • If all conditions are met, it increments the counter
  • The time complexity is O(R*C*(R*C)) due to the nested loops and calculations.

Solution Code:


class Solution {
public:
    int numMagicSquaresInside(vector>& grid) {
        int ans = 0;
        if (grid.size() < 3 || grid[0].size() < 3) return 0;
        for(int i = 0 ; i < grid.size() - 2; i++){
            for(int j = 0 ; j < grid[i].size() - 2; j++){
                int cnt = 0;
                int sum = 0;
                bool visited[10] = {false};
                for(int r =i; r < i + 3; r++){
                    for(int c = j; c < j + 3; c++){
                        if(grid[r][c] < 1 || grid[r][c] >= 10 || visited[grid[r][c]]) break;
                        cnt++;
                        visited[grid[r][c]] = true;
                    }
                }
                int sumArr[8] = {0};
                if (cnt == 9){
                    for(int k = 0 ; k < 3; k++){
                        sumArr[0] += grid[i][j+k];
                        sumArr[1] += grid[i+1][j+k];
                        sumArr[2] += grid[i+2][j+k];
                        sumArr[3] += grid[i+k][j];
                        sumArr[4] += grid[i+k][j+1];
                        sumArr[5] += grid[i+k][j+2];
                        sumArr[6] += grid[i+k][j+k];
                        sumArr[7] += grid[i+k][j+2-k];
                    }
                    bool isMagicGrid = true;
                    for(int k = 1 ; k < 8; k++){
                        if (sumArr[k] != sumArr[0]){
                            isMagicGrid = false;
                            break;
                        }
                    }
                    if (isMagicGrid){
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
};

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

Tuple with Same Product  (0) 2025.02.07
Check if One String Swap Can Make Strings Equal  (0) 2025.02.05
Spiral Matrix III  (0) 2025.02.05
Integer to English Words  (0) 2025.02.05
Minimum Number of Pushes to Type Word II  (0) 2025.02.05
블로그 이미지

짬뽕얼큰하게

,

Spiral Matrix III

알고리즘 2025. 2. 5. 08:47

Leetcode Problem:

Summary

  • Find the positions of a 2D grid in a clockwise spiral shape.

Approach

  • The solution uses a while loop to traverse the grid in a clockwise spiral shape
  • It starts at the given start position and moves in a direction (right, down, left, up) for a specified number of steps
  • The direction is updated after each step, and the position is added to the result list if it is within the grid boundaries.

Complexity

  • O(rows * cols)

Explain

  • The solution uses four arrays `dy` and `dx` to represent the possible directions (up, down, left, right) in the grid
  • The `ans_cnt` variable keeps track of the number of positions visited, and the `cnt` variable keeps track of the number of steps in the current direction
  • The `dir` variable keeps track of the current direction
  • The solution uses a while loop to traverse the grid, and it adds the current position to the result list if it is within the grid boundaries.

Solution Code:


class Solution {
public:
    vector> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        vector> ans;
        int dy[] = {0, 1, 0, -1};
        int dx[] = {1, 0, -1, 0};
        int ans_cnt = 0;
        int cnt = 1;
        int dir = 0;
        ans.push_back({rStart, cStart});
        ans_cnt++;
        while(ans_cnt < rows * cols){
            for(int i = 0 ; i < 2; i++){
                for(int j = 0 ; j < cnt; j++){
                    rStart += dy[dir];
                    cStart += dx[dir];
                    if (rStart < 0 || rStart >= rows || cStart < 0 || cStart >= cols){
                        continue;
                    }
                    ans.push_back({rStart, cStart});
                    ans_cnt++;
                }
                dir = (dir + 1) % 4;
            }
            cnt++;
        }
        return ans;
    }
};

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

Check if One String Swap Can Make Strings Equal  (0) 2025.02.05
Magic Squares In Grid  (1) 2025.02.05
Integer to English Words  (0) 2025.02.05
Minimum Number of Pushes to Type Word II  (0) 2025.02.05
Kth Distinct String in an Array  (0) 2025.02.05
블로그 이미지

짬뽕얼큰하게

,