Day 5 of LeetCode Challenge

Tushar PantTushar Pant
2 min read

Problem 1: Reverse Prefix Problem

Link to the problem: https://leetcode.com/problems/reverse-prefix-of-word/description/

class Solution {
    public String reversePrefix(String word, char ch) {
        int index = word.indexOf(ch);
        String substring = word.substring(0, index+1);
        substring = new StringBuilder(substring).reverse().toString();
        return substring.concat(word.substring(index+1));
    }
}

Problem 2: Minimum Operations to make arrays value equal to k

Link to the problem: https://leetcode.com/problems/minimum-operations-to-make-array-values-equal-to-k/description/

class Solution {
    public int minOperations(int[] nums, int k) {
        int ans = 0;
        for(int i=0; i<nums.length; i++){
            if(nums[i]<k)
                return -1;
            else if(nums[i]>k){
                ans++;
                for(int j=i+1; j<nums.length; j++){
                    if(nums[j]==nums[i]){
                        nums[j] = k;
                    }
                }
                nums[i] = k;
            }
        }
        return ans;
    }
}

Problem 3: Number of Beautiful Pairs

Link to the problem: https://leetcode.com/problems/number-of-beautiful-pairs/description/

class Solution {
        public int countBeautifulPairs(int[] nums) {
        int pairs = 0;
        for (int i = 0; i < nums.length; ++i) {
            int d = nums[i] % 10;
            for (int j = 0; j < i; ++j) {
                int n = nums[j];
                while (n >= 10) {
                    n /= 10;
                }
                pairs += gcd(n, d) == 1 ? 1 : 0;
            }
        }
        return pairs;
    }
    private int gcd(int x, int y) {
        while (y != 0) {
            int tmp = x % y;
            x = y;
            y = tmp;
        }
        return x;
    }
}

Problem 4: Count Distinct number on Board

Link to the problem: https://leetcode.com/problems/count-distinct-numbers-on-board/description/

class Solution {
    public int distinctIntegers(int n) {
        if (n==1)
            return 1;
        return n-1;
    }
}

Problem 5: Transpose Matrix

Link to the problem: https://leetcode.com/problems/transpose-matrix/description/

class Solution {
    public int[][] transpose(int[][] matrix) {
        int ans[][] = new int[matrix[0].length][matrix.length];
        for(int i=0; i<matrix.length; i++){
            for(int j=0; j<matrix[0].length; j++){
                ans[j][i]=matrix[i][j];
            }
        }
        return ans;
    }
}

0
Subscribe to my newsletter

Read articles from Tushar Pant directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tushar Pant
Tushar Pant