304 North Cardinal St.
Dorchester Center, MA 02124

# Weekly Contest 287 LeetCode Solution

## Problem 1 – Minimum Number of Operations to Convert Time Leetcode Solution

You are given two strings `current` and `correct` representing two 24-hour times.

24-hour times are formatted as `"HH:MM"`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`.

In one operation you can increase the time `current` by `1``5``15`, or `60` minutes. You can perform this operation any number of times.

Return the minimum number of operations needed to convert `current` to `correct`.

Example 1:

``````Input: current = "02:30", correct = "04:35"
Output: 3
Explanation:
We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes "03:30".
- Add 60 minutes to current. current becomes "04:30".
- Add 5 minutes to current. current becomes "04:35".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.
``````

Example 2:

``````Input: current = "11:00", correct = "11:01"
Output: 1
Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1.``````

Constraints:

• `current` and `correct` are in the format `"HH:MM"`
• `current <= correct`

### Minimum Number of Operations to Convert Time Leetcode Solution in C++

``````int convertTime(string current, string correct) {
auto toMin = [](string &s) {
return s * 600 + s * 60 + s * 10 + s ;
};
int d = toMin(correct) - toMin(current);
return d / 60 + d % 60 / 15 + d % 15 / 5 + d % 5;
}
``````

### Minimum Number of Operations to Convert Time Leetcode Solution in Python

``````class Solution:
def convertTime(self, current: str, correct: str) -> int:
current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes
target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes
diff = target_time - current_time # Difference b/w current and target times in minutes
count = 0 # Required number of operations
# Use GREEDY APPROACH to calculate number of operations
for i in [60, 15, 5, 1]:
count += diff // i # add number of operations needed with i to count
diff %= i # Diff becomes modulo of diff with i
return count
``````

### Minimum Number of Operations to Convert Time Leetcode Solution in Java

`````` public int convertTime(String current, String correct){
Function<String, Integer> parse = t -> Integer.parseInt(t.substring(0, 2)) * 60 + Integer.parseInt(t.substring(3));
int diff = parse.apply(correct) - parse.apply(current), ops[] = {60, 15, 5, 1}, r = 0;
for(int i = 0; i < ops.length && diff > 0; diff = diff % ops[i++])
r += diff / ops[i];
return r;
}
``````

## Problem 2 – Find Players With Zero or One Losses Leetcode Solution

You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match.

Return a list `answer` of size `2` where:

• `answer` is a list of all players that have not lost any matches.
• `answer` is a list of all players that have lost exactly one match.

The values in the two lists should be returned in increasing order.

Note:

• You should only consider the players that have played at least one match.
• The testcases will be generated such that no two matches will have the same outcome.

Example 1:

``````Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output: [[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer = [1,2,10] and answer = [4,5,7,8].
``````

Example 2:

``````Input: matches = [[2,3],[1,3],[5,4],[6,4]]
Output: [[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer = [1,2,5,6] and answer = [].
``````

Constraints:

• `1 <= matches.length <= 105`
• `matches[i].length == 2`
• `1 <= winneri, loseri <= 105`
• `winneri != loseri`
• All `matches[i]` are unique.

### Find Players With Zero or One Losses Leetcode Solution in Java

`````` public List<List<Integer>> findWinners(int[][] matches){
Map<Integer, Integer> losses = new TreeMap<>();
for(int[] m : matches){
losses.put(m, losses.getOrDefault(m, 0));
losses.put(m, losses.getOrDefault(m, 0) + 1);
}
List<List<Integer>> r = Arrays.asList(new ArrayList<>(), new ArrayList<>());
for(Integer player : losses.keySet())
if(losses.get(player) <= 1)
return r;
}
``````

### Find Players With Zero or One Losses Leetcode Solution in Python

``````class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
winners, losers, table = [], [], {}
for winner, loser in matches:
# map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.
# map.get(key, 0) returns map[key] if key exists and 0 if it does not.
table[winner] = table.get(winner, 0)  # Winner
table[loser] = table.get(loser, 0) + 1
for k, v in table.items(): # Player k with losses v
if v == 0:
winners.append(k) # If player k has no loss ie v == 0
if v == 1:
losers.append(k) # If player k has one loss ie v == 1
return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.
``````

### Find Players With Zero or One Losses Leetcode Solution in C++

``````vector<vector<int>> findWinners(vector<vector<int>>& matches) {
set<int> all, l, l2;
vector<int> a0, a1;
for (auto &m : matches) {
all.insert({m, m});
if (!l.insert(m).second)
l2.insert(m);
}
set_difference(begin(all), end(all), begin(l), end(l), back_inserter(a0));
set_difference(begin(l), end(l), begin(l2), end(l2), back_inserter(a1));
return {a0, a1};
}
``````

## Problem 3 – Maximum Candies Allocated to K Children Leetcode Solution

You are given a 0-indexed integer array `candies`. Each element in the array denotes a pile of candies of size `candies[i]`. You can divide each pile into any number of sub piles, but you cannot merge two piles together.

You are also given an integer `k`. You should allocate piles of candies to `k` children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.

Return the maximum number of candies each child can get.

Example 1:

``````Input: candies = [5,8,6], k = 3
Output: 5
Explanation: We can divide candies into 2 piles of size 5 and 3, and candies into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.``````

Example 2:

``````Input: candies = [2,5], k = 11
Output: 0
Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.
``````

Constraints:

• `1 <= candies.length <= 105`
• `1 <= candies[i] <= 107`
• `1 <= k <= 1012`

### Maximum Candies Allocated to K Children Leetcode Solution in Java

``````    public int maximumCandies(int[] A, long k) {
int left = 0, right = 10_000_000;
while (left < right) {
long sum = 0;
int mid = (left + right + 1) / 2;
for (int a : A) {
sum += a / mid;
}
if (k > sum)
right = mid - 1;
else
left = mid;
}
return left;
}
``````

### Maximum Candies Allocated to K Children Leetcode Solution in C++

``````    int maximumCandies(vector<int>& A, long long k) {
int left = 0, right = 1e7;
while (left < right) {
long sum = 0, mid = (left + right + 1) / 2;
for (int& a : A) {
sum += a / mid;
}
if (k > sum)
right = mid - 1;
else
left = mid;
}
return left;
}
``````

### Maximum Candies Allocated to K Children Leetcode Solution in Python

``````    def maximumCandies(self, A, k):
left, right = 0, sum(A) / k
while left < right:
mid = (left + right + 1) / 2
if k > sum(a / mid for a in A):
right = mid - 1
else:
left = mid
return left
``````

## Problem 4 – Encrypt and Decrypt Strings Leetcode Solution

You are given a character array `keys` containing unique characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.

A string is encrypted with the following process:

1. For each character `c` in the string, we find the index `i` satisfying `keys[i] == c` in `keys`.
2. Replace `c` with `values[i]` in the string.

Note that in case a character of the string is not present in `keys`, the encryption process cannot be carried out, and an empty string `""` is returned.

A string is decrypted with the following process:

1. For each substring `s` of length 2 occurring at an even index in the string, we find an `i` such that `values[i] == s`. If there are multiple valid `i`, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.
2. Replace `s` with `keys[i]` in the string.

Implement the `Encrypter` class:

• `Encrypter(char[] keys, String[] values, String[] dictionary)` Initializes the `Encrypter` class with `keys, values`, and `dictionary`.
• `String encrypt(String word1)` Encrypts `word1` with the encryption process described above and returns the encrypted string.
• `int decrypt(String word2)` Returns the number of possible strings `word2` could decrypt to that also appear in `dictionary`.

Example 1:

``````Input
["Encrypter", "encrypt", "decrypt"]
[[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]]
Output
[null, "eizfeiam", 2]

Explanation
Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);
encrypter.encrypt("abcd"); // return "eizfeiam".
// 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am".
encrypter.decrypt("eizfeiam"); // return 2.
// "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'.
// Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd".
// 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.
``````

Constraints:

• `1 <= keys.length == values.length <= 26`
• `values[i].length == 2`
• `1 <= dictionary.length <= 100`
• `1 <= dictionary[i].length <= 100`
• All `keys[i]` and `dictionary[i]` are unique.
• `1 <= word1.length <= 2000`
• `1 <= word2.length <= 200`
• All `word1[i]` appear in `keys`.
• `word2.length` is even.
• `keys``values[i]``dictionary[i]``word1`, and `word2` only contain lowercase English letters.
• At most `200` calls will be made to `encrypt` and `decrypt` in total.

### Encrypt and Decrypt Strings Leetcode Solution in Java

``````    Map<Character, String> enc;
Map<String, Integer> count;

public Encrypter(char[] keys, String[] values, String[] dictionary) {
enc = new HashMap<>();
for (int i = 0; i < keys.length; ++i)
enc.put(keys[i], values[i]);

count = new HashMap<>();
for (String w : dictionary) {
String e = encrypt(w);
count.put(e, count.getOrDefault(e, 0) + 1);
}
}

public String encrypt(String word1) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < word1.length(); ++i)
res.append(enc.getOrDefault(word1.charAt(i), "#"));
return res.toString();
}

public int decrypt(String word2) {
return count.getOrDefault(word2, 0);
}
``````

### Encrypt and Decrypt Strings Leetcode Solution in C++

``````    unordered_map<char, string> enc;
unordered_map<string, int> count;
Encrypter(vector<char>& keys, vector<string>& values, vector<string>& dictionary) {
for (int i = 0; i < keys.size(); ++i)
enc[keys[i]] = values[i];
for (string& w: dictionary)
count[encrypt(w)]++;
}

string encrypt(string word1) {
string res = "";
for (char c: word1) {
if (!enc.count(c)) return "";
res += enc[c];
}
return res;
}

int decrypt(string word2) {
return count[word2];
}
``````

### Encrypt and Decrypt Strings Leetcode Solution in Python

``````class Encrypter(object):

def __init__(self, keys, values, dictionary):
self.enc = {k: v for k,v in zip(keys, values)}
self.decrypt = collections.Counter(self.encrypt(w) for w in dictionary).__getitem__

def encrypt(self, word1):
return ''.join(self.enc.get(c, '#') for c in word1)
``````
##### Weekly Contest 287 LeetCode Solution Review:

In our experience, we suggest you solve this Weekly Contest 287 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 287 LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Weekly Contest 287 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