Weekly Contest 276 LeetCode Solution

Problem 1 – Divide a String Into Groups of Size k Leetcode Solution

A string s can be partitioned into groups of size k using the following procedure:

  • The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.
  • For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.

Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.

Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.

Example 1:

Input: s = "abcdefghi", k = 3, fill = "x"
Output: ["abc","def","ghi"]
Explanation:
The first 3 characters "abc" form the first group.
The next 3 characters "def" form the second group.
The last 3 characters "ghi" form the third group.
Since all groups can be completely filled by characters from the string, we do not need to use fill.
Thus, the groups formed are "abc", "def", and "ghi".

Example 2:

Input: s = "abcdefghij", k = 3, fill = "x"
Output: ["abc","def","ghi","jxx"]
Explanation:
Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi".
For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.
Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters only.
  • 1 <= k <= 100
  • fill is a lowercase English letter.

Divide a String Into Groups of Size k Leetcode Solution in C++

vector<string> divideString(string s, int k, char fill) {
    vector<string> res((s.size() + k - 1) / k, string(k, fill));
    for (int i = 0; i < s.size(); ++i)
        res[i / k][i % k] = s[i];
    return res;
}

Divide a String Into Groups of Size k Leetcode Solution in Java

public String[] divideString(String str, int k, char fill) {
    
	// return if k and str are same
	if (str.length() == k)
		return new String[] { str };

	int index = 0;
	int stringLength = str.length();
	StringBuilder sb = new StringBuilder(str);
	
	// find size of array creation
	String[] strArr = (stringLength % k == 0) ? new String[stringLength / k] : new String[(stringLength / k) + 1];

	//append fill after str 
	if (stringLength % k != 0) {
		for (int i = 0; i < k - (stringLength % k); i++) {
			sb.append(fill);
		}
	}

	//divide into k
	for (int i = 0; i < sb.length(); i += k) {			
		strArr[index] = (sb.substring(i, i + k));
		++index;

	}

	return strArr;

Divide a String Into Groups of Size k Leetcode Solution in Python

def divideString(self, s: str, k: int, fill: str) -> List[str]:
        l=[]
        if len(s)%k!=0:
            s+=fill*(k-len(s)%k)
        for i in range(0,len(s),k):
            l.append(s[i:i+k])
        return l

Divide a String Into Groups of Size k Leetcode Solution in Kotlin

class Solution {
    fun divideString(s: String, k: Int, fill: Char) = s.chunked(k) {it.padEnd(k, fill).toString()}
}

Divide a String Into Groups of Size k Leetcode Solution in Python 3

class Solution:
    def divideString(self, s: str, k: int, fill: str) -> List[str]:
        return [(s+k*fill)[i:i+k] for i in range(0,len(s),k)]

Problem 2 – Minimum Moves to Reach Target Score Leetcode Solution

You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.

In one move, you can either:

  • Increment the current integer by one (i.e., x = x + 1).
  • Double the current integer (i.e., x = 2 * x).

You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.

Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.

Example 1:

Input: target = 5, maxDoubles = 0
Output: 4
Explanation: Keep incrementing by 1 until you reach target.

Example 2:

Input: target = 19, maxDoubles = 2
Output: 7
Explanation: Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19

Example 3:

Input: target = 10, maxDoubles = 4
Output: 4
Explanation: Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10

Constraints:

  • 1 <= target <= 109
  • 0 <= maxDoubles <= 100

Minimum Moves to Reach Target Score Leetcode Solution in Java

    public int minMoves(int target, int k) {
        int res = 0;
        while (target > 1 && k > 0) {   
            res += 1 + target % 2;
            k--;
            target >>= 1;
        }
        return target - 1 + res;
    }

Minimum Moves to Reach Target Score Leetcode Solution in C++

    int minMoves(int target, int k) {
        int res = 0;
        while (target > 1 && k > 0) {   
            res += 1 + target % 2;
            k--;
            target >>= 1;
        }
        return target - 1 + res;
    }

Minimum Moves to Reach Target Score Leetcode Solution in Python

    def minMoves(self, target, k):
        res = 0
        while target > 1 and k > 0:
            res += 1 + target % 2
            k -= 1
            target >>= 1
        return target - 1 + res

Problem 3 – Solving Questions With Brainpower Leetcode Solution

You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].

The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question.

  • For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:
    • If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2.
    • If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3.

Return the maximum points you can earn for the exam.

Example 1:

Input: questions = [[3,2],[4,3],[4,4],[2,5]]
Output: 5
Explanation: The maximum points can be earned by solving questions 0 and 3.
- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions
- Unable to solve questions 1 and 2
- Solve question 3: Earn 2 points
Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.

Example 2:

Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]
Output: 7
Explanation: The maximum points can be earned by solving questions 1 and 4.
- Skip question 0
- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions
- Unable to solve questions 2 and 3
- Solve question 4: Earn 5 points
Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.

Constraints:

  • 1 <= questions.length <= 105
  • questions[i].length == 2
  • 1 <= pointsi, brainpoweri <= 105

Solving Questions With Brainpower Leetcode Solution in C++

long long mostPoints(vector<vector<int>>& q) {
    long long dp[200001] = {};
    for (int i = q.size() - 1; i >= 0; --i)
        dp[i] = max(q[i][0] + dp[q[i][1] + i + 1], dp[i + 1]);
    return dp[0];
}

Solving Questions With Brainpower Leetcode Solution in Python 3

class Solution:
    def mostPoints(self, q: List[List[int]]) -> int:
        @cache
        def dfs(i: int) -> int:
            return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1]))
        return dfs(0)

Solving Questions With Brainpower Leetcode Solution in Java

    public long mostPoints(int[][] questions) {
        return getPoints(questions, 0, new long[questions.length]);
    }
    private long getPoints(int[][] q, int idx, long[] ans) {
        if (idx >= q.length) { // base cases.
            return 0;
        }else if (ans[idx] == 0) { // general case.
            int points = q[idx][0], brain = q[idx][1];
            // max points if we solve questions[i].
            long cur = points + getPoints(q, idx + 1 + brain, ans);
            // max points we can get for questions[i] 
            // (i = idx, idx + 1, ..., questions.length - 1).
            ans[idx] = Math.max(cur, getPoints(q, idx + 1, ans));
        }
        return ans[idx];
    }

Solving Questions With Brainpower Leetcode Solution in JavaScript

var mostPoints = function(questions) {
    let totalQuestions = questions.length;
    
    let map = new Map();
    
    const helper = (index) => {
        if(map.has(index))
            return map.get(index);
        
        if(index >= totalQuestions) {
            return 0;
        }  
        
        let solve = questions[index][0] + helper(index + questions[index][1] + 1);
        
        let skip = helper(index + 1);
        
        let res = Math.max(solve, skip);
        
        map.set(index, res);
        
        return res;
    }
    
    return helper(0);
	

Solving Questions With Brainpower Leetcode Solution in Python

def mostPoints(self, questions: List[List[int]]) -> int:
        n=len(questions)
        l=[x[0] for x in questions]
        maxi=0
        for i in range(n-1,-1,-1):
            if i+questions[i][1]+1>n-1:
                maxi=max(l[i],maxi)
            else:
                maxi=max(l[i]+l[i+questions[i][1]+1],maxi)
            l[i]=maxi
        return l[0]

Problem 4 – Maximum Running Time of N Computers Leetcode Solution

You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.

Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.

Note that the batteries cannot be recharged.

Return the maximum number of minutes you can run all the n computers simultaneously.

Example 1:

Input: n = 2, batteries = [3,3,3]
Output: 4
Explanation: 
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.

Example 2:

Input: n = 2, batteries = [1,1,1,1]
Output: 2
Explanation: 
Initially, insert battery 0 into the first computer and battery 2 into the second computer. 
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. 
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.

Constraints:

  • 1 <= n <= batteries.length <= 105
  • 1 <= batteries[i] <= 109

Maximum Running Time of N Computers Leetcode Solution in Java

    public long maxRunTime(int n, int[] A) {
        Arrays.sort(A);
        long sum = 0;
        for (int a: A)
            sum += a;
        int k = 0, na = A.length;
        while (A[na - 1 - k] > sum / (n - k))
            sum -= A[na - 1 - k++];
        return sum / (n - k);
    }

Maximum Running Time of N Computers Leetcode Solution in C++

    long long maxRunTime(int n, vector<int>& A) {
        sort(A.begin(), A.end());
        long long sum = accumulate(A.begin(), A.end(), 0L);
        int k = 0, na = A.size();
        while (A[na - 1 - k] > sum / (n - k))
            sum -= A[na - 1 - k++];
        return sum / (n - k);
    }

Maximum Running Time of N Computers Leetcode Solution in Python

    def maxRunTime(self, n, A):
        A.sort()
        su = sum(A)
        while A[-1] > su / n:
            n -= 1
            su -= A.pop()
        return su / n

Maximum Running Time of N Computers Leetcode Solution in Python 3

class Solution:
    def maxRunTime(self, n: int, batteries: List[int]) -> int:
        batteries.sort()
        extra = sum(batteries[:-n])
        batteries = batteries[-n:]
        
        ans = prefix = 0 
        for i, x in enumerate(batteries): 
            prefix += x 
            if i+1 < len(batteries) and batteries[i+1]*(i+1) - prefix > extra: return (prefix + extra) // (i+1)
        return (prefix + extra) // n
Weekly Contest 276 LeetCode Solution Review:

In our experience, we suggest you solve this Weekly Contest 276 LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Weekly Contest 276 LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Weekly Contest 276 LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *