짬뽕얼큰하게의 맨땅에 헤딩 :: '2025/02 글 목록 (18 Page)

summary

  • Finding the Center of a Star Graph

approach

  • The solution iterates over each edge in the graph and increments the count of the nodes at each end of the edge
  • It then checks if the count of any node exceeds 1
  • If so, that node is the center of the star graph and the function returns it.

complexity

  • O(n)

explain

  • The time complexity of this solution is O(n) because in the worst case, we might have to iterate over all n edges
  • The space complexity is also O(n) because in the worst case, we might have to store the count of all n nodes.

Solution Code:


class Solution {
public:
    int findCenter(vector>& edges) {
        int cnt[100001] = {0};
        for(int i = 0 ; i < edges.size(); i++){
            int a = edges[i][0];
            int b = edges[i][1];
            cnt[a]++;
            cnt[b]++;
            if (cnt[a] >= 2) return a;
            if (cnt[b] >= 2) return b;
        }
        return 0;
    }
};
블로그 이미지

짬뽕얼큰하게

,

summary

  • The problem is to find the size of the longest non-empty subarray in the given array of integers such that the absolute difference between any two elements of this subarray is less than or equal to the given limit.

approach

  • The approach used is to use a sliding window technique with a multiset data structure to store the elements of the subarray
  • The multiset is used to keep track of the minimum and maximum elements in the current subarray
  • The sliding window is expanded to the right by adding elements to the multiset and contracting the window from the left by removing elements from the multiset if the absolute difference between the minimum and maximum elements exceeds the limit.

complexity

  • O(N log N) due to the insertion and removal operations in the multiset, where N is the size of the input array.

explain

  • The solution code initializes two pointers, l and r, to the start of the array
  • It also initializes a multiset, multi, to store the elements of the subarray
  • The code then enters a loop where it expands the sliding window to the right by adding elements to the multiset and checking if the absolute difference between the minimum and maximum elements exceeds the limit
  • If it does, the code contracts the window from the left by removing elements from the multiset
  • The code keeps track of the maximum length of the subarray seen so far and returns it at the end.

Solution Code:


class Solution {
public:
    int longestSubarray(vector& nums, int limit) {
        int l = 0;
        int r = 0;
        multiset multi;
        int N = nums.size();
        int ans = 0;
        
        multi.insert(nums[0]);
        while(r < N){
            int last = *(multi.rbegin());
            int first = *(multi.begin());
            if (abs(last - first) <= limit){
                ans = max(ans, r-l+1);
                r++;
                if (r < N){
                    multi.insert(nums[r]);
                }
            } else{
                multi.erase(multi.find(nums[l]));
                l++;
            }
        }
        return ans;
    }
};

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

Remove Max Number of Edges to Keep Graph Fully Traversable  (0) 2025.02.02
Find Center of Star Graph  (0) 2025.02.02
Special Array I  (0) 2025.02.02
Check if Array Is Sorted and Rotated  (0) 2025.02.02
Making A Large Island  (0) 2025.02.02
블로그 이미지

짬뽕얼큰하게

,

Special Array I

알고리즘 2025. 2. 2. 10:28

summary

  • Check if an array is special, where every pair of adjacent elements contains two numbers with different parity.

approach

  • Use a flag variable to track the parity of the first element
  • Then, iterate through the array, updating the flag variable based on the parity of each element
  • If a pair of adjacent elements has the same parity, return false
  • Otherwise, return true if all pairs have different parity.

complexity

  • O(n), where n is the number of elements in the array

explain

  • The solution uses bitwise operations to check the parity of each element
  • The expression `nums[i] & 1` checks if the least significant bit of `nums[i]` is 1 (i.e., the number is odd)
  • The `flag ^ (nums[i] & 1)` expression updates the flag variable based on the parity of `nums[i]`
  • If `flag` and `nums[i]` have different parity, `flag` is set to the opposite parity
  • If they have the same parity, `flag` remains unchanged
  • The solution returns false as soon as it encounters a pair of adjacent elements with the same parity, and returns true otherwise.

Solution Code:


class Solution {
public:
    bool isArraySpecial(vector& nums) {
        bool flag = nums[0] & 1;
        for(int i = 1; i < nums.size(); i++){
            if(flag ^ (nums[i] & 1)){
                flag ^= 1;
            } else{
                return false;
            }
        }
        return true;
    }
};

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

Find Center of Star Graph  (0) 2025.02.02
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit  (0) 2025.02.02
Check if Array Is Sorted and Rotated  (0) 2025.02.02
Making A Large Island  (0) 2025.02.02
Redundant Connection  (0) 2025.02.01
블로그 이미지

짬뽕얼큰하게

,

summary

  • Given an array of integers, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions, otherwise return false.

approach

  • The approach used is to find the minimum element in the array and the index of the minimum element
  • Then, check if the array can be rotated such that the minimum element becomes the first element
  • If it can, return true, otherwise return false.

complexity

  • O(n) where n is the number of elements in the array

explain

  • The solution code first finds the minimum element in the array and its index
  • Then, it checks if the array can be rotated such that the minimum element becomes the first element
  • If it can, it means the array was originally sorted in non-decreasing order and then rotated some number of positions
  • If it cannot, it means the array was not rotated and therefore the array was not originally sorted in non-decreasing order.

Solution Code:


class Solution {
public:
    bool check(vector& nums) {
        int N = nums.size();
        int minIdx = 0;
        int minValue = 101;
        for(int i = 0; i 
            if(minValue> nums[i]){
                minIdx = i;
                minValue = nums[i];
            }
        }
        int idx = N - 1;
        while(idx >= 0 && minIdx != N-1 && nums[minIdx] == nums[idx]){
            idx--;
        }
        if(idx != N-1){
            minIdx = idx + 1;
        }
        int beforeVal = nums[minIdx];
        minIdx = (minIdx + 1) %N;
        int n = N;
        n--;
        while(n--){
            if(beforeVal > nums[minIdx]){
                return false;
            }
            beforeVal = nums[minIdx];
            minIdx = (minIdx + 1) %N;
        }
        return true;
    }
};
블로그 이미지

짬뽕얼큰하게

,

summary

  • This solution calculates the size of the largest island in a binary matrix after changing at most one 0 to 1.

approach

  • This solution first calculates the size of each island in the grid, then finds the maximum island size
  • After that, it finds the maximum island size that can be formed by connecting islands with at most one common cell.

complexity

  • O(n^4)

explain

  • The solution first calculates the size of each island in the grid by using DFS
  • Then it finds the maximum island size
  • After that, it finds the maximum island size that can be formed by connecting islands with at most one common cell
  • The time complexity is O(n^4) due to the nested loops in the DFS and the loop to find the maximum island size.

Solution Code:


class Solution {
public:
    int groups[62501];
    int groupSize;
    int R;
    int C;
    set aroundGroup[500][500];
    void calcGroupCnt(vector>& grid, int r, int c, int& cnt, int visited[500][500],int groupIdx){
        if(r < 0 || r >= R || c <0 || c >= C || visited[r][c] || grid[r][c] == 0){
            return;
        }
        visited[r][c] = groupIdx;
        cnt++;
        calcGroupCnt(grid, r+1, c, cnt, visited, groupIdx);
        calcGroupCnt(grid, r-1, c, cnt, visited, groupIdx);
        calcGroupCnt(grid, r, c+1, cnt, visited, groupIdx);
        calcGroupCnt(grid, r, c-1, cnt, visited, groupIdx);
    }
    int largestIsland(vector>& grid) {
        R = grid.size();
        C = grid[0].size();
        int visited[500][500] = {0};
        for(int i = 0 ; i < R; i++){
            for(int j = 0 ; j < C; j++){
                if(grid[i][j] == 1 && visited[i][j] == 0){
                    int cnt = 0;
                    groupSize++;
                    calcGroupCnt(grid, i, j, cnt, visited, groupSize);
                    groups[groupSize] = cnt;
                }        
            }
        }
        int ans = 0;
        for(int i = 1 ; i <= groupSize; i++){
            ans = max(ans, groups[i]);
        }


        int dy[] = {1, 0, -1, 0};
        int dx[] = {0, 1, 0, -1};
        for(int i = 0 ; i < R; i++){
            for(int j = 0 ; j < C; j++){
                if(visited[i][j]) continue;
                for(int d = 0; d < 4; d++){
                    int nr = i + dy[d];
                    int nc = j + dx[d];
                    if(nr < 0 || nr >= R || nc < 0 || nc >= C || visited[nr][nc] == 0){
                        continue;
                    }
                    aroundGroup[i][j].insert(visited[nr][nc]);
                }
            }
        }
        for(int i = 0 ; i < R; i++){
            for(int j = 0 ; j < C; j++){
                int ans2 = 0;
                for(auto iter : aroundGroup[i][j]){
                    ans2 += groups[iter];
                }
                ans = max(ans, ans2 + 1);
            }
        }

        return ans;
    }
};

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

Special Array I  (0) 2025.02.02
Check if Array Is Sorted and Rotated  (0) 2025.02.02
Redundant Connection  (0) 2025.02.01
프로그래머스 (PROGRAMMERS) 문자열압축  (0) 2021.01.18
프로그래머스 (Programmers) 입국심사  (0) 2021.01.12
블로그 이미지

짬뽕얼큰하게

,

summary

  • Find the edge that can be removed from a connected graph with n nodes and m edges to make it a tree.

approach

  • Use a union-find data structure to keep track of connected components in the graph
  • Iterate through the edges, and for each edge, check if the two nodes are in the same component
  • If they are, then the edge is the redundant one
  • Otherwise, union the two components.

complexity

  • O(n + m log n) due to the union-find operations, where n is the number of nodes and m is the number of edges.

explain

  • The solution uses a union-find data structure to keep track of connected components in the graph
  • The union-find data structure is initialized with each node as its own component
  • Then, for each edge, the solution checks if the two nodes are in the same component by calling the `disjoint` function
  • If they are, then the edge is the redundant one, and the solution returns it
  • Otherwise, the solution unions the two components by calling the `uf` function
  • The `disjoint` function is used to find the root of a node, and the `uf` function is used to union two components.

Solution Code:


class Solution {
public:
    int uf[1001];
    int disjoint(int x){
        if(x == uf[x]) return x;
        return uf[x] = disjoint(uf[x]);
    }
    vector findRedundantConnection(vector>& edges) {
        for(int i = 0 ; i <= 1000; i++){
            uf[i] = i;
        }
        vector ans;
        for(int i = 0 ; i < edges.size(); i++){
            int a = edges[i][0];
            int b = edges[i][1];
            if(disjoint(a) != disjoint(b)){
                uf[disjoint(a)] = disjoint(b);
            } else{
                ans.push_back(a);
                ans.push_back(b);
            }
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,