짬뽕얼큰하게의 맨땅에 헤딩 :: '알고리즘' 태그의 글 목록

Leetcode Problem:

Summary

  • Given an integer array and an integer k, return the number of pairs where the product of indices is divisible by k.

Approach

  • The approach is to use two nested loops to generate all possible pairs of indices in the array
  • For each pair, we check if the elements at those indices are equal and if their product is divisible by k
  • If both conditions are met, we increment the answer counter.

Complexity

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

Explanation

  • The time complexity is O(n^2) because we have two nested loops that iterate over the array
  • The space complexity is O(1) because we only use a constant amount of space to store the answer and other variables.

Solution Code:


class Solution {
public:
    int countPairs(vector& nums, int k) {
        int ans = 0;
        for(int i = 0 ; i < nums.size(); i++){
            for(int j = i + 1; j < nums.size(); j++){
                if(nums[i] != nums[j]) continue;
                if((i*j)%k != 0) continue;
                ans++;
            }
        }
        return ans;
    }
};

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

Count the Number of Good Subarrays  (0) 2025.04.17
Count Good Triplets in an Array  (0) 2025.04.15
Count Good Triplets  (0) 2025.04.14
Count Good Numbers  (0) 2025.04.13
Find the Count of Good Integers  (1) 2025.04.12
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • This problem requires us to find the number of good subarrays in a given array
  • A good subarray is a subarray that has at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].

Approach

  • The solution uses a sliding window approach with two pointers, i and j, to traverse the array
  • It also uses a hashmap to store the count of each element in the current window
  • The time complexity of this approach is O(n), where n is the size of the array.

Complexity

  • O(n)

Explanation

  • The solution starts by initializing a hashmap to store the count of each element in the array
  • It then traverses the array using two pointers, i and j
  • For each element at index j, it increments the count of the element in the hashmap and subtracts 1 from the count of the element at index i
  • If the count of the element at index j is greater than 0, it means that there is already a pair of indices (i, j) such that i < j and arr[i] == arr[j], so it increments the result by j
  • If the count of the element at index j is 0, it means that there is no pair of indices (i, j) such that i < j and arr[i] == arr[j], so it increments the count of the element at index j and continues to the next element
  • Finally, the solution returns the result.

Solution Code:


class Solution {
public:
    long long countGood(vector& A, int k) {
        long long res = 0;
        unordered_map count;
        for (int i = 0, j = 0; j < A.size(); ++j) {
            k -= count[A[j]]++;
            while (k <= 0)
                k += --count[A[i++]];
            res += i;
        }
        return res;
    }
};

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

Count Equal and Divisible Pairs in an Array  (0) 2025.04.17
Count Good Triplets in an Array  (0) 2025.04.15
Count Good Triplets  (0) 2025.04.14
Count Good Numbers  (0) 2025.04.13
Find the Count of Good Integers  (1) 2025.04.12
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • Given two 0-indexed arrays of length n, find the total number of good triplets which are in increasing order in both arrays.

Approach

  • The approach used is to create a Fenwick Tree to efficiently calculate prefix sums, then for each value in the first array, calculate the number of good triplets by querying the Fenwick Tree for the number of elements to the left and right, and multiplying these counts together.

Complexity

  • O(n log n) due to the Fenwick Tree operations, where n is the length of the input arrays.

Solution Code:


class FenwickTree {
private:
    vector tree;

public:
    FenwickTree(int size) : tree(size + 1, 0) {}

    void update(int index, int delta) {
        index++;
        while (index < tree.size()) {
            tree[index] += delta;
            index += index & -index;
        }
    }

    int query(int index) {
        index++;
        int res = 0;
        while (index > 0) {
            res += tree[index];
            index -= index & -index;
        }
        return res;
    }
};

class Solution {
public:
    long long goodTriplets(vector& nums1, vector& nums2) {
        int n = nums1.size();
        vector pos2(n), reversedIndexMapping(n);
        for (int i = 0; i < n; i++) {
            pos2[nums2[i]] = i;
        }
        for (int i = 0; i < n; i++) {
            reversedIndexMapping[pos2[nums1[i]]] = i;
        }
        FenwickTree tree(n);
        long long res = 0;
        for (int value = 0; value < n; value++) {
            int pos = reversedIndexMapping[value];
            int left = tree.query(pos);
            tree.update(pos, 1);
            int right = (n - 1 - pos) - (value - left);
            res += (long long)left * right;
        }
        return res;
    }
};

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

Count Equal and Divisible Pairs in an Array  (0) 2025.04.17
Count the Number of Good Subarrays  (0) 2025.04.17
Count Good Triplets  (0) 2025.04.14
Count Good Numbers  (0) 2025.04.13
Find the Count of Good Integers  (1) 2025.04.12
블로그 이미지

짬뽕얼큰하게

,

Count Good Triplets

알고리즘 2025. 4. 14. 21:03

Leetcode Problem:

Summary

  • Find the number of good triplets in an array of integers given three integers a, b, and c.

Approach

  • Three nested loops are used to iterate through the array and check each triplet against the conditions
  • The absolute difference between each pair of numbers is calculated and compared to the given integers a, b, and c
  • If all conditions are met, the triplet is counted.

Complexity

  • O(n^3) where n is the size of the array

Explanation

  • The solution uses three nested loops to iterate through the array
  • The outer loop starts at the first element, the middle loop starts at the next element after the outer loop, and the inner loop starts at the next element after the middle loop
  • The solution checks each triplet against the conditions and increments the count if all conditions are met.

Solution Code:


class Solution {
public:
    
    int countGoodTriplets(vector& arr, int a, int b, int c) {
        int ans = 0;
        for(int i = 0 ; i < arr.size(); i++){
            for(int j = i + 1; j < arr.size(); j++){
                for(int k = j + 1; k < arr.size(); k++){
                    if(abs(arr[i] - arr[j]) <= a &&
                       abs(arr[j] - arr[k]) <= b &&
                       abs(arr[k] - arr[i]) <= c){
                        ans++;
                       }
                }

            }
        }
        return ans;
    }
};

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

Count the Number of Good Subarrays  (0) 2025.04.17
Count Good Triplets in an Array  (0) 2025.04.15
Count Good Numbers  (0) 2025.04.13
Find the Count of Good Integers  (1) 2025.04.12
Count Symmetric Integers  (0) 2025.04.11
블로그 이미지

짬뽕얼큰하게

,

Count Good Numbers

알고리즘 2025. 4. 13. 09:57

Leetcode Problem:

Summary

  • The problem is to find the total number of good digit strings of length n, where a good digit string is defined as a string where the digits at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).

Approach

  • The solution uses dynamic programming and modular arithmetic to calculate the total number of good digit strings
  • It first calculates the number of good digit strings for even and odd indices separately and then combines them to get the final result.

Complexity

  • The time complexity of the solution is O(log n) due to the use of modular exponentiation, where n is the length of the input string.

Explanation

  • The solution first defines a helper function powpow to calculate the modular exponentiation of a number
  • It then calculates the number of good digit strings for even and odd indices separately using this function
  • The number of good digit strings for even indices is calculated as 5^a, where a is the number of even indices, and the number of good digit strings for odd indices is calculated as 4^b, where b is the number of odd indices
  • The final result is obtained by multiplying these two numbers together and taking the result modulo 10^9 + 7.

Solution Code:


struct powRet{
    long long ret;
    long long n;
};
class Solution {
public:
    const int MOD = 1000000007;
    powRet powpow(long long n, long long num){
        powRet ret;
        long long pow = num;
        long long nn = 1;
        long long beforePow = pow;
        long long beforenn = nn;
        while(nn <= n){
            nn *= 2;
            pow *= pow;
            pow %= MOD;
            if(nn > n) break;
            beforePow = pow;
            beforenn = nn;
        }
        ret.ret = beforePow;
        ret.n = beforenn;
        return ret;
    }
    int countGoodNumbers(long long n) {
        long long ans= 1;
        long long a = (n + 1)/2;
        long long b = n - a;
        while(a){
            powRet ret = powpow(a, 5);
            ans *= ret.ret;
            ans %= MOD;
            a -= ret.n;
        }
        while(b){
            powRet ret = powpow(b, 4);
            ans *= ret.ret;
            ans %= MOD;
            b -= ret.n;
        }
        return ans;
    }
};

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

Count Good Triplets in an Array  (0) 2025.04.15
Count Good Triplets  (0) 2025.04.14
Find the Count of Good Integers  (1) 2025.04.12
Count Symmetric Integers  (0) 2025.04.11
Count the Number of Powerful Integers  (0) 2025.04.11
블로그 이미지

짬뽕얼큰하게

,
pre> code> }; } return ans; } ans += ret; long long ret = getCnt(cnt, n); } cnt[c-'0']++; for(char c : vals){ int cnt[10] = {0}; for(auto vals : s){ long long ans = 0; makePalindrome(n, k, 0, 0); long long countGoodIntegers(int n, int k) { } return ret; } n -= cnt[i]; } ret *= combi(n, cnt[i]); } else{ ret *= combi(n-1, cnt[i]); if(i == 0){ if(cnt[i] == 0) continue; for(int i = 0 ; i < 10; i++){ long long ret = 1; long long getCnt(int cnt[10], int n){ } return ret; }<= i; ret code> for(int i = 1; i <= r; i++){ } n--; rr--; ret *= n; while(rr){ int rr = r; long long ret = 1; long long combi(int n, int r){ } } makePalindrome(n, k, curNum*10 + i, depth + 1); if(depth == 0 && i == 0) continue; for(int i = 0; i <= 9; i++){ } return; } push(curNum); if((curNum%k) == 0){ }<= 10; tmp code> curNum += tmp %10; curNum *= 10; while(tmp){ }<= 10; tmp code> if((n%2) == 1){ long long tmp = curNum;<2){ if(depth == (n+1)code> void makePalindrome(int n, int k, long long curNum, int depth){ } s.insert(str); } str += to_string(tmp[i]); for(int i = 0 ; i < tmp.size(); i++){ string str = ""; sort(tmp.begin(), tmp.end(), [](long long a, long long b) -> long long {return a > b; }); }<= 10; nn code> tmp.push_back(nn%10); while(nn){ long long nn = n; vector tmp; void push(long long n){ set s; public:


class Solution {

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

Count Good Triplets  (0) 2025.04.14
Count Good Numbers  (0) 2025.04.13
Count Symmetric Integers  (0) 2025.04.11
Count the Number of Powerful Integers  (0) 2025.04.11
Minimum Operations to Make Array Values Equal to K  (0) 2025.04.10
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem is to find the number of symmetric integers in the given range [low, high].

Approach

  • The solution checks for symmetry by comparing the sum of the first n digits with the sum of the last n digits for each integer in the range
  • It also handles numbers with an odd number of digits by not including them in the count.

Complexity

  • O(n) where n is the number of integers in the range, as it checks each integer once.

Explanation

  • The solution iterates over each integer in the range and checks for symmetry
  • For numbers with an even number of digits (4 or more), it calculates the sum of the first n digits and the sum of the last n digits
  • If they are equal, it increments the count
  • For numbers with 3 digits, it directly compares the two middle digits
  • The time complexity is linear as it checks each integer once.

Solution Code:


class Solution {
public:
    int countSymmetricIntegers(int low, int high) {
        int ans = 0;
        for(int i = low; i <= high; i++){
            if(i / 1000){
                int a = i / 1000;
                int b = (i % 1000) / 100;
                int c = (i % 100) / 10;
                int d = (i % 10);
                if((a + b) == (c + d)){
                    ans++;
                }
            } else if( ((i/10) > 0) && ((i/10) < 10)){
                int a = i/10;
                int b = i%10;
                if(a == b) ans++;
            }
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • This problem requires finding the total number of powerful integers in a given range.

Approach

  • The solution uses a recursive depth-first search (DFS) approach with memoization to efficiently count the powerful integers
  • It aligns the digits of the start and finish numbers, and then recursively explores all possible combinations of digits that meet the conditions
  • The memoization helps avoid redundant calculations and improves the performance of the solution.

Complexity

  • O(n * limit) where n is the length of the finish number, and limit is the maximum allowed digit value.

Solution Code:


class Solution {
public:
    long long numberOfPowerfulInt(long long start, long long finish, int limit,
                                  string s) {
        string low = to_string(start);
        string high = to_string(finish);
        int n = high.size();
        low = string(n - low.size(), '0') + low;  // align digits
        int pre_len = n - s.size();               // prefix length

        vector memo(n, -1);
        function dfs =
            [&](int i, bool limit_low, bool limit_high) -> long long {
            // recursive boundary
            if (i == low.size()) {
                return 1;
            }

            if (!limit_low && !limit_high && memo[i] != -1) {
                return memo[i];
            }

            int lo = limit_low ? low[i] - '0' : 0;
            int hi = limit_high ? high[i] - '0' : 9;

            long long res = 0;
            if (i < pre_len) {
                for (int digit = lo; digit <= min(hi, limit); digit++) {
                    res += dfs(i + 1, limit_low && digit == lo,
                               limit_high && digit == hi);
                }
            } else {
                int x = s[i - pre_len] - '0';
                if (lo <= x && x <= min(hi, limit)) {
                    res =
                        dfs(i + 1, limit_low && x == lo, limit_high && x == hi);
                }
            }

            if (!limit_low && !limit_high) {
                memo[i] = res;
            }
            return res;
        };
        return dfs(0, true, true);
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem requires to find the minimum number of operations required to make every element in the array equal to a given number k
  • An operation is defined as selecting a valid integer h for the current values in the array, and for each index i where nums[i] > h, set nums[i] to h.

Approach

  • The solution sorts the input array and checks if the first element is less than k
  • If it is, the function returns -1
  • Otherwise, it initializes a counter cnt and a variable cur to the first element of the array
  • It then iterates over the array, incrementing cnt whenever it encounters an element different from cur
  • Finally, it returns cnt as the minimum number of operations required.

Complexity

  • O(n log n) due to the sorting operation, where n is the size of the input array.

Explanation

  • The provided solution code uses a simple and efficient approach to solve the problem
  • First, it sorts the input array in ascending order
  • If the first element is less than k, the function returns -1, indicating that it is impossible to make all elements equal to k
  • Otherwise, it initializes a counter cnt and a variable cur to the first element of the array
  • It then iterates over the array, incrementing cnt whenever it encounters an element different from cur
  • Finally, it returns cnt as the minimum number of operations required
  • The time complexity of this solution is O(n log n) due to the sorting operation, where n is the size of the input array.

Solution Code:


class Solution {
public:
    int minOperations(vector& nums, int k) {
        sort(nums.begin(), nums.end());
        if(nums[0] < k) return -1;
        int cnt = 0;
        int cur = nums[0];
        if(cur != k) cnt++;
        for(int i = 1; i < nums.size(); i++){
            if(cur != nums[i]){
                cnt++;
                cur = nums[i];
            }
        }
        return cnt;
    }
};

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

Count Symmetric Integers  (0) 2025.04.11
Count the Number of Powerful Integers  (0) 2025.04.11
Minimum Number of Operations to Make Elements in Array Distinct  (0) 2025.04.08
Partition Equal Subset Sum  (0) 2025.04.08
Largest Divisible Subset  (0) 2025.04.06
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem is to find the minimum number of operations needed to make the elements in the array distinct
  • The operation allowed is to remove 3 elements from the beginning of the array
  • The goal is to return the minimum number of operations required to make all elements in the array distinct.

Approach

  • The approach used is to first count the occurrences of each number in the array
  • Then, if a number occurs more than once, we find the last occurrence of that number and calculate the minimum number of operations required to remove all occurrences of that number
  • The minimum number of operations is calculated by dividing the last occurrence index by 3 and adding 1.

Complexity

  • O(n) where n is the size of the array, because we are scanning the array once to count the occurrences of each number.

Explanation

  • The code first initializes a count array `numberCnt` to keep track of the occurrences of each number in the array
  • It then scans the array from the end to the beginning and increments the count of each number in the `numberCnt` array
  • If a number occurs more than once, it updates the `lastIdx` variable to the last occurrence index of that number
  • Finally, it calculates the minimum number of operations required by dividing the `lastIdx` by 3 and adding 1, and returns this value.

Solution Code:


class Solution {
public:
    int numberCnt[101];
    int minimumOperations(vector& nums) {
        int lastIdx = -1;
        for(int i = nums.size() - 1 ; i >= 0 ; i--){
            numberCnt[nums[i]]++;
            if(numberCnt[nums[i]] >= 2){
                lastIdx = i;
                break;
            }
        }
        if(lastIdx == -1) return 0;
        return lastIdx / 3 + 1;
    }
};

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

Count the Number of Powerful Integers  (0) 2025.04.11
Minimum Operations to Make Array Values Equal to K  (0) 2025.04.10
Partition Equal Subset Sum  (0) 2025.04.08
Largest Divisible Subset  (0) 2025.04.06
Sum of All Subset XOR Totals  (0) 2025.04.05
블로그 이미지

짬뽕얼큰하게

,