algo_input
stringlengths 240
3.91k
| solution_py
stringlengths 10
6.72k
| solution_java
stringlengths 87
8.97k
| solution_c
stringlengths 10
7.38k
| solution_js
stringlengths 10
4.56k
| title
stringlengths 3
77
|
---|---|---|---|---|---|
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i] is '(', or ')'.
| class Solution:
def longestValidParentheses(self, s: str) -> int:
maxi = 0
stack = [-1]
for i in range(len(s)) :
if s[i] == "(" : stack.append(i)
else :
stack.pop()
if len(stack) == 0 : stack.append(i)
else : maxi = max(maxi, i - stack[-1])
return maxi | class Solution {
public int longestValidParentheses(String s) {
int i=0;
int len=0;
while(i<s.length()){
int j=i;
int open=0;
int closed=0;
while(j<s.length()){
char ch = s.charAt(j);
if(ch=='(') open++;
if(ch==')') closed++;
if(closed>open) break;
if(open==closed) len=Math.max(len,j-i+1);
j++;
}
i++;
}
return len;
}
} | class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(), i = 0, ans = 0, k = 0;
for(int j = 0; j < n; j++) {
if(s[j] == '(') k++;
else if(s[j] == ')') {
k--;
if(k == 0)
ans = max(ans, j - i + 1);
}
if(k < 0) {
k = 0;
i = j + 1;
}
}
k = 0, i = n - 1;
for(int j = n - 1; j >= 0; j--) {
if(s[j] == ')') {
k++;
}
else if(s[j] == '(') {
k--;
if(k == 0)
ans = max(ans, i - j + 1);
}
if(k < 0) {
k = 0;
i = j - 1;
}
}
return ans;
}
}; | var longestValidParentheses = function(s) {
let indexStack=[-1]
let characterStack=[];
let maxLength=0;
for(let i=0;i<s.length;i++){
if(s[i]=='('){
indexStack.push(i);
characterStack.push(s[i]);
}else{
if(characterStack[characterStack.length-1]=='('){
indexStack.pop();
characterStack.pop();
if(maxLength<i-indexStack[indexStack.length-1]){
maxLength=i-indexStack[indexStack.length-1];
}
}else{
indexStack.push(i);
}
}
}
return maxLength;
}; | Longest Valid Parentheses |
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique.
| class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
solution = set()
trie = self.make_trie(words)
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
self.dfs(i,j,board,trie,visited,"",solution)
return solution
def dfs(self,i,j,board,trie,visited,word,solution):
if "*" in trie:
if len(trie.keys()) == 0:
return
else:
solution.add(word)
del trie["*"]
if (i,j) in visited:
return
if (i < 0 or i == len(board) or j < 0 or j == len(board[0])):
return
if board[i][j] not in trie:
return
if len(trie[board[i][j]]) == 0:
del trie[board[i][j]]
return
visited.add((i,j))
neighbours = [(i,j-1),(i-1,j),(i,j+1),(i+1,j)]
for n_x,n_y in neighbours:
self.dfs(n_x,n_y,board,trie[board[i][j]],visited,word+board[i][j],solution)
visited.remove((i,j))
def make_trie(self,words):
trie = {}
for word in words:
current = trie
for char in word:
if char not in current:
current[char] = {}
current = current[char]
current["*"] = "*"
return trie | class Solution {
class TrieNode {
Map<Character, TrieNode> children = new HashMap();
boolean word = false;
public TrieNode() {}
}
int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
public List<String> findWords(char[][] board, String[] words) {
Set<String> res = new HashSet<>();
TrieNode root = new TrieNode();
int m = board.length;
int n = board[0].length;
for(String word : words){
char[] cArr = word.toCharArray();
TrieNode dummy = root;
for(char c : cArr){
if(!dummy.children.containsKey(c)){
dummy.children.put(c, new TrieNode());
}
dummy = dummy.children.get(c);
}
dummy.word = true;
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
char nextChar = board[i][j];
boolean[][] visited = new boolean[m][n];
if(root.children.containsKey(nextChar)){
res.addAll(dfs(board, root.children.get(nextChar), i, j, visited, ""+nextChar));
}
}
}
return new ArrayList<>(res);
}
Set<String> dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word){
Set<String> res = new HashSet<>();
if(root.word){
res.add(word);
root.word = false;
}
visited[i][j] = true;
for(int[] dir : dirs){
int newI = i + dir[0];
int newJ = j + dir[1];
if(newI>=0 && newI<board.length && newJ>=0 && newJ<board[0].length && !visited[newI][newJ]){
char nextChar = board[newI][newJ];
if(root.children.containsKey(nextChar)){
res.addAll(dfs(board, root.children.get(nextChar), newI, newJ, visited, word+nextChar));
}
}
}
visited[i][j] = false;
return res;
}
} | class Solution {
public:
vector<string> result;
struct Trie {
Trie *child[26];
bool isEndOfWord;
string str;
Trie(){
isEndOfWord = false;
str = "";
for(int i=0; i<26; i++)
child[i] = NULL;
}
};
Trie *root = new Trie();
void insert(string &word) {
Trie *curr = root;
for(int i=0; i<word.size(); i++) {
int index = word[i]-'a';
if(!curr->child[index])
curr->child[index] = new Trie();
curr = curr->child[index];
}
curr->isEndOfWord = true;
curr->str = word;
}
void trieSearchDFS(vector<vector<char>>& board, Trie *curr, int i, int j, int row, int col) {
if(i<0 || i>row || j<0 || j>col || board[i][j] == '@')
return;
//int index = board[i][j]-'a';
curr = curr->child[board[i][j]-'a'];
if(curr == NULL)
return;
if(curr->isEndOfWord){
result.push_back(curr->str);
curr->isEndOfWord = false;
}
char ch = board[i][j];
board[i][j] = '@';
if(i-1>=0)
trieSearchDFS(board,curr,i-1,j,row,col);
if(j+1<col)
trieSearchDFS(board,curr,i,j+1,row,col);
if(i+1<row)
trieSearchDFS(board,curr,i+1,j,row,col);
if(j-1>=0)
trieSearchDFS(board,curr,i,j-1,row,col);
board[i][j] = ch;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
int row = board.size();
int col = board[0].size();
for(int i=0; i<words.size(); i++)
insert(words[i]);
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
trieSearchDFS(board,root,i,j,row,col);
}
}
return result;
}
}; | const buildTrie = (words) => {
const trie = {};
const addToTrie = (word, index = 0, node = trie) => {
const char = word[index];
if(!node[char]) {
node[char] = {};
}
if(index === word.length - 1) {
node[char].word = word;
return word;
}
return addToTrie(word, index + 1, node[char]);
};
words.map((word) => addToTrie(word));
return trie;
};
const dfs = (i, j, board, node, wordsFound = []) => {
if(i < 0 || i >= board.length) return wordsFound;
if(j < 0 || j >= board[board.length - 1].length) return wordsFound;
const char = board[i][j];
if(char === '#') return wordsFound;
if(node[char]) {
if(node[char].word) {
wordsFound.push(node[char].word);
node[char].word = null;
}
board[i][j] = '#';
dfs(i + 1, j, board, node[char], wordsFound);
dfs(i, j + 1, board, node[char], wordsFound);
dfs(i - 1, j, board, node[char], wordsFound);
dfs(i, j - 1, board, node[char], wordsFound);
board[i][j] = char;
}
return wordsFound;
};
var findWords = function(board, words) {
const m = board.length;
const n = board[m - 1].length;
const trie = buildTrie(words);
let result = [];
for(let i = 0; i < m; i += 1) {
for(let j = 0; j < n; j += 1) {
result = result.concat(dfs(i, j, board, trie));
}
}
return result;
}; | Word Search II |
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 106
| class Solution:
def countPrimes(self, n: int) -> int:
# Prerequisite:
# What is prime number. What are they just the starting.
truth = [True]*n # making a list of lenght n. And keep all the values as True.
if n<2: # as 0 & 1 are not prime numbers.
return 0
truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.
i=2 # As we know 0 & 1 are not prime.
while i*i<n: # why we are doing it as i*i here is bcz lets say 5*2 = 10 is divisble by 2 as well as 5 so if 10 is already removed why to traverse a value which is already travered once. so in case of n=5 - 5<5. CONCLUSION : i<sqrt(n)
#why we are running the loop till n is bcz question says " prime numbers that are strictly less than n".
if truth[i] == True:
for j in range(i*i,n,i): # if we have mutiple of a number in the range of n, we have to remove them as they can be prime. i.e 2 is prime, but its multiple in n = 10 are 4,6,8 they cant be prime. So we will make them false(means not a prime).
truth[j]=False
i += 1 # increasing our iterator.
return truth.count(True) # will count true value
| class Solution {
public int countPrimes(int n) {
boolean check[]=new boolean[n];int count=0;
for(int i=2;i<n;i++){
if(check[i]==false){
count++;
for(int j=i;j<n;j+=i){
check[j]=true;
}
}
}
return count;
}
} | class Solution {
public:
int countPrimes(int n) {
if(n == 0 || n == 1) return 0;
vector<bool>prime(n,true);
for(int i = 2; i*i < n; i++){
if(prime[i]){
for(int j = i*i; j < n; j += i){
prime[j] = false;
}
}
}
int cnt = 0;
for(int i = 2; i < n; i++){
if(prime[i]) cnt++;
}
return cnt;
}
}; | function makeSieve(n) {
let arr = new Array(n+1)
arr[0] = false;
arr[1] = false;
arr.fill(true,2,arr.length);
for( let i = 2; i*i<n; i++) {
if(arr[i] === true) {
for( let j = i*i ; j<=n ;j+=i){
arr[j] = false;
}
}
}
let count = 0;
for(let i = 0; i<n;i++) {
if(arr[i] == true) {
count++;
}
}
return count;
}
var countPrimes = function(n) {
let numberOfPrimes = makeSieve(n)
return numberOfPrimes;
}; | Count Primes |
You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.
Given an integer k, return the kth letter (1-indexed) in the decoded string.
Example 1:
Input: s = "leet2code3", k = 10
Output: "o"
Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Example 2:
Input: s = "ha22", k = 5
Output: "h"
Explanation: The decoded string is "hahahaha".
The 5th letter is "h".
Example 3:
Input: s = "a2345678999999999999999", k = 1
Output: "a"
Explanation: The decoded string is "a" repeated 8301530446056247680 times.
The 1st letter is "a".
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters and digits 2 through 9.
s starts with a letter.
1 <= k <= 109
It is guaranteed that k is less than or equal to the length of the decoded string.
The decoded string is guaranteed to have less than 263 letters.
| class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
idx = {}
acclens = [0]
prevd = 1
j = 0
for i, c in enumerate(S + '1'):
if c.isalpha():
idx[acclens[-1] * prevd + j] = i
j += 1
else:
acclens.append(acclens[-1] * prevd + j)
prevd = int(c)
j = 0
k = K - 1
for al in reversed(acclens[1:]):
k %= al
if k in idx:
return S[idx[k]]
return None # should never reach this | class Solution {
public String decodeAtIndex(String s, int k) {
long sz = 0;
for (char ch : s.toCharArray()){ // total length
sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;
}
--k; // make it 0 index based.
for (int i = s.length() - 1; true; i--){
if (Character.isLetter(s.charAt(i)) && --sz == k){ // found!
return ""+s.charAt(i);
}else if(Character.isDigit(s.charAt(i))){
sz /= (s.charAt(i) - '0');
k %= sz; // we are at the end of a multplied string, we can mod k with sz.
}
}
}
} | class Solution {
public:
string decodeAtIndex(string s, int k) {
k--;
struct op { string s; size_t mult; size_t total; };
vector<op> v;
size_t total = 0;
for (auto c : s) {
if (isalpha(c)) {
if (v.empty() || v.back().mult > 1)
v.push_back({"", 1, total});
v.back().s += c;
v.back().total = ++total;
} else {
size_t m = c-'0';
v.back().mult *= m;
v.back().total = total *= m;
}
if (total > k) break;
}
while (!v.empty()) {
auto [s, mult, total] = v.back();
v.pop_back();
size_t part = total / mult;
k %= part;
if (size_t i = k-part+s.size(); i < s.size())
return {s[i]};
}
return "#";
}
}; | var decodeAtIndex = function(s, k) {
let len=0;
let isDigit=false
for(let v of s){
if(v>='0'&&v<='9'){
len*=+v
isDigit=true
}else{
len++
if(len===k&&!isDigit){
return s[k-1]
}
}
}
for(let i=s.length-1;i>=0;i--){
const v=s[i]
if(v>='0'&&v<='9'){
len=Math.ceil(len/+v) // Math.floor() wont work because we endup leaving few strings
k%=len
}else{
if(k===0||k===len){
return v
}
len--
}
}
}; | Decoded String at Index |
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.
Return an integer array answer, where each answer[i] is the answer to the ith query.
Example 1:
Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j], words[i][j] consist of lowercase English letters.
| class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def _f(s):
d = Counter(s)
d =dict(sorted(d.items(), key=lambda item: item[0]))
for x in d:
return d[x]
freq = []
for w in words:
n1 = _f(w)
freq.append(n1)
freq.sort(reverse=True)
res = []
for q in queries:
n = _f(q)
c=0
for n1 in freq:
if n < n1:
c+=1
else:
break
res.append(c)
return res | class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int[] ans = new int[queries.length];
int[] freq = new int[words.length];
for (int i = 0; i < words.length; i++) {
freq[i] = freqOfSmallest(words[i]);
}
Arrays.sort(freq);
int k = 0;
for (String query : queries) {
int target = freqOfSmallest(query);
ans[k++] = binarySearch(freq, target);
}
return ans;
}
public int freqOfSmallest(String s) {
int[] freq = new int[26];
char min = 'z';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq[c - 'a'] += 1;
if (c < min) {
min = c;
}
}
return freq[min - 'a'];
}
public int binarySearch(int[] arr, int target) {
int idx = arr.length;
int lo = 0;
int hi = idx - 1;
int mid;
while (lo <= hi) {
mid = (lo + hi) / 2;
if (arr[mid] <= target) {
lo = mid + 1;
} else {
idx = mid;
hi = mid - 1;
}
}
return arr.length - idx;
}
} | class Solution {
private:
int countFreq(const string &s) {
char c = *min_element(begin(s), end(s));
return count(begin(s), end(s), c);
}
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> freqs(11, 0);
for (const auto &word : words) {
freqs[countFreq(word)]++;
}
vector<int> prefSum(12, 0);
for (int i = 0; i < freqs.size(); i++) {
prefSum[i+1] = prefSum[i] + freqs[i];
}
vector<int> ans;
for (const auto &q : queries) {
int cnt = countFreq(q);
ans.push_back(prefSum.back() - prefSum[cnt + 1]);
}
return ans;
}
}; | /**
* @param {string[]} queries
* @param {string[]} words
* @return {number[]}
*/
var numSmallerByFrequency = function(queries, words) {
let res=[]
queries=queries.map(q=>countFrequency(q))//[3,2]
words=words.map(w=>countFrequency(w))//[1,2,3,4]
words = words.sort((a, b) => a - b)
for(let i=0;i<queries.length;i++){
let start=0,end=words.length-1
while(start<=end){
let mid=start+Math.floor((end-start)/2)
if(queries[i]<words[mid]){
end=mid-1
}else{
start=mid+1
}
}
res.push(words.length-1-end)
}
return res
};
function countFrequency(str){
let freq={}
str.split('').forEach(key=>{
freq[key]=(freq[key]||0)+1
})
return freq[Object.keys(freq).sort()[0]]
} | Compare Strings by Frequency of the Smallest Character |
You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
Example 1:
Input: nums = [2,3,5]
Output: [4,3,5]
Explanation: Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
Example 2:
Input: nums = [1,4,6,8,10]
Output: [24,15,13,15,21]
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= nums[i + 1] <= 104
| from itertools import accumulate
class Solution(object):
def getSumAbsoluteDifferences(self, nums):
total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)
return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumerate(nums), list(accumulate(nums)))]
| class Solution {
public int[] getSumAbsoluteDifferences(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int sumBelow = 0;
int sumTotal = Arrays.stream(nums).sum();
for (int i = 0; i < n; i++) {
int num = nums[i];
sumTotal -= num;
res[i] = sumTotal - (n - i - 1) * num + i * num - sumBelow;
sumBelow += num;
}
return res;
}
} | class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
vector<int>ans(nums.size(),0);
for(int i = 1;i<nums.size();i++)
ans[0]+=(nums[i]-nums[0]);
for(int j = 1;j<nums.size();j++)
ans[j] = ans[j-1]+(nums[j]-nums[j-1])*j-(nums[j]-nums[j-1])*(nums.size()-j);
return ans;
}
}; | var getSumAbsoluteDifferences = function(nums) {
const N = nums.length;
const ans = new Array(N);
ans[0] = nums.reduce((a, b) => a + b, 0) - (N * nums[0]);
for (let i = 1; i < N; i++)
ans[i] = ans[i - 1] + (nums[i] - nums[i - 1]) * i - (nums[i] - nums[i - 1]) * (N - i);
return ans;
}; | Sum of Absolute Differences in a Sorted Array |
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
Constraints:
1 <= arr.length <= 105
-104 <= arr[i] <= 104
| class Solution:
def maximumSum(self, arr: List[int]) -> int:
n = len(arr)
if n ==1:
return arr[0]
dpLeft = [-10**4-1 for _ in range(n)]
dpLeft[0] = arr[0]
i = 1
while i < n :
dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])
i += 1
dpRight = [-10**4-1 for _ in range(n)]
dpRight[-1] = arr[-1]
j = n-2
while j >= 0:
dpRight[j] = max(arr[j],dpRight[j+1]+arr[j])
j -= 1
k = 0
maxi = -10**4-1
while k < n:
# if we take it
curr_maxi_with = dpRight[k] + dpLeft[k] - arr[k]
if k==0:
curr_maxi_without = dpRight[k+1]
elif k==n-1:
curr_maxi_without = dpLeft[k-1]
else:
if dpLeft[k-1]>=0 and dpRight[k+1]>=0:
curr_maxi_without = dpRight[k+1] + dpLeft[k-1]
else:
curr_maxi_without = max(dpLeft[k-1],dpRight[k+1])
maxi= max(maxi,curr_maxi_without, curr_maxi_with)
k += 1
return maxi | class Solution {
public int maximumSum(int[] arr) {
int n = arr.length;
int[] prefixSum = new int[n+1];
prefixSum[0] = 0;
int ans = (int)-1e9;
for(int i = 1; i <= n; i++){
prefixSum[i] = prefixSum[i-1] + arr[i-1];
ans = Math.max(ans, arr[i-1]);
}
if(ans < 0) return ans;
for(int i = 1; i <= n; i++){
if(arr[i-1] < 0){
int leftPrefixSum = 0;
// find max in i to 0
for(int j = i-1; j >= 0; j--){
leftPrefixSum = Math.max(leftPrefixSum, prefixSum[i-1] -prefixSum[j]);
}
int rightPrefixSum = 0;
// find max in i to n
for(int j = i+1; j <= n; j++){
rightPrefixSum = Math.max(rightPrefixSum, prefixSum[j] -prefixSum[i]);
}
ans = Math.max(ans, leftPrefixSum + rightPrefixSum);
}
}
return Math.max(ans, prefixSum[n]);
}
} | class Solution {
public:
int maximumSum(vector<int>& arr) {
int n = arr.size(), curr, maxi = INT_MIN;
vector<int> fw(n + 1, 0), bw(n + 1, 0);
fw[0] = arr[0];
maxi = max(maxi, fw[0]);
// ith element denotes the maximum subarray sum with ith element as the last element
for(int i = 1; i < n; ++i) {
curr = max(arr[i], fw[i - 1] + arr[i]);
maxi = max(maxi, curr);
fw[i] = curr;
}
// similar to fw array, but in the backward direction
bw[n - 1] = curr = arr[n - 1];
for(int i = n - 2; i >= 0; --i) {
curr = max(arr[i], bw[i + 1] + arr[i]);
maxi = max(maxi, curr);
bw[i] = curr;
}
int res = INT_MIN;
for(int i = 1; i < n - 1; ++i) {
res = max(res, fw[i - 1] + bw[i + 1]);
}
return max(res, maxi);
}
}; | /**
* @param {number[]} arr
* @return {number}
*/
// var maximumSum = function(arr) {
// const len = arr.length;
// const dp = new Array(len).fill(() => [null, null]);
// dp[0][0] = arr[0];
// dp[0][1] = 0;
// let result = arr[0];
// for(let i = 1; i < len; i++) {
// dp[i][1] = Math.max(dp[i-1][1] + arr[i], dp[i-1][0]);
// dp[i][0] = Math.max(dp[i-1][0] + arr[i], arr[i]);
// result = Math.max(result, Math.max(dp[i][0], dp[i][1]));
// }
// return result;
// };
// optimization
var maximumSum = function(arr) {
let noDelete = arr[0], oneDelete = 0, max = arr[0];
for(let i = 1; i < arr.length; i++) {
oneDelete = Math.max(oneDelete + arr[i], noDelete);
noDelete = Math.max(noDelete + arr[i], arr[i]);
max = Math.max(max, Math.max(noDelete, oneDelete));
}
return max;
}; | Maximum Subarray Sum with One Deletion |
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.
Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.
Example 1:
Input: favorite = [2,2,1,2]
Output: 3
Explanation:
The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.
All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.
Note that the company can also invite employees 1, 2, and 3, and give them their desired seats.
The maximum number of employees that can be invited to the meeting is 3.
Example 2:
Input: favorite = [1,2,0]
Output: 3
Explanation:
Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.
The seating arrangement will be the same as that in the figure given in example 1:
- Employee 0 will sit between employees 2 and 1.
- Employee 1 will sit between employees 0 and 2.
- Employee 2 will sit between employees 1 and 0.
The maximum number of employees that can be invited to the meeting is 3.
Example 3:
Input: favorite = [3,0,1,4,1]
Output: 4
Explanation:
The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.
Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.
So the company leaves them out of the meeting.
The maximum number of employees that can be invited to the meeting is 4.
Constraints:
n == favorite.length
2 <= n <= 105
0 <= favorite[i] <= n - 1
favorite[i] != i
| class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
visited_time = [0] * n
inpath = [False] * n
cur_time = 1
def get_max_len_cycle(cur) :
nonlocal cur_time
inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]
cur_time += 1
ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1
if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))
inpath[cur] = False
return ret
ret_cycle = 0
for i in range(n) :
if visited_time[i] == 0 :
ret_cycle = max(ret_cycle, get_max_len_cycle(i))
ret_not_cycle = 0
back_edge_graph = [[] for _ in range(n)]
for i in range(n) : back_edge_graph[favorite[i]].append(i)
def get_max_depth(cur) :
ret = 0
for nxt in back_edge_graph[cur] :
if favorite[cur] != nxt :
ret = max(ret, get_max_depth(nxt) + 1)
return ret
for i in range(n) :
if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1
ret = max(ret_cycle, ret_not_cycle)
return ret | class Solution {
public int maximumInvitations(int[] favorite) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < favorite.length; i++) {
graph.add(new ArrayList<>());
}
int answer = 0;
List<List<Integer>> pairs = new ArrayList<>();
for (int i = 0; i < favorite.length; i++) {
if (i == favorite[favorite[i]]) {
if (i < favorite[i]) {
List<Integer> pair = new ArrayList<>();
pair.add(i);
pair.add(favorite[i]);
pairs.add(pair);
}
} else {
graph.get(favorite[i]).add(i);
}
}
boolean[] visited = new boolean[favorite.length];
for (List<Integer> pair: pairs) {
answer += dfs(graph, pair.get(0), visited) + dfs(graph, pair.get(1), visited);
}
int[] counter = new int[favorite.length];
int[] round = new int[favorite.length];
int rnd = 1;
int circleMax = 0;
for (int i = 0; i < favorite.length; i++) {
if (visited[i]) {
continue;
}
if (round[i] != 0) {
continue;
}
int cnt = 1;
int j = i;
while (counter[j] == 0) {
counter[j] = cnt;
round[j] = rnd;
j = favorite[j];
cnt++;
}
if (round[j] == rnd) {
circleMax = Math.max(circleMax, cnt - counter[j]);
}
rnd++;
}
return Math.max(circleMax, answer);
}
private int dfs(List<List<Integer>> graph, int node, boolean[] visited) {
visited[node] = true;
int max = 0;
for (int neighbor: graph.get(node)) {
max = Math.max(max, dfs(graph, neighbor, visited));
}
return max + 1;
}
} | class Solution {
public:
vector<vector<int>> rev;
vector<int> es, sizeOfTwo;
int N, ans1, ans2;
void dfs(vector<int>& depth, int cur, int d) {
if (depth[cur] > 0) {
if (d - depth[cur] == 2) sizeOfTwo.push_back(cur);
ans1 = max(ans1, d - depth[cur]);
return;
}
if (depth[cur] != -1) return;
depth[cur] = d;
dfs(depth, es[cur], d+1);
depth[cur] = 0; // 0 means visited
}
void findAllCircules() {
vector<int> depth(N, -1);
for (int i=0; i<N; i++) {
if (depth[i] == -1) {
dfs(depth, i, 1);
}
}
}
int dfs2(int cur, int except) {
int ret = 1;
int d = 0;
for (auto nxt : rev[cur]) {
if (nxt != except) {
d = max(d, dfs2(nxt, except));
}
}
return ret + d;
}
void expandSizeOfTwo() {
for (auto i : sizeOfTwo) {
int j = es[i];
ans2 += dfs2(i, j);
ans2 += dfs2(j, i);
}
}
int maximumInvitations(vector<int>& favorite) {
es = favorite;
N = es.size(), ans1 = 0, ans2 = 0;
rev.resize(N);
for (int i=0; i<N; i++) {
rev[es[i]].push_back(i);
}
findAllCircules();
expandSizeOfTwo();
return max(ans1, ans2);
}
}; | /**
* @param {number[]} favorite
* @return {number}
*/
var maximumInvitations = function(favorite) {
let res = 0;
let len = favorite.length;
// count the number indegree
let indegree = new Array(len).fill(0);
// save the number relation
let rMap = new Map();
for(let i=0; i<favorite.length; i++){
indegree[favorite[i]] ++;
if(rMap.has(favorite[i])){
let arr = rMap.get(favorite[i]);
arr.push(i);
rMap.set(favorite[i], arr);
}else{
rMap.set(favorite[i], [i]);
}
}
// find the 0 indegree number
let arr = [];
for(let i=0; i<len; i++){
if(indegree[i] === 0){
arr.push(i);
}
}
// check if the circle exist
let search = 0;
// the length of uncircle
let l = 1;
// save the number and the length of uncircle
let lMap = new Map();
while(arr.length > 0){
let tmp = [];
for(let i=0; i<arr.length; i++){
lMap.set(arr[i], l);
let next = favorite[arr[i]];
indegree[next] --;
search ++;
if(indegree[next] === 0){
tmp.push(next);
}
}
// update the length of uncircle
l ++;
arr = [...tmp];
}
if(search === len){
// circle not exist
}else{
// circle exist
// find the not 0 indegree number
let keys = find(indegree);
// mark the search number in circle
let circleMap = new Map();
// the length of circle
let circleLen = 1;
// the max length of circle
let maxCircleLen = 0;
// sum the length of circle
let sumCircleLen = 0;
let cArr = [keys[0]];
while(cArr.length > 0){
let tmp = [];
for(let i=0; i<cArr.length; i++){
// not find the circle
if(!circleMap.has(cArr[i])){
circleMap.set(cArr[i], circleLen);
tmp.push(favorite[cArr[i]]);
// find the circle
}else{
maxCircleLen = Math.max(maxCircleLen, circleLen-1);
// if the length equals 2 then sum the length
if(circleLen-1 === 2){
let m = calc(cArr[i], rMap, lMap) + calc(favorite[cArr[i]], rMap, lMap) + 2;
sumCircleLen += m;
}
// reset the length
circleLen = 0;
// find the next number not search
for(let i=0; i<keys.length; i++){
if(!circleMap.has(keys[i])){
tmp.push(keys[i]);
break;
}
}
}
}
circleLen ++;
cArr = [...tmp];
}
res = Math.max(res, maxCircleLen, sumCircleLen);
}
return res;
};
function calc(num, rMap, lMap){
let res = 0;
let arr = rMap.has(num) ? rMap.get(num) : [];
if(arr.length > 0){
for(let i=0; i<arr.length; i++){
let l = lMap.has(arr[i]) ? lMap.get(arr[i]) : 0;
res = Math.max(res, l);
}
}
return res;
}
function find(arr){
let res = [];
for(let i=0; i<arr.length; i++){
if(arr[i] > 0){
res.push(i);
}
}
return res;
} | Maximum Employees to Be Invited to a Meeting |
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.
Example 2:
Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.
Constraints:
2 <= cookies.length <= 8
1 <= cookies[i] <= 105
2 <= k <= cookies.length
| class Solution:
def distributeCookies(self, cookies: List[int], k: int) -> int:
ans = float('inf')
fair = [0]*k
def rec(i):
nonlocal ans,fair
if i == len(cookies):
ans = min(ans,max(fair))
return
# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution
if ans <= max(fair):
return
for j in range(k):
fair[j] += cookies[i]
rec(i+1)
fair[j] -= cookies[i]
rec(0)
return ans | class Solution {
int ans;
int count[];
public int distributeCookies(int[] cookies, int k) {
ans= Integer.MAX_VALUE;
count= new int[k];
backtrack(0,cookies, k);
return ans;
}
public void backtrack(int cookieNumber, int[] cookies, int k)
{
if(cookieNumber==cookies.length)
{
int max= 0;
for(int i=0; i<k; i++)
{
max=Math.max(max, count[i]);
}
ans = Math.min(ans, max);
return;
}
for(int i=0;i<k; i++)
{
count[i]+=cookies[cookieNumber];
backtrack(cookieNumber+1, cookies, k);
count[i]-=cookies[cookieNumber];
if(count[i]==0) break;
}
}
} | class Solution {
public:
int ans = INT_MAX;
void solve(int start, vector<int>& nums, vector<int>& v, int k){
if(start==nums.size()){
int maxm = INT_MIN;
for(int i=0;i<k;i++){
maxm = max(maxm,v[i]);
}
ans = min(ans,maxm);
return;
}
for(int i=0;i<k;i++){
v[i] += nums[start];
solve(start+1,nums,v,k);
v[i] -= nums[start];
}
}
int distributeCookies(vector<int>& nums, int k) { // nums is the cookies vector
int n = nums.size();
vector<int> v(k,0); // v is to store each sum of the k subsets
solve(0,nums,v,k);
return ans;
}
}; | var distributeCookies = function(cookies, k) {
cookies.sort((a, b) => b - a);
if(k === cookies.length) return cookies[0];
const arr = new Array(k).fill(0);
let res = Infinity;
function helper(arr, cookies, level) {
if(level === cookies.length) {
const max = Math.max(...arr);
res = Math.min(res, max);
return;
}
const cookie = cookies[level];
for(let i = 0; i < arr.length; i++) {
arr[i] += cookie;
helper(arr, cookies, level + 1);
arr[i] -= cookie;
}
}
helper(arr, cookies, 0);
return res;
}; | Fair Distribution of Cookies |
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Example 1:
Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0
Example 2:
Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
row 2: 01
Example 3:
Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
row 2: 01
Constraints:
1 <= n <= 30
1 <= k <= 2n - 1
| class Solution:
def solve(self,n,k):
if n==1 and k==1:
return 0
mid = pow(2,n-1)//2
if k<=mid:
return self.solve(n-1,k)
return not self.solve(n-1,k-mid)
def kthGrammar(self,n,k):
if self.solve(n,k):
return 1
else:
return 0
| class Solution {
public int kthGrammar(int n, int k) {
if (n == 1 || k == 1) {
return 0;
}
int length = (int) Math.pow(2, n - 1);
int mid = length / 2;
if (k <= mid) {
return kthGrammar(n - 1, k);
} else if (k > mid + 1) {
return invert(kthGrammar(n - 1, k - mid));
} else {
return 1;
}
}
static int invert(int x) {
if (x == 0) {
return 1;
}
return 0;
}
} | class Solution {
public:
int kthGrammar(int n, int k) {
int kthNode = pow(2, (n-1)) + (k - 1);
vector<int>arr;
while(kthNode) {
arr.push_back(kthNode);
kthNode /= 2;
}
arr[arr.size() - 1] = 0;
for (int i = arr.size() - 2; i >= 0; i--) {
if (arr[i] % 2 == 0) {
arr[i] = arr[i+1];
}
else {
arr[i] = 1 ^ arr[i+1];
}
}
return arr[0];
}
}; | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var kthGrammar = function(n, k) {
if (n == 1 && k == 1) {
return 0;
}
const mid = Math.pow(2, n-1) / 2;
if (k <= mid) {
return kthGrammar(n-1, k);
} else {
return kthGrammar(n-1, k-mid) == 1 ? 0 : 1;
}
}; | K-th Symbol in Grammar |
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".
Example 1:
Input: senate = "RD"
Output: "Radiant"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: senate = "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in round 1.
And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Constraints:
n == senate.length
1 <= n <= 104
senate[i] is either 'R' or 'D'.
| class Solution:
def predictPartyVictory(self, senate: str) -> str:
nxt = ""
ar, de = senate.count('R'), senate.count('D')
r , d = 0, 0
while(ar and de) :
for i in senate :
if (i== 'R' and d == 0):
r += 1
nxt = nxt + 'R'
elif (i== 'R' and d > 0):
d -= 1
elif (i== 'D' and r > 0):
r -= 1
elif(i== 'D' and r == 0):
d += 1
nxt = nxt + 'D'
senate = nxt
nxt = ""
ar, de = senate.count('R'), senate.count('D')
if (ar) :
return 'Radiant'
else:
return 'Dire' | // Two Queues Solution
// Two queues to store the R index and D index.
// If the senate can execute his right, the senate is alive and can execute in the next round.
// Then we can add the senate back to the queue and process in the next round (idx + N).
// Time complexity: O(N), each loop we add/remove 1 senate in the queue.
// Space complexity: O(N)
class Solution {
public String predictPartyVictory(String senate) {
if (senate == null || senate.length() == 0) throw new IllegalArgumentException("Invalid input.");
final int N = senate.length();
Queue<Integer> queR = new ArrayDeque<>(); // store the R index
Queue<Integer> queD = new ArrayDeque<>(); // store the D index
for (int i = 0; i < N; i++) {
if (senate.charAt(i) == 'R') {
queR.add(i);
} else {
queD.add(i);
}
}
while (!queR.isEmpty() && !queD.isEmpty()) {
int r = queR.poll();
int d = queD.poll();
if (r < d) { // R is alive in the next round.
queR.add(r + N);
} else { // D is alive in the next round.
queD.add(d + N);
}
}
return queR.isEmpty() ? "Dire" : "Radiant";
}
} | class Solution {
public:
string predictPartyVictory(string senate) {
queue<int> D, R;
int len = senate.size();
for (int i = 0; i < len; i++) {
if (senate[i] == 'D') {
D.push(i);
}
else {
R.push(i);
}
}
while (!D.empty() && !R.empty()) {
int dIdx = D.front();
D.pop();
int rIdx = R.front();
R.pop();
if (dIdx < rIdx) {
D.push(dIdx + len);
}
else {
R.push(rIdx + len);
}
}
return D.empty() ? "Radiant" : "Dire";
}
}; | var predictPartyVictory = function(senate) {
let index = 0, RCount = 0, DCount = 0, deletion = false, delCount = 1;
while(delCount || index < senate.length) {
if(index >= senate.length) {
index = 0;
delCount = 0;
}
deletion = false;
if(senate.charAt(index) == 'R') {
if(DCount > 0) {
senate = senate.slice(0,index)+senate.slice(index+1);
DCount--;
index--;
deletion = true;
delCount++;
}
else {
RCount++;
}
}
else if(senate.charAt(index) == 'D') {
if(RCount > 0) {
senate = senate.slice(0,index)+senate.slice(index+1);
RCount--;
index--;
deletion = true;
delCount++;
}
else {
DCount++;
}
}
if(index == senate.length-1) {
if(senate.charAt(0) == 'R' && senate.charAt(index) == 'D' && DCount > 0 && !deletion) {
senate = senate.slice(1);
DCount--;
index = -1;
}
else if(senate.charAt(0) == 'D' && senate.charAt(index) == 'R' && RCount > 0 && !deletion) {
senate = senate.slice(1);
RCount--;
index = -1;
}
}
index++;
}
return senate.charAt(0) == 'D' ? 'Dire' : 'Radiant';
}; | Dota2 Senate |
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.
| class Solution:
def findTheDifference(self, s: str, t: str) -> str:
c = 0
for cs in s: c ^= ord(cs) #ord is ASCII value
for ct in t: c ^= ord(ct)
return chr(c) #chr = convert ASCII into character | class Solution {
public char findTheDifference(String s, String t) {
char c = 0;
for(char cs : s.toCharArray()) c ^= cs;
for(char ct : t.toCharArray()) c ^= ct;
return c;
}
} | class Solution {
public:
char findTheDifference(string s, string t) {
char c = 0;
for(char cs : s) c ^= cs;
for(char ct : t) c ^= ct;
return c;
}
}; | var findTheDifference = function(s, t) {
var map = {};
var re = "";
for(let i = 0; i < t.length; i++){
if(t[i] in map){
map[t[i]] += 1;
}else{
map[t[i]] = 1;
}
}
for(let i = 0; i < s.length; i++){
if(s[i] in map){
map[s[i]] -= 1;
}
}
for(let [key, value] of Object.entries(map)){
if(value > 0){
let temp = re.concat(key);
re = temp;
}
}
return re;
}; | Find the Difference |
You are given a string s and two integers x and y. You can perform two types of operations any number of times.
Remove substring "ab" and gain x points.
For example, when removing "ab" from "cabxbae" it becomes "cxbae".
Remove substring "ba" and gain y points.
For example, when removing "ba" from "cabxbae" it becomes "cabxe".
Return the maximum points you can gain after applying the above operations on s.
Example 1:
Input: s = "cdbcbbaaabab", x = 4, y = 5
Output: 19
Explanation:
- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.
Example 2:
Input: s = "aabbaaxybbaabb", x = 5, y = 4
Output: 20
Constraints:
1 <= s.length <= 105
1 <= x, y <= 104
s consists of lowercase English letters.
| class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a = 'a'
b = 'b'
if x < y:
x, y = y, x
a, b = b, a
seen = Counter()
ans = 0
for c in s + 'x':
if c in 'ab':
if c == b and 0 < seen[a]:
ans += x
seen[a] -= 1
else:
seen[c] += 1
else:
ans += y * min(seen[a], seen[b])
seen = Counter()
return ans | class Solution {
public int maximumGain(String s, int x, int y) {
int aCount = 0;
int bCount = 0;
int lesser = Math.min(x, y);
int result = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 'b') {
result += Math.min(aCount, bCount) * lesser;
aCount = 0;
bCount = 0;
} else if (c == 'a') {
if (x < y && bCount > 0) {
bCount--;
result += y;
} else {
aCount++;
}
} else {
if (x > y && aCount > 0) {
aCount--;
result += x;
} else {
bCount++;
};
}
}
result += Math.min(aCount, bCount) * lesser;
return result;
}
} | class Solution {
public:
int helper(string&str, char a, char b){
int count =0;
stack<char> st;
for(int i=0;i<str.length();i++) {
if(!st.empty() && str[i]==b && st.top()==a) {
st.pop();
count++;
}
else {
st.push(str[i]);
}
}
str="";
while(!st.empty()) {
str += st.top();
st.pop();
}
reverse(str.begin(),str.end());
return count;
}
int maximumGain(string s, int x, int y) {
int ca=0,cb=0;
if(x>y) {
ca = helper(s,'a','b');
cb = helper(s,'b','a');
}
else {
cb = helper(s,'b','a');
ca = helper(s,'a','b');
}
return ca*x + cb*y;
}
}; | var maximumGain = function(s, x, y) {
const n = s.length;
let totPoints = 0;
let stack;
if (x > y) {
stack = remove(s, x, "ab");
s = stack.join("");
remove(s, y, "ba");
}
else {
stack = remove(s, y, "ba");
s = stack.join("");
remove(s, x, "ab");
}
return totPoints;
function remove(str, points, match) {
const stack = [];
for (let i = 0; i < str.length; i++) {
const char = str.charAt(i);
if (stack.length > 0 && stack[stack.length - 1] + char == match) {
totPoints += points;
stack.pop();
}
else {
stack.push(char);
}
}
return stack;
}
}; | Maximum Score From Removing Substrings |
Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
Example 1:
Input: points = [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: points = [[1,1],[2,2],[3,3]]
Output: false
Constraints:
points.length == 3
points[i].length == 2
0 <= xi, yi <= 100
| class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
a,b,c=points
return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0]) | class Solution {
public boolean isBoomerang(int[][] points) {
double a, b, c, d, area;
a=points[0][0]-points[1][0];
b=points[1][0]-points[2][0];
c=points[0][1]-points[1][1];
d=points[1][1]-points[2][1];
area=0.5*((a*d)-(b*c));
return area!=0;
}
} | class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
if (points.size()<=2) return false;
int x0=points[0][0], y0=points[0][1];
int x1=points[1][0], y1=points[1][1];
int x2=points[2][0], y2=points[2][1];
int dx1=x1-x0, dy1=y1-y0;
int dx2=x2-x1, dy2=y2-y1;
if (dy1*dx2==dy2*dx1) return false;
return true;
}
}; | var isBoomerang = function(points) {
// if any two of the three points are the same point return false;
if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) return false;
if (points[0][0] == points[2][0] && points[0][1] == points[2][1]) return false;
if (points[2][0] == points[1][0] && points[2][1] == points[1][1]) return false;
// if the points are in a straight line return false;
let slope1 = (points[0][1] - points[1][1]) / (points[0][0] - points[1][0]);
let slope2 = (points[1][1] - points[2][1]) / (points[1][0] - points[2][0]);
if (points[0][0] == points[1][0] && points[0][0] === points[2][0]) return false;
if (points[0][1] == points[1][1] && points[0][1] === points[2][1]) return false;
if (slope1 === slope2) return false;
return true;
}; | Valid Boomerang |
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\' is represented as '\\'.
Example 1:
Input: grid = [" /","/ "]
Output: 2
Example 2:
Input: grid = [" /"," "]
Output: 1
Example 3:
Input: grid = ["/\\","\\/"]
Output: 5
Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.
Constraints:
n == grid.length == grid[i].length
1 <= n <= 30
grid[i][j] is either '/', '\', or ' '.
| class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n=len(grid)
dots=n+1
par=[0]*(dots*dots)
rank=[0]*(dots*dots)
self.count=1
def find(x):
if par[x]==x:
return x
temp=find(par[x])
par[x]=temp
return temp
def union(x,y):
lx=find(x)
ly=find(y)
if lx!=ly:
if rank[lx]>rank[ly]:
par[ly]=lx
elif rank[lx]<rank[ly]:
par[lx]=ly
else:
par[lx]=ly
rank[ly]+=1
else:
self.count+=1
#-------------------------------------------#
for i in range(len(par)):
par[i]=i
rank[i]=1
for i in range(dots):
for j in range(dots):
if i==0 or j==0 or i==dots-1 or j==dots-1:
cellno=i*dots+j
if cellno!=0:
union(0,cellno)
for i in range(len(grid)):
ch=grid[i]
for j in range(len(ch)):
if ch[j]=='/':
cellno1=i*dots+j+1
cellno2=(i+1)*dots+j
union(cellno1,cellno2)
elif ch[j]=='\\':
cellno1=i*dots+j
cellno2=(i+1)*dots+j+1
union(cellno1,cellno2)
return self.count | class Solution {
int[] parent;
int[] rank;
public int regionsBySlashes(String[] grid) {
parent = new int[4*grid.length*grid.length];
rank = new int[4*grid.length*grid.length];
for(int i=0;i<parent.length;i++){
parent[i] = i;
rank[i] = 0;
}
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length();j++){
char ch = grid[i].charAt(j);
int bno = i * grid.length + j;
if(ch != '/'){
unionHelper(4*bno + 0 , 4*bno + 1);
unionHelper(4*bno + 2, 4*bno + 3);
}
if(ch != '\\'){
unionHelper(4*bno + 0 , 4*bno + 3);
unionHelper(4*bno + 1, 4*bno + 2);
}
if(i > 0){
int obno = (i-1) * grid.length + j;
unionHelper(4*bno + 0 , 4*obno + 2);
}
if(j > 0){
int obno = i * grid.length + (j-1);
unionHelper(4*bno + 3 , 4*obno + 1);
}
}
}
int count = 0;
for(int i=0;i<parent.length;i++){
if(parent[i] == i){
count++;
}
}
return count;
}
public int find(int x){
if(parent[x] == x){
return parent[x];
}else{
parent[x] = find(parent[x]);
return parent[x];
}
}
public void union(int xl,int yl){
if(rank[xl] < rank[yl]){
parent[xl] = yl;
}else if(rank[yl] < rank[xl]){
parent[yl] = xl;
}else{
parent[xl] = yl;
rank[yl]++;
}
}
public void unionHelper(int x,int y){
int xl = find(x);
int yl = find(y);
if(xl != yl){
union(xl,yl);
}
}
} | /*
Convert grid to 3*n X 3*n grid where eacah of the cell is upscalled to 3x3 grid
and then map the diagonal to 0 or 1 depending on '/' or '\' type in the grid.
Example:
["/\\","\\/"] this can be converted to following scaled grid:
1 1 0 0 1 1
1 0 1 1 0 1
0 1 1 1 1 0
0 1 1 1 1 0
1 0 1 1 0 1
1 1 0 0 1 1
Once this conversion is done, then its simple island count problem, run dfs from each cell
to visit all cells and count number of times dfs is started and return it as answer.
*/
class Solution {
public:
int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
void dfs(vector<vector<int>>& g, vector<vector<int>>& vis, int i, int j){
for(int d = 0; d<4; ++d){
int x = i + dir[d][0];
int y = j + dir[d][1];
if( x >= 0 && y >= 0 && x < g.size() && y < g.size() &&
vis[x][y] == -1 && g[x][y] == 1){
vis[x][y] = 1;
dfs(g, vis, x, y);
}
}
}
int regionsBySlashes(vector<string>& grid) {
int n = grid.size();
vector<vector<int>> g(3*n, vector<int> (3*n, 1));
for(int i = 0; i < n; ++i){
for(int j = 0; j< n; ++j){
if(grid[i][j] == '\\'){
for(int k = 0; k < 3; ++k) g[3*i+k][3*j+k] = 0;
}
else if(grid[i][j] == '/'){
for(int k = 0; k < 3; ++k) g[3*i+k][3*j+ 2-k] = 0;
}
}
}
int count = 0;
vector<vector<int>> vis(3*n, vector<int> (3*n, -1));
for(int i = 0; i < 3*n; ++i){
for(int j = 0; j < 3*n; ++j){
if(vis[i][j] == -1 && g[i][j] == 1){ //cout<<i<<" "<<j<<endl;
count++;
vis[i][j] = 1;
dfs(g, vis, i, j);
}
}
}
return count;
}
}; | // this is a very common disjoint set implement
function DS(n) {
var root = [...new Array(n).keys()];
var rank = new Array(n).fill(0);
this.find = function(v) {
if (root[v] !== v) root[v] = this.find(root[v]);
return root[v];
}
this.union = function(i, j) {
var [ri, rj] = [this.find(i), this.find(j)];
if (ri === rj) return;
if (rank[ri] > rank[rj]) root[rj] = ri;
else if (rank[ri] < rank[rj]) root[ri] = rj;
else root[ri] = rj, rank[rj]++;
}
// get how many unique unions
this.getUnoinCount = function() {
for (var i = 0; i < n; i++) this.find(i);
return new Set(root).size;
}
}
function getKeys(i, j, n) {
var val = i * n + j;
val *= 2;
// left and right part key of grid[i][j]
return [val, val + 1];
}
/**
* @param {string[]} grid
* @return {number}
*/
var regionsBySlashes = function(grid) {
var n = grid.length;
if (n === 1) return grid[0][0] === ' ' ? 1 : 2;
var ds = new DS(n * n * 2);
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
var [left, right] = getKeys(i, j, n);
// When this cell is ' ', union left and right.
if (grid[i][j] === ' ') ds.union(left, right);
// if have upper neighbor
if (i !== 0) {
var [upLeft, upRight] = getKeys(i - 1, j, n);
// For upper neighbor, if it's '/', we should choose right part to union, if '\', choose left.
var upKey = grid[i - 1][j] === '\\' ? upLeft : upRight;
// For current cell, if it's '/', we should choose left part to union, if '\', choose right.
var curKey = grid[i][j] === '/' ? left : right;
ds.union(upKey, curKey);
}
// if have left neighbor
if (j !== 0) {
var [leftLeft, leftRight] = getKeys(i, j - 1, n);
// just choose the right part of the left neighbor
var leftKey = leftRight;
// just choose the left part of the current cell
var curKey = left;
ds.union(leftKey, curKey);
}
}
}
return ds.getUnoinCount();
}; | Regions Cut By Slashes |
You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
Example 2:
Input: s = "12345678"
Output: 1
Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
Constraints:
1 <= s.length <= 105
s consists only of digits.
| from collections import defaultdict
class Solution:
def longestAwesome(self, s: str) -> int:
mask = 0
index = defaultdict(lambda:float('-inf'),{0:-1})
res = 0
for i,c in enumerate(s):
mask ^= (1<<(ord(c)-ord('0')))
if index[mask] == float('-inf'):
index[mask] = i
res = max(res, i-index[mask])
#when the palindrome has one odd numbers of digits
for j in range(10):
tmp_mask = mask^(1<<j)
res = max(res, i-index[tmp_mask] if index[tmp_mask] != float('-inf') else 0)
return res | class Solution {
public int longestAwesome(String s) {
Map<Integer,Integer>map=new HashMap<>();
map.put(0,-1);
int state=0;
int ans=0;
for(int i=0;i<s.length();i++){
int bit=(1<<(s.charAt(i)-'0'));
state ^=bit; //if odd freq then it becomes even or if even becomes odd
if(map.containsKey(state))
ans=Math.max(ans,i-map.get(state));
for(int odd=0;odd<=9;odd++){ //become odds one by one
int mask=(1<<odd);
Integer j=map.get(state^mask);
if(j!=null)
ans=Math.max(ans,i-j);
}
if(!map.containsKey(state))
map.put(state,i);
}
return ans;
}
} | class Solution {
public:
int longestAwesome(string s) {
unordered_map<int,int> map;
int mask = 0, maxL = 0;
map[mask] = -1;
for(int i=0; i<s.size(); ++i){
int ch = s[i]-'0';
mask^= (1<<ch);
if(map.find(mask) != map.end()){
maxL = max(maxL, i-map[mask]);
}
for(int x=0; x<=9; ++x){
int newMask = mask^(1<<x);
if(map.find(newMask) != map.end()){
maxL = max(maxL, i-map[newMask]);
}
}
if(map.find(mask) == map.end()){
map[mask] = i;
}
}
return maxL;
}
}; | var longestAwesome = function(s) {
// freq starts with 0:0 because 9 0s is also a state and if I come across a
// 0 down the road, that means that the whole array up to index i is of the required type
let firstIndex={0:0}, result=-1, curr=0
for (let i = 0; i < s.length; i++) {
curr^= 1<<s[i]
// Check if you have seen curr^0=curr before,
// because that would make the inbetween elements' xor = 000000000
if(firstIndex[curr]!==undefined)
result=Math.max(result,i-firstIndex[curr]+1)
// Check all the other xors, because that would make
// the inbetween elements of the required type (100000000,010000000,......,000000001)
for (let j = 0; j <10; j++) {
let ele=1<<j
if(firstIndex[curr^ele]!==undefined)
//i-firstIndex[curr^ele] because on freq I saved
//the smallest index where I last met curr^ele
result=Math.max(result,i-firstIndex[curr^ele]+1)
}
if(firstIndex[curr]===undefined)
firstIndex[curr]=i+1// +1 cos 0th place is for my 0 state
}
return result
}; | Find Longest Awesome Substring |
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.
Example 1:
Input: label = 14
Output: [1,3,4,14]
Example 2:
Input: label = 26
Output: [1,2,6,10,26]
Constraints:
1 <= label <= 10^6
| class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
result = [label]
#determine level of label
#O(log n)
level, nodeCount = 1, 1
while label >= nodeCount * 2:
nodeCount *= 2
level += 1
#Olog(n) time
while label > 1:
#compute max and min node
maxNode, minNode = 2**level-1, 2**(level-1)
parent = ((maxNode + minNode) - label) // 2
#slightly costly operation
result = [parent] + result
label = parent
level -= 1
return result | class Solution {
public List<Integer> pathInZigZagTree(int label)
{
int level, upper, parent, i = label;
double min, max;
List<Integer> ans = new ArrayList<Integer> ();
ans.add(i);
while( i> 1)
{
level = (int)(Math.log(i) / Math.log(2));
upper = level -1;
min = Math.pow(2.0, upper);
max = Math.pow(2.0, level) - 1;
parent = (int)(min + max) - i/2;
ans.add(0, parent);
i = parent;
}
return ans;
}
} | class Solution
{
public:
vector<int> pathInZigZagTree(int label)
{
vector<int> v;
int n = 0, num = label;
while (label)
{
n++;
label = label >> 1;
}
int l, r, c, ans;
for (int i = n; i >= 2; i--)
{
r = pow(2, i) - 1;
l = pow(2, i - 1);
c = r - num;
ans = l + c;
if ((n + i) % 2)
{
v.push_back(ans);
}
else
{
v.push_back(num);
}
num /= 2;
}
v.push_back(1);
sort(v.begin(), v.end());
return v;
}
}; | var pathInZigZagTree = function(label) {
//store highest and lowest value for each level
let levels = [[1,1]] //to reduce space complexity we will fill the levels array with out output as we go
let totalNodes = 1
let nodesInLastRow = 1
//Calculate which level the label lies in
while (totalNodes < label) {
let lowest = totalNodes + 1
nodesInLastRow = nodesInLastRow * 2
totalNodes += nodesInLastRow
let highest = totalNodes
levels.push([lowest, highest])
}
let index = levels.length
let childBoundaries = levels[levels.length -1]
levels[levels.length -1] = label
//Work bottom up, for each level, calculate the value based on the child and the child boundaries boundaries
for (let i=levels.length-2; i>=0; i--) {
let childLevel = i+2 //2 because i is index of 0, so 1 is to preset it to 1...n and then and second one is parent level
let childValue = levels[i+1]
let inversionCalculation = Math.abs((childBoundaries[0] + childBoundaries[1]) - childValue)
childBoundaries = levels[i]
levels[i] = Math.floor(inversionCalculation/2)
}
return levels
}; | Path In Zigzag Labelled Binary Tree |
Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i] consists of lowercase English letters.
| class Solution:
def longestWord(self, words: List[str]) -> str:
TrieNode = lambda: defaultdict(TrieNode)
root = TrieNode()
for i,s in enumerate(words):
cur = root
for c in s: cur=cur[c]
cur['$']=i
ans = ''
st = list(root.values())
while st:
cur = st.pop()
if '$' in cur:
w = words[cur['$']]
if len(ans)<len(w) or len(ans)==len(w) and w<ans:ans=w
st.extend([cur[i] for i in cur if i!='$'])
return ans | class Solution {
private class Node{
Node[] sub;
Node(){
sub = new Node[26];
}
}
Node root;
StringBuilder ans;
private void buildTire(String word){
Node temp = root;
int n = word.length();
for(int i = 0; i < n-1; i++){
int index = word.charAt(i)-'a';
if(temp.sub[index] == null) return;
temp = temp.sub[index];
}
int index = word.charAt(n-1)-'a';
temp.sub[index] = new Node();
if(word.length() > ans.length())
ans = new StringBuilder(word);
}
public String longestWord(String[] words) {
this.ans = new StringBuilder();
this.root = new Node();
PriorityQueue<String> pq = new PriorityQueue<>();
pq.addAll(Arrays.asList(words));
while(!pq.isEmpty()) buildTire(pq.poll());
return ans.toString();
}
} | struct node{
int end=0;
node* adj[26];
};
class Solution {
public:
string longestWord(vector<string>& words) {
auto root = new node();
auto insert = [&](string&s, int ind){
node* cur = root;
int i;
for(char&c:s){
i=c - 'a';
if(!cur->adj[i])cur->adj[i] = new node();
cur=cur->adj[i];
}
cur->end=ind;
};
int ind = 0;
for(string&s : words) insert(s,++ind);
stack<node*> st;
st.push(root);
string ans = "";
while(!st.empty()){
node* cur = st.top();st.pop();
if(cur->end>0 || cur==root){
if(cur!=root){
string word = words[cur->end-1];
if(word.size()>ans.size() ||
(word.size()==ans.size() && word<ans)){ans = word;}
}
for(int j=0;j<26;j++)
if(cur->adj[j])st.push(cur->adj[j]);
}
}
return ans;
}
}; | var longestWord = function(words) {
words.sort();
let trie = new Trie();
let result = ""
for (const word of words) {
if (word.length === 1) {
trie.insert(word);
result = word.length > result.length ? word : result;
} else {
let has = trie.search(word.slice(0, word.length-1));
if (has) {
trie.insert(word);
result = word.length > result.length ? word : result;
}
}
}
return result;
}; | Longest Word in Dictionary |
You are given an integer array nums. The adjacent integers in nums will perform the float division.
For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.
Return the corresponding expression that has the maximum value in string format.
Note: your expression should not contain redundant parenthesis.
Example 1:
Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation:
1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant, since they don't influence the operation priority. So you should return "1000/(100/10/2)".
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
Example 2:
Input: nums = [2,3,4]
Output: "2/(3/4)"
Example 3:
Input: nums = [2]
Output: "2"
Constraints:
1 <= nums.length <= 10
2 <= nums[i] <= 1000
There is only one optimal division for the given iput.
| class Solution(object):
def optimalDivision(self, nums):
A = list(map(str, nums))
if len(A) <= 2:
return '/'.join(A)
return A[0] + '/(' + '/'.join(A[1:]) + ')' | class Solution {
public String optimalDivision(int[] nums) {
if(nums.length==1){
return nums[0] + "";
}else if(nums.length==2){
StringBuilder sb=new StringBuilder();
sb.append(nums[0] + "/" + nums[1]);
return sb.toString();
}
StringBuilder sb=new StringBuilder();
sb.append(nums[0]);
sb.append("/(");
for(int i=1;i<nums.length-1;i++){
sb.append(nums[i] + "/");
}
sb.append(nums[nums.length-1] + ")");
return sb.toString();
}
} | class Solution {
public:
string optimalDivision(vector<int>& nums) {
string s="";
if(nums.size()==1)
return to_string(nums[0]);
if(nums.size()==2)
return to_string(nums[0])+'/'+to_string(nums[1]);
for(int i=0;i<nums.size();i++)
{
s+=to_string(nums[i])+"/";
if(i==0)
s+="(";
}
s[s.size()-1]=')';
return s;
}
}; | var optimalDivision = function(nums) {
const { length } = nums;
if (length === 1) return `${nums[0]}`;
if (length === 2) return nums.join('/');
return nums.reduce((result, num, index) => {
if (index === 0) return `${num}/(`;
if (index === length - 1) return result + `${num})`;
return result + `${num}/`;
}, '');
}; | Optimal Division |
Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "abcde", words = ["a","bb","acd","ace"]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Example 2:
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
Output: 2
Constraints:
1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
s and words[i] consist of only lowercase English letters.
| class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
word_dict = defaultdict(list)
numMatch = 0
# add words into bucket with key as order of the first letter
for w in words:
word_dict[ord(w[0])-ord('a')].append(w)
# loop through the characters in s
for c in s:
qualified = word_dict[ord(c)-ord('a')]
word_dict[ord(c)-ord('a')] = []
for q in qualified:
# if the word starts with the specified letter. i.e this is the last letter of the word
if len(q) == 1:
numMatch += 1
else:
word_dict[ord(q[1])-ord('a')].append(q[1:])
return numMatch | class Solution {
public int numMatchingSubseq(String s, String[] words) {
int count = 0;
Map<String, Integer> map = new HashMap<>();
for(String word : words){
if(!map.containsKey(word)){
map.put(word, 1);
}
else{
map.put(word, map.get(word)+1);
}
}
for(String word : map.keySet()){
if(isSeq(word, s)){
count += map.get(word);
}
}
return count;
}
public boolean isSeq(String s1, String s2){
int s1ind = 0;
int s2ind = 0;
int counter = 0;
if(s1.length() > s2.length()){
return false;
}
while(s1ind < s1.length() && s2ind < s2.length()){
if(s1.charAt(s1ind) == s2.charAt(s2ind)){
counter++;
s1ind++;
s2ind++;
}
else{
s2ind++;
}
}
return counter == s1.length();
}
} | class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words) {
int ct=0;
unordered_map<string,int>m;
for(int i=0;i<words.size();i++)
{
m[words[i]]++;
}
for(auto it=m.begin();it!=m.end();it++)
{
string k=it->first;
int z=0;
for(int i=0;i<s.length();i++)
{
if(s[i]==k[z])
z++;
else if(z==k.length())
break;
}
if(z==k.length())
ct=ct+it->second;
}
return ct;
}
}; | var numMatchingSubseq = function(s, words) {
let subsequence = false;
let count = 0;
let prevIdx, idx
for(const word of words) {
prevIdx = -1;
idx = -1;
subsequence = true;
for(let i = 0; i < word.length; i++) {
idx = s.indexOf(word[i], idx + 1);
if(idx > prevIdx) {
prevIdx = idx;
} else {
subsequence = false;
break;
}
}
if(subsequence) count++;
}
return count;
}; | Number of Matching Subsequences |
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".
Example 2:
Input: words = ["leetcode","win","loops","success"], pref = "code"
Output: 0
Explanation: There are no strings that contain "code" as a prefix.
Constraints:
1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i] and pref consist of lowercase English letters.
| class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return sum(word.find(pref) == 0 for word in words) | class Solution {
public int prefixCount(String[] words, String pref) {
int c = 0;
for(String s : words) {
if(s.indexOf(pref)==0)
c++;
}
return c;
}
} | class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int c=0;
for(auto word:words){
int b=0;
for(int i=0;i<pref.size();i++){
if(word[i]!=pref[i]){
break;
}else{
b++;
}
}
if(b==pref.size()){
c++;
}
}
return c;
}
}; | var prefixCount = function(words, pref) {
return words.filter(word => word.slice(0, pref.length) === pref).length;
}; | Counting Words With a Given Prefix |
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located on the fence perimeter.
Example 1:
Input: points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[3,3],[2,4],[4,2]]
Example 2:
Input: points = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]
Constraints:
1 <= points.length <= 3000
points[i].length == 2
0 <= xi, yi <= 100
All the given points are unique.
| class Solution:
"""Compute the convex hull of a set of points.
Use Andrew's Monotone Chain algorithm, which has order O(N log(N)),
where N is the number of input points.
"""
def cross(self, p, a, b):
"""Return the cross product of the vectors p -> a and p -> b."""
return (a[0] - p[0]) * (b[1] - p[1]) \
- (a[1] - p[1]) * (b[0] - p[0])
def _convex_hull_monotone_chain(self, points):
"""Compute the convex hull of a list of points.
Use Andrew's Monotone Chain algorithm, which is similar to Graham Scan,
except that it doesn't require sorting the points by angle. This algorithm
takes O(N log(N)) time, where N is len(points).
"""
# Ensure all points are unique, and sort lexicographically.
points = list(sorted(set(points)))
# If there are fewer than three points, they must form a hull.
if len(points) <= 2:
return points
# Compute the lower and upper portion of the hull.
lower, upper = [], []
for out, it in ((lower, points), (upper, reversed(points))):
for p in it:
while len(out) >= 2 and self.cross(out[-2], out[-1], p) > 0:
out.pop()
out.append(p)
# Concatenate the upper and lower hulls. Remove the last point from each
# because those points are duplicated in both upper and lower.
return lower[:-1] + upper[:-1]
def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
"""
Find the convex hull of a collection of points.
Return a list of indices of points forming the hull in clockwise order,
starting with the leftmost point.
"""
# Convert input points to tuples.
points = [tuple(p) for p in trees]
ans = set()
for point in self._convex_hull_monotone_chain(points):
ans.add(point)
return ans | class Solution {
public static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public int[][] outerTrees(int[][] trees) {
List<Pair> points=new ArrayList<>();
for(int[] point:trees){
points.add(new Pair(point[0],point[1]));
}
List<Pair> res=new ArrayList<>();
if(points.size()==1){
return trees;
}
int n=points.size();
Collections.sort(points,(a,b)->a.y==b.y?a.x-b.x:a.y-b.y);
HashSet<ArrayList<Integer>> dup=new HashSet<>();
Stack<Pair> hull=new Stack<>();
hull.push(points.get(0));
hull.push(points.get(1));
for(int i=2;i<n;i++){
Pair top=hull.pop();
while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){
top=hull.pop();
}
hull.push(top);
hull.push(points.get(i));
}
for(int i=n-2;i>=0;i--){
Pair top=hull.pop();
while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){
top=hull.pop();
}
hull.push(top);
hull.push(points.get(i));
}
for(Pair p:hull){
ArrayList<Integer> tmp=new ArrayList<>();
tmp.add(p.x);
tmp.add(p.y);
if(dup.contains(tmp))continue;
dup.add(tmp);
res.add(p);
}
int[][] ans=new int[res.size()][2];
int i=0;
for(Pair p:res){
ans[i][0]=p.x;
ans[i][1]=p.y;
i++;
}
return ans;
}
public int ccw(Pair a,Pair b,Pair c){
double cp=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
if(cp<0)return -1;
else if(cp>0)return 1;
else return 0;
}
} | class Solution {
public:
vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
if (trees.size() <= 1) return trees;
int origin = 0;
for (int i = 0; i < trees.size(); ++i) {
if (trees[origin][1] > trees[i][1] || trees[origin][1] == trees[i][1] && trees[origin][0] > trees[i][0]) {
origin = i;
}
}
swap(trees[0], trees[origin]);
sort(trees.begin() + 1, trees.end(), [&](const vector<int>& lhs, const vector<int>& rhs) -> bool {
int result = cross(trees[0], lhs, rhs);
if (result != 0) return result > 0;
return norm(trees[0], lhs) < norm(trees[0], rhs);
});
// deal with cases that the last k points are on one line
int pos = trees.size() - 2;
while (pos > 0 && cross(trees[0], trees.back(), trees[pos]) == 0) {
--pos;
}
reverse(trees.begin() + pos + 1, trees.end());
vector<vector<int>> ans = {trees[0], trees[1]};
for (int i = 2; i < trees.size(); ++i) {
int cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);
while (cross_result < 0) {
ans.pop_back();
cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);
}
ans.push_back(trees[i]);
}
return ans;
}
private:
inline double norm(const vector<int>& o, const vector<int>& x) {
int xx = x[0] - o[0];
int yy = x[1] - o[1];
return sqrt(xx * xx + yy * yy);
}
inline int cross(const vector<int>& x, const vector<int>& y, const vector<int>& z) {
return (y[0] - x[0]) * (z[1] - y[1]) - (y[1] - x[1]) * (z[0] - y[0]);
}
}; | const outerTrees = (trees) => {
trees.sort((x, y) => {
if (x[0] == y[0]) return x[1] - y[1];
return x[0] - y[0];
});
let lower = [], upper = [];
for (const tree of trees) {
while (lower.length >= 2 && cmp(lower[lower.length - 2], lower[lower.length - 1], tree) > 0) lower.pop();
while (upper.length >= 2 && cmp(upper[upper.length - 2], upper[upper.length - 1], tree) < 0) upper.pop();
lower.push(tree);
upper.push(tree);
}
return [...new Set(lower.concat(upper))];
};
const cmp = (p1, p2, p3) => {
let [x1, y1] = p1;
let [x2, y2] = p2;
let [x3, y3] = p3;
return (y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2);
}; | Erect the Fence |
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Constraints:
1 <= columnTitle.length <= 7
columnTitle consists only of uppercase English letters.
columnTitle is in the range ["A", "FXSHRXW"].
| def let_to_num(char):
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return abc.index(char) + 1
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans = 0
for i in range(len(columnTitle)):
ans *= 26
ans += let_to_num(columnTitle[i])
return ans | class Solution {
public int titleToNumber(String columnTitle) {
int n = columnTitle.length();
int pow = 0;
int res = 0;
for(int i = n-1; i >= 0; i--) {
char c = columnTitle.charAt(i);
res += (c - 64) * Math.pow(26, pow);
pow++;
}
return res;
}
} | // 😉😉😉😉Please upvote if it helps 😉😉😉😉
class Solution {
public:
int titleToNumber(string columnTitle) {
int result = 0;
for(char c : columnTitle)
{
//d = s[i](char) - 'A' + 1 (we used s[i] - 'A' to convert the letter to a number like it's going to be C)
int d = c - 'A' + 1;
result = result * 26 + d;
}
return result;
}
}; | /**
* @param {string} columnTitle
* @return {number}
*/
var titleToNumber = function(columnTitle) {
/*
one letter: result between 1-26.
two letter: result between 26^1 + 1 -> 26^2 + digit. 27 - 702. All the combinations of A-Z and A-Z.
*/
let sum = 0;
for (let letter of columnTitle) {
let d = letter.charCodeAt(0) - 'A'.charCodeAt(0) + 1;
sum = sum * 26 + d;
}
return sum;
}; | Excel Sheet Column Number |
Write an API that generates fancy sequences using the append, addAll, and multAll operations.
Implement the Fancy class:
Fancy() Initializes the object with an empty sequence.
void append(val) Appends an integer val to the end of the sequence.
void addAll(inc) Increments all existing values in the sequence by an integer inc.
void multAll(m) Multiplies all existing values in the sequence by an integer m.
int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.
Example 1:
Input
["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]
[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]
Output
[null, null, null, null, null, 10, null, null, null, 26, 34, 20]
Explanation
Fancy fancy = new Fancy();
fancy.append(2); // fancy sequence: [2]
fancy.addAll(3); // fancy sequence: [2+3] -> [5]
fancy.append(7); // fancy sequence: [5, 7]
fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]
fancy.getIndex(0); // return 10
fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]
fancy.append(10); // fancy sequence: [13, 17, 10]
fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]
fancy.getIndex(0); // return 26
fancy.getIndex(1); // return 34
fancy.getIndex(2); // return 20
Constraints:
1 <= val, inc, m <= 100
0 <= idx <= 105
At most 105 calls total will be made to append, addAll, multAll, and getIndex.
| def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
return x % m
mod = 1000000007
class Fancy(object):
def __init__(self):
self.seq = []
self.addC = 0
self.mulC = 1
def append(self, val):
"""
:type val: int
:rtype: None
"""
self.seq.append([val, self.mulC, self.addC])
def addAll(self, inc):
"""
:type inc: int
:rtype: None
"""
self.addC = (self.addC%mod + inc%mod)%mod
def multAll(self, m):
"""
:type m: int
:rtype: None
"""
self.mulC = (self.mulC%mod * m%mod)%mod
self.addC = (self.addC%mod * m%mod)%mod
def getIndex(self, idx):
"""
:type idx: int
:rtype: int
"""
if(idx >= len(self.seq)):
return -1
mulCo = self.seq[idx][1]
addCo = self.seq[idx][2]
val = self.seq[idx][0]
inv = modinv(mulCo, mod)
a = (self.mulC%mod * inv%mod)%mod
val = (val%mod * a%mod)%mod
b = (addCo%mod * a%mod)%mod
val = (val%mod - b%mod)%mod
val = (val%mod + self.addC%mod)%mod
return val | class Fancy {
private ArrayList<Long> lst;
private ArrayList<Long> add;
private ArrayList<Long> mult;
private final long MOD = 1000000007;
public Fancy() {
lst = new ArrayList<>();
add = new ArrayList<>();
mult = new ArrayList<>();
add.add(0L);
mult.add(1L);
}
public void append(int val) {
lst.add((long) val);
int l = add.size();
add.add(add.get(l - 1));
mult.add(mult.get(l - 1));
}
public void addAll(int inc) {
int l = add.size();
add.set(l - 1, add.get(l - 1) + inc);
}
public void multAll(int m) {
int l = add.size();
add.set(l - 1, (add.get(l - 1) * m) % MOD);
mult.set(l - 1, (mult.get(l - 1) * m) % MOD);
}
public int getIndex(int idx) {
if (idx >= lst.size()) return -1;
int l = add.size();
long m = (mult.get(l - 1) * inverse(mult.get(idx))) % MOD;
long a = (add.get(l - 1) - (add.get(idx) * m) % MOD + MOD) % MOD;
return (int) (((lst.get(idx) * m) % MOD + a) % MOD);
}
long inverse(long a) {
return pow(a, MOD - 2);
}
long pow(long a, long n) {
if (n == 0) return 1;
if (n % 2 == 0) {
long t = pow(a, n / 2);
return (t * t) % MOD;
} else {
return (pow(a, n - 1) * a) % MOD;
}
}
} | int mod97 = 1000000007;
/**
Calculates multiplicative inverse
*/
unsigned long modPow(unsigned long x, int y) {
unsigned long tot = 1, p = x;
for (; y; y >>= 1) {
if (y & 1)
tot = (tot * p) % mod97;
p = (p * p) % mod97;
}
return tot;
}
class Fancy {
public:
unsigned long seq[100001];
unsigned int length = 0;
unsigned long increment = 0;
unsigned long mult = 1;
Fancy() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
void append(int val) {
seq[length++] = (((mod97 + val - increment)%mod97) * modPow(mult, mod97-2))%mod97;
}
void addAll(int inc) {
increment = (increment+ inc%mod97)%mod97;
}
void multAll(int m) {
mult = (mult* m%mod97)%mod97;
increment = (increment* m%mod97)%mod97;
}
int getIndex(int idx) {
if (idx >= length){
return -1;
}else{
return ((seq[idx] * mult)%mod97+increment)%mod97;
}
}
}; | var Fancy = function() {
this.sequence = [];
this.appliedOps = [];
this.ops = [];
this.modulo = Math.pow(10, 9) + 7;
};
/**
* @param {number} val
* @return {void}
*/
Fancy.prototype.append = function(val) {
this.sequence.push(val);
this.appliedOps.push(this.ops.length);
};
/**
* @param {number} inc
* @return {void}
*/
Fancy.prototype.addAll = function(inc) {
this.ops.push(['add', inc]);
};
/**
* @param {number} m
* @return {void}
*/
Fancy.prototype.multAll = function(m) {
this.ops.push(['mult', m]);
};
/**
* @param {number} idx
* @return {number}
*/
Fancy.prototype.getIndex = function(idx) {
if (idx >= this.sequence.length) {
return -1;
}
while (this.appliedOps[idx] < this.ops.length) {
const [operation, value] = this.ops[this.appliedOps[idx]];
this.appliedOps[idx]++;
if (operation === 'mult') {
this.sequence[idx] = (this.sequence[idx] * value) % this.modulo;
}
if (operation === 'add') {
this.sequence[idx] = (this.sequence[idx] + value) % this.modulo;
}
}
return this.sequence[idx];
};
/**
* Your Fancy object will be instantiated and called as such:
* var obj = new Fancy()
* obj.append(val)
* obj.addAll(inc)
* obj.multAll(m)
* var param_4 = obj.getIndex(idx)
*/ | Fancy Sequence |
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Example 1:
Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
Output: [3,2,7,1]
Explanation: We perform the following operations on nums:
- Replace the number 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].
Example 2:
Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
Output: [2,1]
Explanation: We perform the following operations to nums:
- Replace the number 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].
Constraints:
n == nums.length
m == operations.length
1 <= n, m <= 105
All the values of nums are distinct.
operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 106
operations[i][0] will exist in nums when applying the ith operation.
operations[i][1] will not exist in nums when applying the ith operation.
| class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
replacements = {}
for x, y in reversed(operations):
replacements[x] = replacements.get(y, y)
for idx, val in enumerate(nums):
if val in replacements:
nums[idx] = replacements[val]
return nums | class Solution {
public int[] arrayChange(int[] nums, int[][] operations) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++) map.put(nums[i],i);
for(int[] op: operations) {
nums[map.get(op[0])] = op[1];
map.put(op[1],map.get(op[0]));
map.remove(op[0]);
}
return nums;
}
} | int m[1000001];
class Solution {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
for (int i = 0; i < nums.size(); ++i)
m[nums[i]] = i;
for (auto &op : operations) {
nums[m[op[0]]] = op[1];
m[op[1]] = m[op[0]];
}
return nums;
}
}; | /**
* @param {number[]} nums
* @param {number[][]} operations
* @return {number[]}
*/
var arrayChange = function(nums, operations) {
let map = new Map()
for(let i = 0; i < nums.length; i++){
let num = nums[i]
map.set(num, i)
}
for(let op of operations){
let key = op[0]
let value = op[1]
// if key exists
if(map.has(key)){
const idx = map.get(key)
map.set(value, idx)
map.delete(key)
}
}
for(let [key, idx] of map){
nums[idx] = key
}
return nums
}; | Replace Elements in an Array |
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
Example 1:
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
Example 3:
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086
Constraints:
2 * n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000
| class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
n = len(costs)
m = n // 2
@lru_cache(None)
def dfs(cur, a):
# cur is the current user index
# `a` is the number of people travel to city `a`
if cur == n:
return 0
# people to b city
b = cur - a
ans = float('inf')
# the number of people to `a` city number did not reach to limit,
# then current user can trval to city `a`
if a < m:
ans = min(dfs(cur+1, a+1)+costs[cur][0], ans)
# the number of people to `b` city number did not reach to limit
# then current user can trval to city `b`
if b < m:
ans = min(dfs(cur+1, a)+costs[cur][1], ans)
return ans
return dfs(0, 0) | // costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
// The difference between them would be like this [511, -394, -259, -45, -722, -108] this will give us the differnce c[1] - c[0]
// Now after sorting them from highest to smallest would be [511, -45, -108, -259, -394,-722] from high to low c2[1] - c2[0], c1[1] - c1[0] if we want low to high then it would be like this c1[1] - c1[0], c2[1] - c2[0]
//
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (c1, c2) -> Integer.compare(c2[1] - c2[0], c1[1] - c1[0]));// biggest to smallest
int minCost = 0;
int n = costs.length;
for (int i = 0; i < n; i++) {
minCost += i < n/2? costs[i][0] : costs[i][1];//First half -> A; Last half -> B 259 + 184 + 577 + 54 + 667 + 118
}
return minCost;
}
} | class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
sort(costs.begin(), costs.end(), [](const vector<int> &curr, const vector<int> &next){ // CUSTOM COMPARATOR
return (curr[0]-curr[1]) < (next[0]-next[1]); // (comparing cost of sending to A - cost to B)
});
// original: [[10,20],[30,200],[400,50],[30,20]]
// after sort: [[30,200],[10,20],[30,20],[400,50]]
// to do: a a b b
int sum = 0;
for(int i=0; i<costs.size()/2; i++){
sum+=costs[i][0];
// cout<<costs[i][0]<<" "; // 30 10
}
for(int i=costs.size()/2; i<costs.size(); i++){
sum+=costs[i][1];
// cout<<costs[i][1]<<" "; // 20 50
}
return sum;
}
}; | /**
* @param {number[][]} costs
* @return {number}
*/
var twoCitySchedCost = function(costs) {
// TC: O(nlogn) and O(1) extra space
let n=costs.length;
let countA=0,countB=0,minCost=0;
// sorted in descending order by their absolute diff
costs=costs.sort((a,b)=>{
let diffA=Math.abs(a[0] - a[1]);
let diffB=Math.abs(b[0] - b[1]);
return diffB-diffA;
});
for(let i=0;i<n;i++){
let [a,b]=costs[i];
if(a<b){
if(countA<n/2){
minCost+=a;
countA++;
}else{
minCost+=b;
countB++;
}
}else{
if(countB<n/2){
minCost+=b;
countB++;
}else{
minCost+=a;
countA++;
}
}
}
return minCost;
}; | Two City Scheduling |
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 105
2 <= k <= 104
s only contains lowercase English letters.
| class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack=[]
res=''
for i in range(len(s)):
if len(stack)==0:
stack.append([s[i],1])
elif stack[-1][0]==s[i]:
stack[-1][1]=stack[-1][1]+1
else:
stack.append([s[i],1])
if stack[-1][1]==k:
stack.pop()
for i in range(len(stack)):
res+=stack[i][0]*stack[i][1]
return res | class Solution
{
public String removeDuplicates(String s, int k)
{
int i = 0 ;
StringBuilder newString = new StringBuilder(s) ;
int[] count = new int[newString.length()] ;
while( i < newString.length() )
{
if( i == 0 || newString.charAt(i) != newString.charAt( i - 1 ) )
{
count[i] = 1 ;
}
else
{
count[i] = count[ i - 1 ] + 1 ;
if( count[i] == k )
{
newString.delete( i - k + 1 , i + 1 ) ;
i = i - k ;
}
}
i++ ;
}
return newString.toString() ;
}
} | #define pp pair< int , char >
class Solution {
public:
string removeDuplicates(string s, int k) {
int n=s.size();
stack< pp > stk;
int i=0;
while(i<n)
{
int count=1;
char ch=s[i];
while((i+1)<n && s[i]==s[i+1])
{
i++;
count++;
}
int c=0;
if(!stk.empty() && stk.top().second==ch)
{
c+=stk.top().first;
stk.pop();
}
count+=c;
count=count%k;
if(count!=0)
{
stk.push({count , ch});
}
i++;
}
string str="";
while(!stk.empty())
{
int count=stk.top().first;
while(count--)
{
str.push_back(stk.top().second);
}
stk.pop();
}
reverse(str.begin() , str.end());
return str;
}
}; | var removeDuplicates = function(s, k) {
const stack = []
for(const c of s){
const obj = {count: 1, char: c}
if(!stack.length){
stack.push(obj)
continue
}
const top = stack[stack.length-1]
if(top.char === obj.char && obj.count + top.count === k){
let count = k
while(count > 1){
stack.pop()
count--
}
}else if(top.char === obj.char){
obj.count+=top.count
stack.push(obj)
}else{
stack.push(obj)
}
}
return stack.reduce((a,b)=> a+b.char, '')
}; | Remove All Adjacent Duplicates in String II |
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
| class Solution:
def romanToInt(self, s: str) -> int:
roman = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
sum = 0;
for i in range(0, len(s) - 1):
curr = roman[s[i]]
nxt = roman[s[i + 1]]
if curr < nxt:
sum -= curr
else:
sum += curr
sum += roman[s[-1]]
return sum | class Solution {
public int romanToInt(String s) {
int res=0;
// Let s = "IV" after traversing string res will be 6
// Let s= "IX" after traversing string res will be 11
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case 'I': res=res+1;
break;
case 'V': res=res+5;
break;
case 'X': res+=10;
break;
case 'L': res+=50;
break;
case 'C': res+=100;
break;
case 'D': res+=500;
break;
case 'M': res+=1000;
break;
}
}
// Since s= "IV" it satisfies first condition and 2 is subtracted from res. res=4
// Since s= "IX" it satisfies first condition and 2 is subtracted from res. res=9
if(s.contains("IV")||s.contains("IX"))
res=res-2;
if(s.contains("XL")||s.contains("XC"))
res=res-20;
if(s.contains("CD")||s.contains("CM"))
res=res-200;
return res;
}
} | class Solution {
public:
int romanToInt(string s){
unordered_map<char, int> T = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };
int sum = T[s.back()];
for (int i = s.length() - 2; i >= 0; --i){
if (T[s[i]] < T[s[i + 1]]) sum -= T[s[i]];
else sum += T[s[i]];
}
return sum;
}
}; | var romanToInt = function(s) {
const sym = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
let result = 0;
for (let i = 0; i < s.length; i++) {
const cur = sym[s[i]];
const next = sym[s[i + 1]];
if (cur < next) {
result += next - cur;
i++;
} else {
result += cur;
}
}
return result;
}; | Roman to Integer |
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string? | class Solution(object):
def isPalindrome(self,x):
return str(x) == str(x)[::-1] | class Solution {
public boolean isPalindrome(int x) {
int sum = 0;
int X = x;
while(x > 0){
sum = 10 * sum + x % 10;
x /= 10;
}
return sum == X;
}
} | class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
long long reversed = 0;
long long temp = x;
while (temp != 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
return (reversed == x);
}
}; | var isPalindrome = function(x) {
if(x < 0 || x % 10 === 0 && x !== 0) return false
let num = x
let rev_x = 0
while(x > 0){
let digit = Math.floor(x % 10)
rev_x = Math.floor(rev_x * 10 + digit)
x = Math.floor(x / 10)
}
return num === rev_x
}; | Palindrome Number |
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2:
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].
Constraints:
The number of nodes in the tree is in the range [1, 210].
1 <= Node.val <= 100
1 <= distance <= 10
| class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
adjList=defaultdict(list)
leaves=[]
ct=0
[#undirected graph two way using parent and node in postorder style]
def dfs(node, parent):
if node:
if not node.left and not node.right:
leaves.append(node)
adjList[node].append(parent)
adjList[parent].append(node)
dfs(node.left,node)
dfs(node.right,node)
[#construct graph and get all the leaves]
dfs(root, None)
#bfs from each leaf till we find another leaf
for leaf in leaves:
q=deque([(leaf,0)] )
seen=set()
while q:
curr,dist = q.popleft()
seen.add(curr)
if dist>distance:
break
for nbr in adjList[curr]:
if nbr and nbr not in seen:
if nbr in leaves and dist+1<=distance:
ct+=1
q.append((nbr,dist+1))
return ct//2 | class Solution {
static int res;
public int countPairs(TreeNode root, int distance) {
res=0;
rec(root,distance);
return res;
}
static List<Integer> rec(TreeNode root,int dist){
if(root==null){
return new LinkedList<Integer>();
}
List<Integer> left=rec(root.left,dist);
List<Integer> right=rec(root.right,dist);
if(left.size()==0&&right.size()==0){
List<Integer> temp=new LinkedList<>();
temp.add(1);
return temp;
}
for(int i:left){
for(int j:right){
if(i+j<=dist){
res++;
}
}
}
List<Integer> temp=new LinkedList<>();
for(int i:left){
temp.add(i+1);
}
for(int i:right){
temp.add(i+1);
}
return temp;
}
} | class Solution {
vector<TreeNode*> leaves;
unordered_map<TreeNode* , TreeNode*> pof;
void makeGraph(unordered_map<TreeNode* , TreeNode*> &pof, TreeNode* root){
if(!root) return;
if(!root->left && !root->right){
leaves.push_back(root);
return;
}
if(root->left) pof[root->left]=root;
if(root->right) pof[root->right]=root;
makeGraph(pof, root->left);
makeGraph(pof, root->right);
}
public:
int countPairs(TreeNode* root, int distance) {
leaves={};
makeGraph(pof, root);
int ans=0;
queue<pair<TreeNode*, int>> q;
for(auto &l: leaves){
q.push({l, 0});
unordered_set<TreeNode*> isVis;
while(q.size()){
auto [cur, dist]=q.front();
q.pop();
if(isVis.count(cur) || dist>distance) continue;
isVis.insert(cur);
if(!cur->left && !cur->right && cur!=l && dist<=distance){
ans++;
continue;
}
if(cur->left && !isVis.count(cur->left)) q.push({cur->left, dist+1});
if(cur->right && !isVis.count(cur->right)) q.push({cur->right, dist+1});
if(pof.count(cur) && !isVis.count(pof[cur])) q.push({pof[cur], dist+1});
}
}
return ans>>1;
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} distance
* @return {number}
*/
var countPairs = function(root, distance) {
var graph = new Map()
var leaves = new Map()
function dfs(root, parent) {
if (!root) return
if (!root.left && !root.right) {
leaves.set(root, true)
}
graph.set(root, [])
if (root.left) {
graph.get(root).push(root.left)
}
if (root.right) {
graph.get(root).push(root.right)
}
if (parent) {
graph.get(root).push(parent)
}
dfs(root.left, root)
dfs(root.right, root)
}
dfs(root, null)
var visited = new Map()
var count = 0
function bfs(start, dis) {
visited.set(start, true)
var queue = [graph.get(start).filter(node => !visited.has(node))]
var innerVisited = new Map()
while (queue.length) {
var curLevelNodes = queue.shift()
if (!curLevelNodes.length) break
if (dis === 0) break
var nextLevelNodes = []
for (var i = 0; i < curLevelNodes.length; i++) {
var curLevelNode = curLevelNodes[i]
innerVisited.set(curLevelNode, true)
if (leaves.has(curLevelNode)) {
count++
}
nextLevelNodes.push(
...graph
.get(curLevelNode)
.filter(node =>
!visited.has(node) &&
!innerVisited.has(node)
)
)
}
queue.push(nextLevelNodes)
dis--
}
}
leaves.forEach((value, leaf) => {
bfs(leaf, distance)
})
return count
}; | Number of Good Leaf Nodes Pairs |
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105
| class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return self.b_search(nums)[0]
def b_search(self, nums):
if len(nums) == 1:
return nums
mid = len(nums)//2
a = nums[:mid]
b = nums[mid:]
# check if last & first element of the two sub lists are same
if a[-1] == b[0]:
a = a[:-1]
b = b[1:]
# ignore the sub list with even number of elements
if len(a)%2:
return self.b_search(a)
else:
return self.b_search(b) | class Solution {
public int singleNonDuplicate(int[] nums) {
if(nums.length==1) return nums[0];
int l = 0;
int h = nums.length-1;
while(l<h){
int mid = l+(h-l)/2; // divide the array
if(nums[mid]==nums[mid+1]) mid = mid-1; //two same elements should be in same half
if((mid-l+1)%2!=0) h = mid; // checking the length of left half. If its is odd then update ur right pointer to mid
else l = mid+1; // else your right half will be odd then update your left pointer to mid+1
}
return nums[l]; //left pointer will have the answer at last
}
} | class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int ans=0;
for(int i=0; i<nums.size();i++){
ans=ans^nums[i];
}
return ans;
}
}; | var singleNonDuplicate = function(nums) {
var start = 0;
var end = nums.length - 1
// to check one element
if (nums.length == 1) return nums[start]
while(start <= end) {
if(nums[start] != nums[start + 1]) {
return nums[start] }
if(nums[end] != nums[end - 1]) {
return nums[end]
}
// increment two point
start = start + 2;
end = end - 2;
}
}; | Single Element in a Sorted Array |
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.
The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.
For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4.
Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Example 1:
Input: cost = [1,2,3]
Output: 5
Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.
Example 2:
Input: cost = [6,5,7,9,2,2]
Output: 23
Explanation: The way in which we can get the minimum cost is described below:
- Buy candies with costs 9 and 7
- Take the candy with cost 6 for free
- We buy candies with costs 5 and 2
- Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.
Example 3:
Input: cost = [5,5]
Output: 10
Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.
Hence, the minimum cost to buy all candies is 5 + 5 = 10.
Constraints:
1 <= cost.length <= 100
1 <= cost[i] <= 100
| class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort(reverse=True)
res, i, N = 0, 0, len(cost)
while i < N:
res += sum(cost[i : i + 2])
i += 3
return res | class Solution {
/** Algorithm
* 1. Sort the cost array.
* 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.
* 3. Decrement the position by 3 and continue. stop when you reach 1.
* 4. From 1, add the remaining 1 or 2 items.
*
*/
public int minimumCost(int[] cost) {
int minCost = 0;
int index = cost.length -1;
Arrays.sort(cost);
// add items in pairs of 2, the 3rd one getting it for free.
while (index > 1) {
minCost += cost[index] + cost[index -1];
index -= 3;
}
// add the remaining 1, 2 items, if any.
while(index >= 0) {
minCost += cost[index--];
}
return minCost;
}
} | //Solution 01:
class Solution {
public:
int minimumCost(vector<int>& cost) {
int n = cost.size();
int i = n-1, ans = 0;
if(n <= 2){
for(auto x: cost)
ans += x;
return ans;
}
sort(cost.begin(), cost.end());
while(i>=1){
ans += cost[i] + cost[i-1];
if(i-1 == 0 || i-1 == 1) return ans;
i = i-3;
}
ans += cost[0];
return ans;
}
}; | var minimumCost = function(cost) {
if (cost.length < 3) {
return cost.reduce((prev, cur) => prev + cur);
}
cost.sort((a, b) => b - a);
let count = 0;
let sum = 0;
for (const num of cost) {
if (count === 2) {
count = 0;
continue;
}
sum += num;
count++;
}
return sum;
}; | Minimum Cost of Buying Candies With Discount |
Given the root of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 1000
| class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
# if not root: return True
def node_count(root):
if not root: return 0
return 1 + node_count(root.left) + node_count(root.right)
def isCBT(root,i,count):
if not root: return True
if i>=count: return False
return isCBT(root.left,2*i+1,count) and isCBT(root.right,2*i+2,count)
return isCBT(root,0,node_count(root)) | class Solution {
public boolean isCompleteTree(TreeNode root) {
boolean end = false;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode currentNode = queue.poll();
if(currentNode == null) {
end = true;
} else {
if(end) {
return false;
}
queue.offer(currentNode.left);
queue.offer(currentNode.right);
}
}
return true;
}
} | class Solution {
public:
bool isComplete = true;
// Returns min, max height of node
pair<int,int> helper(TreeNode *root){
// NULL is of height zero
if(root == NULL){
return {0, 0};
}
// Moving to its children
pair<int,int> lst = helper(root->left);
pair<int,int> rst = helper(root->right);
// Height of rst is greater than lst or
// There are levels which are not filled other than the last level (diff between levels > 1)
if(rst.second > lst.first || lst.second - rst.first > 1){
isComplete = false;
}
return {min(lst.first, rst.first)+1, max(lst.second, rst.second)+1};
}
bool isCompleteTree(TreeNode* root) {
helper(root);
return isComplete;
}
}; | var isCompleteTree = function(root) {
let queue = [root];
let answer = [root];
while(queue.length > 0) {
let current = queue.shift();
if(current) {
queue.push(current.left);
answer.push(current.left);
queue.push(current.right);
answer.push(current.right);
}
}
console.log("queue", queue);
while(answer.length > 0 ) {
let current = answer.shift();
if(current === null) break;
}
console.log("answer after shifting", answer);
let flag = true;
for(let current of answer) {
if(current !== null) {
flag = false;
break
}
}
return flag
}; | Check Completeness of a Binary Tree |
Given two strings s and t, return the number of distinct subsequences of s which equals t.
A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
rabbbit
rabbbit
rabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
babgbag
babgbag
babgbag
babgbag
babgbag
Constraints:
1 <= s.length, t.length <= 1000
s and t consist of English letters.
| class Solution:
def numDistinct(self, s: str, t: str) -> int:
if len(t) > len(s):
return 0
ls, lt = len(s), len(t)
res = 0
dp = [[0] * (ls + 1) for _ in range(lt + 1)]
for j in range(ls + 1):
dp[-1][j] = 1
for i in range(lt - 1, -1, -1):
for j in range(ls -1 , -1, -1):
dp[i][j] = dp[i][j + 1]
if s[j] == t[i]:
dp[i][j] += dp[i + 1][j + 1]
return dp[0][0] | class Solution {
// We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]
int f(int i,int j,String s,String t,int dp[][]){
//If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found a subsequence)
if(j<0)
return 1;
// if s gets exhausted then there are characters remaining in t which are yet to be matched as s got exhausted they could not be matched so there is no distinct subsequence
if(i<0){
return 0;
}
if(dp[i][j]!=-1)
return dp[i][j];
//If both the characters in s[i] and t[j] match then we have two case
//1) Either consider the i'th character of s and find the remaining distinct subsequences of s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)
//2) Do not consider s[i] so we are still at the same j'th character of t as we had not been considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1] i.e. f(i-1,j)
if(s.charAt(i)==t.charAt(j)){
dp[i][j]= f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp);
}
// If both of them do not match then we consider the 2nd case of matching characters
else{
dp[i][j]=f(i-1,j,s,t,dp);
}
return dp[i][j];
}
public int numDistinct(String s, String t) {
int n=s.length();
int m=t.length();
int dp[][]=new int[n][m];
for(int i=0;i<n;i++){
Arrays.fill(dp[i],-1);
}
return f(n-1,m-1,s,t,dp);
}
} | class Solution {
public:
int solve(string &s, string &t, int i, int j, vector<vector<int>> &dp){
if(j >= t.size()) return 1;
if(i >= s.size() || t.size() - j > s.size() - i) return 0;
if(dp[i][j] != -1) return dp[i][j];
int res = 0;
for(int k = i; k < s.size(); k++){
if(s[k] == t[j]) res += solve(s, t, k+1, j+1, dp);
}
return dp[i][j] = res;
}
int numDistinct(string s, string t) {
if(s.size() == t.size()) return s == t;
vector<vector<int>> dp(s.size(), vector<int> (t.size(), -1));
return solve(s, t, 0 , 0, dp);
}
}; | var numDistinct = function(s, t) {
const n = s.length;
const memo = {};
const dfs = (index = 0, subsequence = '') => {
if(subsequence === t) return 1;
if(n - index + 1 < t.length - subsequence.length) return 0;
if(index === n) return 0;
const key = `${index}-${subsequence}`;
if(key in memo) return memo[key];
memo[key] = t[subsequence.length] !== s[index] ? 0 : dfs(index + 1, subsequence + s[index]);
memo[key] += dfs(index + 1, subsequence);
return memo[key];
}
return dfs();
}; | Distinct Subsequences |
Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb"
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc"
Output: 1
Constraints:
3 <= s.length <= 5 x 10^4
s only consists of a, b or c characters.
| class Solution:
def numberOfSubstrings(self, s: str) -> int:
start = 0
end = 0
counter = 0
store = {'a' : 0, 'b' : 0, 'c' : 0}
for end in range(len(s)):
store[s[end]] += 1
while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:
counter += (len(s) - end)
store[s[start]] -= 1
start += 1
return counter | class Solution {
public int numberOfSubstrings(String s) {
int a = 0, b = 0, c = 0, count = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'a': ++a; break;
case 'b': ++b; break;
case 'c': ++c; break;
}
if (a > 0 && b > 0 && c > 0) {
while (a > 0 && b > 0 && c > 0) {
char farLeft = s.charAt(i - a - b - c + 1);
switch (farLeft) {
case 'a': {
--a;
count += doCount(s, i);
break;
}
case 'b': {
--b;
count += doCount(s, i);
break;
}
case 'c': {
--c;
count += doCount(s, i);
break;
}
}
}
}
}
return count;
}
private int doCount(String s, int i) {
int count = 0;
int n = s.length() - i;
if (n > 0) {
count += n;
}
return count;
}
} | class Solution {
public:
int numberOfSubstrings(string s) {
int i=0,j=0;
int n = s.size();
map<char,int> mp;
int count=0;
while(j<n){
mp[s[j]]++;
if(mp.size()<3){
j++;
}
else{
while(mp.size()==3){
count+=(n-j);
mp[s[i]]--;
if(mp[s[i]]==0) mp.erase(s[i]);
i++;
}
j++;
}
}
return count;
}
}; | /**
* @param {string} s
* @return {number}
*/
var numberOfSubstrings = function(s) {
let ans = 0;
let map = {};
for(let i = 0, l = 0; i < s.length; i++) {
const c = s[i];
map[c] = (map[c] || 0) + 1;
while(Object.keys(map).length == 3) {
ans += s.length - i;
map[s[l]]--;
if(map[s[l]] == 0) {
delete map[s[l]];
}
l++;
}
}
return ans;
}; | Number of Substrings Containing All Three Characters |
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:
A stone '#'
A stationary obstacle '*'
Empty '.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.
Return an n x m matrix representing the box after the rotation described above.
Example 1:
Input: box = [["#",".","#"]]
Output: [["."],
["#"],
["#"]]
Example 2:
Input: box = [["#",".","*","."],
["#","#","*","."]]
Output: [["#","."],
["#","#"],
["*","*"],
[".","."]]
Example 3:
Input: box = [["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]]
Output: [[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]]
Constraints:
m == box.length
n == box[i].length
1 <= m, n <= 500
box[i][j] is either '#', '*', or '.'.
| class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
# move stones to right, row by row
for i in range(len(box)):
stone = 0
for j in range(len(box[0])):
if box[i][j] == '#': # if a stone
stone += 1
box[i][j] = '.'
elif box[i][j] == '*': # if a obstacle
for m in range(stone):
box[i][j-m-1] = '#'
stone = 0
# if reaches the end of j, but still have stone
if stone != 0:
for m in range(stone):
box[i][j-m] = '#'
# rotate box, same as leetcode #48
box[:] = zip(*box[::-1])
return box | class Solution {
public char[][] rotateTheBox(char[][] box) {
int row = box.length, col = box[0].length;
char[][] res = new char[col][row];
// rotate first, then drop
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
res[j][i] = box[row-1-i][j];
}
}
for (int i = col - 1; i >= 0; i--) {
for (int j = 0; j < row; j++) {
if (res[i][j] == '#') {
int curRow = i;
while (curRow+1 < col && res[curRow+1][j] == '.') {
curRow++;
}
if (curRow != i) {
res[curRow][j] = '#';
res[i][j] = '.';
}
}
}
}
return res;
}
} | class Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
int m = box.size();
int n = box[0].size();
vector<vector<char>> ans(n,vector<char>(m,'.'));
for(int i=0;i<m;++i){
int k = n; //Stores last obstacle or occupied position
for(int j=n-1;j>=0;--j)
{
if(box[i][j] == '#')
{
ans[--k][i] = '#';
}
else if(box[i][j] == '*')
{
k = j;
ans[j][i] = '*';
}
}
}
for(int i=0;i<n;++i){
reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
}; | var rotateTheBox = function(box) {
for(let r=0; r<box.length;r++){
let idx = null
for(let c = 0;c<box[r].length;c++){
const curr = box[r][c]
if(curr === '*'){
idx = null
continue
}
if(curr === '#' && idx === null){
idx = c
continue
}
if(curr === '.' &&
box[r][idx] === '#' &&
idx <= c){
box[r][idx] = '.'
box[r][c] = '#'
idx++
}
}
}
return transpose(box)
};
function transpose(arr){
const B = []
for(let c = 0; c < arr[0].length; c++){
if(!B[c]) B[c] = []
for(let r = 0; r < arr.length; r++){
B[c][r] = arr[r][c]
}
B[c].reverse()
}
return B
} | Rotating the Box |
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).
Given the string word, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Example 1:
Input: word = "CAKE"
Output: 3
Explanation: Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3
Example 2:
Input: word = "HAPPY"
Output: 6
Explanation: Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6
Constraints:
2 <= word.length <= 300
word consists of uppercase English letters.
| from functools import cache
class Solution:
def minimumDistance(self, word: str) -> int:
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
COL = 6
index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}
def dist(a, b):
return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])
@cache
def dfs(lhand, rhand, i):
if i == len(word): return 0
res = float('inf')
res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))
res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))
return res
return dfs(-1, -1, 0) | class Solution {
HashMap<Character,Integer[]> pos;
int [][][]memo;
int type(String word,int index,char finger1,char finger2){
if (index==word.length()) return 0;
int ans=9999999;
if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];
if (finger1=='['){
ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));
}
else{
Integer [] prev=pos.get(finger1);
Integer [] curr=pos.get(word.charAt(index));
int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);
ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);
}
if (finger2=='['){
ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));
}
else{
Integer [] prev=pos.get(finger2);
Integer [] curr=pos.get(word.charAt(index));
int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);
ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);
}
memo[index][finger1-'A'][finger2-'A']=ans;
return ans;
}
public int minimumDistance(String word) {
pos=new HashMap();
for (int i=0;i<26;i++){
Integer [] coord={i/6,i%6};
pos.put((char)('A'+i),coord);
}
memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];
for (int[][] row : memo) {
for (int[] rowColumn : row) {
Arrays.fill(rowColumn, -1);
}
}
return type(word,0,'[','[');
}
} | class Solution {
public:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unordered_map<char, pair<int, int>> m;
int distCalc(char a, char b) {
pair<int, int> p_a = m[a];
pair<int, int> p_b = m[b];
int x_diff = abs(p_a.first - p_b.first);
int y_diff = abs(p_a.second - p_b.second);
return x_diff + y_diff;
}
int dp[301][27][27];
int minDist(string word, int i, char finger1_char, char finger2_char) {
if(i == word.size()) return 0;
if(dp[i][finger1_char - 'A'][finger2_char - 'A'] != -1) return dp[i][finger1_char - 'A'][finger2_char - 'A'];
//finger1
int op1 = (finger1_char == '[' ? 0 : distCalc(finger1_char, word[i])) + minDist(word, i + 1, word[i], finger2_char);
//finger2
int op2 = (finger2_char == '[' ? 0 : distCalc(finger2_char, word[i])) + minDist(word, i + 1, finger1_char, word[i]);
return dp[i][finger1_char - 'A'][finger2_char - 'A'] = min(op1, op2);
}
int minimumDistance(string word) {
//each letter has choice to be clicked by finger 1 or 2
int row = -1;
for(int i = 0; i < alpha.length(); i++) {
int col = i % 6;
if(col == 0) row++;
m[alpha[i]] = {row, col};
}
memset(dp, -1, sizeof(dp));
return minDist(word, 0, '[', '[');
}
}; | const dist = function(from, to){
if(from==-1) return 0;
const d1 = Math.abs((from.charCodeAt(0)-65)%6-(to.charCodeAt(0)-65)%6),
d2 = Math.abs(Math.floor((from.charCodeAt(0)-65)/6)-Math.floor((to.charCodeAt(0)-65)/6));
return d1 + d2;
}
var minimumDistance = function(word) {
const dp = new Map();
const dfs = function(i, lpos, rpos){
if(i==word.length)
return 0;
const key = [i,lpos,rpos].join(',');
if(dp.get(key))
return dp.get(key);
dp.set(key, Math.min(dist(lpos,word[i])+dfs(i+1,word[i],rpos), dist(rpos,word[i])+dfs(i+1,lpos,word[i])));
return dp.get(key);
}
return dfs(0, -1, -1);
}; | Minimum Distance to Type a Word Using Two Fingers |
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1
| class Solution:
def hasAlternatingBits(self, n: int) -> bool:
bin_n = bin(n)[2:]
for i in range(len(bin_n)-1):
if bin_n[i] == '0' and bin_n[i+1] == '0':
return False
if bin_n[i] == '1' and bin_n[i+1] == '1':
return False
return True | class Solution {
public boolean hasAlternatingBits(int n) {
int flag = 1;
if(n % 2 == 0) flag = 0;
return bin(n / 2, flag);
}
public boolean bin(int n, int flag) {
if(flag == n % 2) return false;
if(n == 0) return true;
else return bin(n / 2, n % 2);
}
} | class Solution {
public:
const static uint32_t a = 0b10101010101010101010101010101010;
bool hasAlternatingBits(int n) {
return ((a >> __builtin_clz(n)) ^ n) == 0;
}
}; | /**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
let previous;
while (n) {
const current = n & 1;
if (previous === current) return false;
previous = current;
n >>>= 1;
}
return true;
}; | Binary Number with Alternating Bits |
Implement strStr().
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Constraints:
1 <= haystack.length, needle.length <= 104
haystack and needle consist of only lowercase English characters.
| class Solution(object):
def strStr(self, haystack, needle):
if needle == '':
return 0
else:
return self.search_substring(haystack, needle)
def search_substring(self, haystack, needle):
len_substring = len(needle)
for i in range(len(haystack)):
if haystack[i: i + len_substring] == needle:
return i
return -1 | class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()>haystack.length()) {
return -1;
}
if(needle.length()==haystack.length()) {
if(haystack.equals(needle)) {
return 0;
}
return -1;
}
int i=0;
int j=0;
while(i<needle.length() && j<haystack.length()) {
if(needle.charAt(i)==haystack.charAt(j)) {
i++;
j++;
if(i==needle.length()) {
return j-needle.length();
}
} else {
j = j-i+1; // backtrack to last pos+1 where there was a probable match
i=0;
}
}
return -1;
}
} | class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
}; | var strStr = function(haystack, needle) {
return haystack.indexOf(needle)
}; | Implement strStr() |
You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
It does not occupy a cell containing the character '#'.
The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word, return true if word can be placed in board, or false otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
Output: true
Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
Output: false
Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
Output: true
Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 105
board[i][j] will be ' ', '#', or a lowercase English letter.
1 <= word.length <= max(m, n)
word will contain only lowercase English letters.
| class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
W = len(word)
def valid(x, y):
return 0 <= x < m and 0 <= y < n
def place(x, y, word, direction):
dx, dy = direction
for c in word:
if not valid(x, y) or board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != c):
return False
x, y = x+dx, y+dy
return True
for x in range(m):
for y in range(n):
if board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != word[0]):
continue
# left to right
if (not valid(x, y-1) or board[x][y-1] == '#') and (not valid(x, y+W) or board[x][y+W] == '#') and place(x, y, word, [0, 1]):
return True
# right to left
if (not valid(x, y+1) or board[x][y+1] == '#') and (not valid(x, y-W) or board[x][y-W] == '#') and place(x, y, word, [0, -1]):
return True
# top to bottom
if (not valid(x-1, y) or board[x-1][y] == '#') and (not valid(x+W, y) or board[x+W][y] == '#') and place(x, y, word, [1, 0]):
return True
# bottom to top
if (not valid(x+1, y) or board[x+1][y] == '#') and (not valid(x-W, y) or board[x-W][y] == '#') and place(x, y, word, [-1, 0]):
return True
return False | class Solution {
public boolean placeWordInCrossword(char[][] board, String word) {
String curr = "";
Trie trie = new Trie();
// Insert all horizontal strings
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '#') {
insertIntoTrie(trie, curr);
curr = "";
}
else {
curr += board[i][j];
}
}
insertIntoTrie(trie, curr);
curr = "";
}
// Insert all vertical strings
for (int i = 0; i < board[0].length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[j][i] == '#') {
insertIntoTrie(trie, curr);
curr = "";
}
else {
curr += board[j][i];
}
}
insertIntoTrie(trie, curr);
curr = "";
}
return trie.isPresent(word);
}
// Insert string and reverse of string into the trie
private void insertIntoTrie(Trie trie, String s) {
trie.insert(s);
StringBuilder sb = new StringBuilder(s);
sb.reverse();
trie.insert(sb.toString());
}
class TrieNode {
Map<Character, TrieNode> children;
boolean isEnd;
TrieNode() {
children = new HashMap<>();
isEnd = false;
}
}
class Trie {
TrieNode root;
Trie() {
root = new TrieNode();
}
void insert(String s) {
TrieNode curr = root;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (!curr.children.containsKey(c)) {
curr.children.put(c, new TrieNode());
}
curr = curr.children.get(c);
}
curr.isEnd = true;
}
boolean isPresent(String key) {
TrieNode curr = root;
return helper(key, 0, root);
}
boolean helper(String key, int i, TrieNode curr) {
if (curr == null)
return false;
if (i == key.length())
return curr.isEnd;
char c = key.charAt(i);
return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));
}
}
} | class Solution {
public:
bool placeWordInCrossword(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < n; j++){
if(board[i][j] != '#'){
if(valid(board, i-1, j) && check(board, word, i, j, 0, true, 1)) return true;
if(valid(board, i+1, j) && check(board, word, i, j, 0, true, -1)) return true;
if(valid(board, i, j-1) && check(board, word, i, j, 0, false, 1)) return true;
if(valid(board, i, j+1) && check(board, word, i, j, 0, false, -1)) return true;
}
}
}
return false;
}
bool check(vector<vector<char>>& board, string &word, int x, int y, int pos, bool vertical, int inc){
if(pos == word.size()){
if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;
return board[x][y] == '#';
}
if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false;
if(board[x][y] == '#') return false;
if(board[x][y] != ' ' && board[x][y] != word[pos]) return false;
int newx = x + vertical * inc;
int newy = y + (!vertical) * inc;
return check(board, word, newx, newy, pos+1, vertical, inc);
}
bool valid(vector<vector<char>>& board, int x, int y){
if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;
return board[x][y] == '#';
}
}; | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var placeWordInCrossword = function(board, word) {
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
if (i === 0 || board[i - 1][j] === '#') {
if (match(getFill(i, j, false))) {
return true;
}
}
if (j === 0 || board[i][j - 1] === '#') {
if (match(getFill(i, j, true))) {
return true;
}
}
}
}
return false;
function getFill(x, y, goRight) {
if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] !== '#') {
return goRight ? board[x][y] + getFill(x, y + 1, goRight) : board[x][y] + getFill(x + 1, y, goRight);
}
return '';
}
function match(str) {
if (str.length !== word.length) {
return false;
}
let fromLeft = true;
let fromRight = true;
let l = 0;
let r = str.length - 1;
for (let each of word) {
if (!fromLeft && !fromRight) {
return false;
}
if (fromLeft) {
if (each !== str[l] && str[l] !== ' ') {
fromLeft = false;
}
l++;
}
if (fromRight) {
if (each !== str[r] && str[r] !== ' ') {
fromRight = false;
}
r--;
}
}
return fromLeft || fromRight;
}
}; | Check if Word Can Be Placed In Crossword |
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
Example 1:
Input: head = [1,3,4,7,1,2,6]
Output: [1,3,4,1,2,6]
Explanation:
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node.
Example 2:
Input: head = [1,2,3,4]
Output: [1,2,4]
Explanation:
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.
Example 3:
Input: head = [2,1]
Output: [2]
Explanation:
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.
Constraints:
The number of nodes in the list is in the range [1, 105].
1 <= Node.val <= 105
| # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head: return head
if head and not head.next: return None
prev = ListNode(0, head)
slow = fast = head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = slow.next
return head | class Solution {
public ListNode deleteMiddle(ListNode head) {
// Base Condition
if(head == null || head.next == null) return null;
// Pointers Created
ListNode fast = head;
ListNode slow = head;
ListNode prev = head;
while(fast != null && fast.next != null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
return head;
}
} | **Intution**- we know that we can find middle node using two pointer fast and slow.
After we iterate through linkedlist slow pointer is our middle node and since we need to delete it
we only need pointer to its previous node and then just simply put next to next node in previous node.
Woahh ! you are done with deleting middle NODE;
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if(head->next==nullptr) return nullptr;
ListNode *f=head;
ListNode *s=head,*prev;
while(f!=nullptr && f->next!=nullptr){
f=f->next->next;
prev=s;
s=s->next;
}
prev->next=prev->next->next;
return head;
}
}; | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// Two Pointer: Fast & Slow | O(N) | O(1)
var deleteMiddle = function(head) {
if (!head.next) return null;
let prev = head;
let slow = head;
let fast = head.next;
let size = 2;
while (fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
size += fast ? 2 : 1;
}
if (size % 2 === 0) slow.next = slow.next.next;
else prev.next = slow.next;
return head;
}; | Delete the Middle Node of a Linked List |
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
If you start a task in a work session, you must complete it in the same work session.
You can start a new task immediately after finishing the previous one.
You may complete the tasks in any order.
Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Example 1:
Input: tasks = [1,2,3], sessionTime = 3
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
Example 3:
Input: tasks = [1,2,3,4,5], sessionTime = 15
Output: 1
Explanation: You can finish all the tasks in one work session.
Constraints:
n == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15
| class Solution:
def minSessions(self, tasks, T):
n = len(tasks)
@lru_cache(None)
def dp(mask):
if mask == 0: return (1, 0)
ans = (float("inf"), float("inf"))
for j in range(n):
if mask & (1<<j):
pieces, last = dp(mask - (1 << j))
full = (last + tasks[j] > T)
ans = min(ans, (pieces + full, tasks[j] + (1-full)*last))
return ans
return dp((1<<n) - 1)[0] | // Java Solution
class Solution {
public int minSessions(int[] tasks, int sessionTime) {
int n = tasks.length, MAX = Integer.MAX_VALUE;
int[][] dp = new int[1<<n][2];
dp[0][0] = 1;
dp[0][1] = 0;
for(int i = 1; i < (1 << n); i++) {
dp[i][0] = MAX;
dp[i][1] = 0;
for(int t = 0; t < n; t++) {
if(((1<<t) & i) == 0) continue;
int[] prev = dp[(1<<t) ^ i];
if(prev[1] + tasks[t] <= sessionTime) {
dp[i] = min(dp[i], new int[]{prev[0], prev[1] + tasks[t]});
}else{
dp[i] = min(dp[i], new int[]{prev[0] + 1, tasks[t]});
}
}
}
return dp[(1<<n) - 1][0];
}
private int[] min(int[] d1, int[] d2) {
if(d1[0] > d2[0]) return d2;
if(d1[0] < d2[0]) return d1;
if(d1[1] > d2[1]) return d2;
return d1;
}
} | // C++ Solution
class Solution {
public:
int minSessions(vector<int>& tasks, int sessionTime) {
const int N = tasks.size();
const int INF = 1e9;
vector<pair<int, int>> dp(1 << N, {INF, INF});
dp[0] = {0, INF};
for(int mask = 1; mask < (1 << N); ++mask) {
pair<int, int> best = {INF, INF};
for(int i = 0; i < N; ++i) {
if(mask & (1 << i)) {
pair<int, int> cur = dp[mask ^ (1 << i)];
if(cur.second + tasks[i] > sessionTime) {
cur = {cur.first + 1, tasks[i]};
} else
cur.second += tasks[i];
best = min(best, cur);
}
}
dp[mask] = best;
}
return dp[(1 << N) - 1].first;
}
}; | /**
* @param {number[]} tasks
* @param {number} sessionTime
* @return {number}
*/
var minSessions = function(tasks, sessionTime) {
const n = tasks.length;
const dp = Array(1 << n).fill().map(() => Array(16).fill(-1));
const solve = (mask, time) => {
if (mask === (1 << n) - 1) {
return 1;
}
if (dp[mask][time] !== -1) {
return dp[mask][time];
}
let min = Infinity;
for (let i = 0; i < n; ++i) {
if (mask & (1 << i)) {
continue;
}
if (time >= tasks[i]) {
min = Math.min(
min,
solve(mask | (1 << i), time - tasks[i]),
);
} else {
min = Math.min(
min,
1 + solve(mask | (1 << i), sessionTime - tasks[i]),
);
}
}
dp[mask][time] = min;
return min;
}
return solve(0, sessionTime);
}; | Minimum Number of Work Sessions to Finish the Tasks |
We are given hours, a list of the number of hours worked per day for a given employee.
A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.
A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.
Return the length of the longest well-performing interval.
Example 1:
Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].
Example 2:
Input: hours = [6,6,6]
Output: 0
Constraints:
1 <= hours.length <= 104
0 <= hours[i] <= 16
| class Solution:
def longestWPI(self, hours: List[int]) -> int:
#accumulative count
#+1 when > 8, -1 when less than 8.
#find strictly increasing length.
p = [] #number of tiring days vs not
c = 0
for e in hours:
if e > 8:
c +=1
else:
c-=1
p.append(c)
#for every moment: we want earliest moment which could be positive overall tiring days.
a = []
#a is sorted by tiringnes. At day 8 have -2, want earliest point that could get us to at least 1.
#so up until that point we have -3, -4, etc, and we want earliest out of it to get longest well performing interval. Which is when prefix comes in.
a1 =[]
for i in range(len(p)):
a.append([p[i], i])
a1.append(p[i])
a1.sort() #bisectable list
a.sort()
prefix = []
currearly = float('inf')
for t, day in a:
currearly = min(currearly, day)
prefix.append(currearly)
res = 0
# print(p)
for i in range(len(hours)):
if p[i] > 0:
res = max(res, i + 1)
else:
#find earliest
#value must be less than -1-p[i]
loc = bisect_right(a1, -1+p[i]) #bisect right means anything before this is less than or equals to
if loc == 0: #the rightmost place to put it is at the beginning...
continue
else:
earliest = prefix[loc - 1]
if earliest >= i: continue
interval = i - earliest #notice: we're not including the starting index, since its also technically being removed!
# print("From day", earliest, "to", i)
res = max(res, interval)
return res
| // Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)
// For Longest Well Performing Interval/Window
// T.C. = O(n^2) , S.C. = O(n)
class Solution {
public int longestWPI(int[] hours) {
int n = hours.length;
int[] prefixSumTiringDaysMinusNonTiringDaysArr = new int[n + 1];
prefixSumTiringDaysMinusNonTiringDaysArr[0] = 0;
int prefixSumTiringDaysCount = 0;
int prefixSumNonTiringDaysCount = 0;
for (int i = 0 ; i < n ; i++) {
int noOfHoursWorkedToday = hours[i];
if (noOfHoursWorkedToday > 8) {
prefixSumTiringDaysCount++;
}
else {
prefixSumNonTiringDaysCount++;
}
prefixSumTiringDaysMinusNonTiringDaysArr[i + 1] = prefixSumTiringDaysCount - prefixSumNonTiringDaysCount;
// System.out.print(prefixSumTiringDaysMinusNonTiringDaysArr[i] + " ");
}
// System.out.println(prefixSumTiringDaysMinusNonTiringDaysArr[n]);
int longestLengthOfContinuousPositiveSequence = 0;
for (int currentSlidingWindowLength = 1 ; currentSlidingWindowLength <= n ; currentSlidingWindowLength++) {
// System.out.print(currentSlidingWindowLength + " - ");
for (int i = 0 ; i <= n - currentSlidingWindowLength ; i++) {
int j = i + currentSlidingWindowLength - 1;
// System.out.print(i + "," + j + " ");
int currentIntervalNoOfTiringDaysMinusNonTiringDays = prefixSumTiringDaysMinusNonTiringDaysArr[j + 1] - prefixSumTiringDaysMinusNonTiringDaysArr[i];
if (currentIntervalNoOfTiringDaysMinusNonTiringDays > 0) { // => currentInterval = Well Performing Interval
longestLengthOfContinuousPositiveSequence = Math.max(currentSlidingWindowLength, longestLengthOfContinuousPositiveSequence);
}
}
// System.out.println();
}
// System.out.println();
int lengthOfLongestWellPerformingInterval = longestLengthOfContinuousPositiveSequence;
return lengthOfLongestWellPerformingInterval;
}
} | class Solution {
public:
int longestWPI(vector<int>& hours) {
int n = hours.size();
int ans = 0;
int ct = 0;
unordered_map<int, int> m;
for (int i = 0; i < n; ++i) {
if (hours[i] > 8) ct++;
else ct--;
if (ct > 0) ans = max(ans, i + 1);
else {
if (m.find(ct) == m.end()) m[ct] = i;
if (m.find(ct - 1) != m.end()) ans = max(ans, i - m[ct - 1]);
}
}
return ans;
}
}; | var longestWPI = function(hours) {
var dp = new Array(hours.length).fill(0);
for(i=0;i<hours.length;i++){
if(dp[i-1]>0 && hours[i]<=8){
dp[i]=dp[i-1]-1;
continue;
}
let tiring = 0;
for(j=i;j<hours.length;j++){
if(hours[j]>8) tiring++;
else tiring--;
if(tiring>0) dp[i] = Math.max(dp[i], j-i+1);
}}
return Math.max(...dp);
}; | Longest Well-Performing Interval |
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3
Output: 3
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= k <= 109
| # 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative,
# the numbers in sliding window are not always incrementing
# ex [8,-4,3,1,6], 10
# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.
# 3. monotonic queue is used to keep the prefix sums are in the incrementing order
# 4. If the diffenence between the cur and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.
class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
prefixsum = [0]
monoq = deque()
minLen = float('inf')
# to calculate prefix sum
for n in nums:
prefixsum.append(n+prefixsum[-1])
for idx, cur in enumerate(prefixsum):
while monoq and prefixsum[monoq[-1]] >= cur: monoq.pop() # to maintain monotonic queue
# If the diffenence between the head and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.
while monoq and cur-prefixsum[monoq[0]]>=k:
minLen = min(minLen, idx-monoq.popleft())
monoq.append(idx)
return -1 if minLen == float('inf') else minLen | class Solution {
public int shortestSubarray(int[] nums, int k) {
TreeMap<Long, Integer> maps = new TreeMap<>();
long sum = 0l;
int min = nums.length + 1;
maps.put(0l, -1);
for(int i = 0; i < nums.length; i++) {
sum += nums[i];ntry(sum - k) != null)
min = Math.min(min, i - maps.floorEntry(sum - k).getValue());
while(!maps.isEmpty() && maps.lastEntry().getKey() >= sum)
maps.remove(maps.lastEntry().getKey());
maps.put(sum, i);
}
return min == (nums.length + 1) ? -1 : min;
}
} | class Solution {
public:
//2-pointer doesnt work on neg elements
//Using mono deque to solve sliding window
int shortestSubarray(vector<int>& nums, int k) {
int n = nums.size();
int minsize = INT_MAX;
vector<long> prefixsum(n,0);
deque<int> dq;
prefixsum[0] = nums[0];
for(int i = 1;i<n;i++) prefixsum[i] = prefixsum[i-1] + nums[i];
for(int i = 0;i<n;i++){
if(prefixsum[i]>=k)
minsize = min(minsize,i+1);
while(!dq.empty() && prefixsum[i]-prefixsum[dq.front()]>=k){
minsize = min(minsize,i-dq.front());
dq.pop_front();
}
while(!dq.empty() && prefixsum[i]<=prefixsum[dq.back()]){
dq.pop_back();
}
dq.push_back(i);
}
return (minsize==INT_MAX) ? -1 : minsize;
}
}; | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var DoublyLinkedList = function(sum = "DUMMY", index = "DUMMY") {
this.property = {sum, index}
this.prev = null
this.next = null
}
DoublyLinkedList.prototype.deque = function() {
const dequeNode = this.next
this.next = dequeNode.next
dequeNode.next.prev = this
dequeNode.next = null
dequeNode.prev = null
return dequeNode
}
DoublyLinkedList.prototype.pop = function() {
const dequeNode = this.prev
this.prev = dequeNode.prev
dequeNode.prev.next = this
dequeNode.next = null
dequeNode.prev = null
return dequeNode
}
DoublyLinkedList.prototype.push = function(node) {
const prev = this.prev
const next = this
node.prev = prev
node.next = next
prev.next = node
next.prev = node
}
var shortestSubarray = function(nums, k) {
// Steps :-
// Initalize 3 vaiables :- sum = 0, subArrayLength = Infinity, queue -> []
const dummyHead = new DoublyLinkedList()
const dummyTail = new DoublyLinkedList()
dummyHead.next = dummyTail
dummyTail.prev = dummyHead
let queueSize = 0
let subArraySize = Number.MAX_SAFE_INTEGER
let sum = 0
for (let i = 0; i < nums.length; i++) {
sum += nums[i]
// Gives one possible answer, if sum is greater than or
// equal to k
if (sum >= k)
subArraySize = Math.min(subArraySize, i+1)
let lastDequeued
// Reduce the queue from left till the sum of elements from
// first index of queue till last index of queue is less than k
// Each time we constantly update the lastdequeued element
// As the last lastdequeued will satisfy sum - lastDequeued.sum >= k
// Thus the range would be i-lastDequeued.property.index
// (without lastDequeued.property.index)
while (queueSize > 0 && sum - dummyHead.next.property.sum >= k) {
queueSize--
lastDequeued = dummyHead.deque()
}
// Using the lastDequeued value to check
if (lastDequeued !== undefined) {
subArraySize = Math.min(subArraySize, i-lastDequeued.property.index)
}
// Maintaining the monotonic queue
while (queueSize > 0 && sum <= dummyTail.prev.property.sum) {
queueSize--
dummyTail.pop()
}
const newNode = new DoublyLinkedList(sum, i)
dummyTail.push(newNode)
queueSize++
}
return subArraySize === Number.MAX_SAFE_INTEGER ? -1 : subArraySize
}; | Shortest Subarray with Sum at Least K |
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
Example 1:
Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0
Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
Example 2:
Input: arr1 = [12], arr2 = [4]
Output: 4
Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
Constraints:
1 <= arr1.length, arr2.length <= 105
0 <= arr1[i], arr2[j] <= 109
| class Solution:
def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:
def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)
return xor_lis(arr1) & xor_lis(arr2) | class Solution {
public int getXORSum(int[] arr1, int[] arr2) {
int[] x = (arr1.length < arr2.length ? arr2 : arr1);
int[] y = (arr1.length < arr2.length ? arr1 : arr2);
int xorSumX = 0;
for (int xi : x) {
xorSumX ^= xi;
}
int answer = 0;
for (int yj : y) {
answer ^= (yj & xorSumX);
}
return answer;
}
} | class Solution {
public:
// this code is basically pure mathematics, mainly distributive property with AND and XOR
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int m=arr1.size();
int n=arr2.size();
long int ans1=0,ans2=0;
for(int i=0;i<m;i++) // this loop stores the XOR between every element of arr1
{
ans1=ans1 ^ arr1[i];
}
for(int j=0;j<n;j++) // this loop stores the XOR between every element of arr2
{
ans2=ans2 ^ arr2[j];
}
return ans1 & ans2; // AND operation of both XOR's is the answer.
}
}; | var getXORSum = function(arr1, arr2) {
// (x & 2) xor (x & 3) =[ !(x&2) & (x&3) ] OR [ (x&2) & !(x&3) ]
// = [ (!x || !2 ) & (x&3) ] OR [ (x&2) & (!x || !3) ]
// = [ (!x || !2) & x & 3 ] OR [ x & 2 & (!x || !3) ]
// = (!2 & x & 3 ) || (x & 2 & !3)
// = x & [ (!2 & 3) || (!3 & 2) ]
// = x & (2 XOR 3)
// const ans = (2 XOR 3 XOR....) in arr2
// The same principle: x, y,z... in arr1
// res = (x & ans) XOR (y & ans) XOR .....
// = ans & (x XOR y XOR z .......)
// Finally: res = (XOR: arr1) AND (XOR: arr2);
var xor1 = arr1.reduce((acc,cur)=>acc^cur);
var xor2 = arr2.reduce((acc,cur)=>acc^cur);
return xor1 & xor2;
}; | Find XOR Sum of All Pairs Bitwise AND |
The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1].
Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.
Example 1:
Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
Example 2:
Input: num = [2,7,4], k = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455
Example 3:
Input: num = [2,1,5], k = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021
Constraints:
1 <= num.length <= 104
0 <= num[i] <= 9
num does not contain any leading zeros except for the zero itself.
1 <= k <= 104
| class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
return list(str(int("".join(map(str,num)))+k)) | class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new ArrayList<>();
int i = num.length;
while(--i >= 0 || k > 0) {
if(i >= 0)
k += num[i];
res.add(k % 10);
k /= 10;
}
Collections.reverse(res);
return res;
}
} | Time: O(max(n,Log k)) Space: O(1)
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int i=size(num)-1;
int c=0,sum;
while(i>=0){
sum=num[i]+k%10+c;
res.push_back(sum%10);
c=sum/10;
k/=10;i--;
}
while(k){
sum=k%10+c;
res.push_back(sum%10);
c=sum/10;
k/=10;
}
if(c)
res.push_back(c);
reverse(begin(res),end(res));
return res;
}
};
--> Approach 2
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int i=size(num)-1;
int sum;
while(i>=0){
sum=num[i]+k;
res.push_back(sum%10);
k=sum/10;i--;
}
while(k){
res.push_back(k%10);
k/=10;
}
reverse(begin(res),end(res));
return res;
}
}; | var addToArrayForm = function(num, k) {
const length = num.length;
let digit = 0, index = length-1;
while(k > 0 || digit > 0) {
if(index >= 0) {
digit = digit + num[index] + k%10;
num[index] = digit%10;
}
else {
digit = digit + k%10;
num.unshift(digit%10);
}
digit = digit > 9 ? 1 : 0;
k = parseInt(k/10);
index--;
}
if(digit) num.unshift(digit);
return num;
}; | Add to Array-Form of Integer |
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.
Example 1:
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
Output: 34
Explanation: You can choose all the players.
Example 2:
Input: scores = [4,5,6,5], ages = [2,1,2,1]
Output: 16
Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
Example 3:
Input: scores = [1,2,3,5], ages = [8,9,10,1]
Output: 6
Explanation: It is best to choose the first 3 players.
Constraints:
1 <= scores.length, ages.length <= 1000
scores.length == ages.length
1 <= scores[i] <= 106
1 <= ages[i] <= 1000
| class Solution(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
l = len(scores)
mapped = [[ages[i], scores[i]] for i in range(l)]
mapped = sorted(mapped, key = lambda x : (x[0], x[1]))
dp = [i[1] for i in mapped]
for i in range(l):
for j in range(0, i):
if mapped[j][1] <= mapped[i][1]:
dp[i] = max(dp[i], mapped[i][1] + dp[j])
elif mapped[i][0] == mapped[j][0]:
dp[i] = max(dp[i], mapped[i][1] + dp[j])
return max(dp) | class Solution {
public int bestTeamScore(int[] scores, int[] ages) {
int n = scores.length;
// combine the arrays for ease in processing
int[][] combined = new int[n][2];
for (int i = 0; i < n; i++) {
combined[i][0] = ages[i];
combined[i][1] = scores[i];
}
// sort the arrays by age and scores
Arrays.sort(combined, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// find max answer between all possible teams
int ans = 0;
for (int i = 0; i < n; i++)
ans = Math.max(ans, recurse(combined, i));
return ans;
}
private int recurse(int[][] combined, int cur) {
// base case
if (cur == -1)
return 0;
// try teaming player with others if no conflict found
int ans = 0;
for (int prev = 0; prev < cur; prev++) {
if (combined[cur][0] == combined[prev][0] || combined[cur][1] >= combined[prev][1])
ans = Math.max(ans, recurse(combined, prev));
}
// add score of current player
ans += combined[cur][1];
return ans;
}
} | class Solution {
public:
int dp[1005][1005];
int bestTeamScore(vector<int>& scores, vector<int>& ages) {
vector<vector<int>>grp;
for(int i=0;i<scores.size();i++)
{
grp.push_back({scores[i],ages[i]});
}
sort(grp.begin(),grp.end());
memset(dp,-1,sizeof(dp));
return recur(grp,0,ages.size(),0);
}
int recur(vector<vector<int>>&grp , int i , int n , int maxiAge)
{
if(i==n)
return 0;
if(dp[i][maxiAge]!=-1)
return dp[i][maxiAge];
// score is already greater than previous socre we need to check age
// if current age is greater than previous maxiAge then two choices
if(grp[i][1]>=maxiAge)
{
return dp[i][maxiAge] = max(grp[i][0]+recur(grp,i+1,n,grp[i][1]),recur(grp,i+1,n,maxiAge));
}
return dp[i][maxiAge] = recur(grp,i+1,n,maxiAge);
}
}; | var bestTeamScore = function(scores, ages) {
const players = scores.map((score, index) => ({ score, age: ages[index] }))
.sort((a,b) => a.score === b.score ? a.age - b.age : a.score - b.score);
let memo = new Array(scores.length).fill(0).map(_ => new Array());
return dfs(0, 0);
function dfs(maxAge, index) {
if (index === players.length) {
return 0;
}
if (memo[index][maxAge] !== undefined) {
return memo[index][maxAge];
}
let max = 0;
let currentPlayer = players[index];
// cannot take because I'm too young and better than an old guy in my team
if (currentPlayer.age < maxAge) {
memo[index][maxAge] = dfs(maxAge, index + 1)
return memo[index][maxAge];
}
// take
max = Math.max(max, currentPlayer.score + dfs(Math.max(maxAge, currentPlayer.age), index + 1));
// not take
max = Math.max(max, dfs(maxAge, index + 1));
memo[index][maxAge] = max;
return max;
}
}; | Best Team With No Conflicts |
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
Example 2:
Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.
Constraints:
2 <= arr.length <= 105
arr.length is even.
1 <= arr[i] <= 105
| class Solution:
def minSetSize(self, arr: List[int]) -> int:
n = len(arr)
half = n // 2
c = Counter(arr)
s = 0
ans = 0
for num, occurances in c.most_common():
s += occurances
ans += 1
if s >= half:
return ans
return ans | class Solution {
public int minSetSize(int[] arr) {
int size=arr.length;
int deletedSize=0;
int countIteration=0;
Map<Integer,Integer> hashMap=new HashMap<>();
Queue<Map.Entry<Integer,Integer>> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());
for(int i=0;i<size;i++)
{
if(hashMap.get(arr[i])!=null)
hashMap.put(arr[i],hashMap.get(arr[i])+1);
else
hashMap.put(arr[i],1);
}
for(Map.Entry<Integer,Integer> entry:hashMap.entrySet())
{
queue.add(entry);
}
while(!queue.isEmpty())
{
int totalOccurence=queue.poll().getValue();
deletedSize+=totalOccurence;
countIteration++;
if(deletedSize>=size/2)
return countIteration;
}
return countIteration;
}
} | class Solution {
public:
int minSetSize(vector<int>& arr) {
const int n=1e5+10 ;
int a[n]={0} ;
for(int i=0 ;i<arr.size() ;i++)
{
a[arr[i]]++ ;
}
priority_queue<int> maxh ;
for(int i=0; i<n ;i++)
{
maxh.push(a[i]) ;
}
int sum=0 ;
int count=0 ;
while(sum<(arr.size()/2))
{
sum=sum+maxh.top() ;
maxh.pop() ;
count++ ;
}
return count ;
}
}; | var minSetSize = function(arr) {
let halfSize = arr.length / 2;
const numsCount = Object.values(getNumsCount(arr)).sort((a, b) => b - a); // get the frequencies in an array sorted in descending order
let setSize = 0;
if (numsCount[0] >= halfSize) return 1; // if the highest frequency is greater than or equal to half of the array size, then you already have your smallest set size of 1
for (let i = 0; i < numsCount.length; i++) {
let numCount = numsCount[i];
if (halfSize > 0) {
setSize++;
halfSize -= numCount;
} else {
return setSize;
};
};
};
var getNumsCount = function (arr) {
let eleCounts = {};
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
if (!eleCounts[num]) {
eleCounts[num] = 1;
} else {
eleCounts[num]++;
};
};
return eleCounts;
}; | Reduce Array Size to The Half |
Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.
Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.
Example 1:
Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
Explanation: The second player can choose the node with value 2.
Example 2:
Input: root = [1,2,3], n = 3, x = 1
Output: false
Constraints:
The number of nodes in the tree is n.
1 <= x <= n <= 100
n is odd.
1 <= Node.val <= n
All the values of the tree are unique.
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findParent(self,node,par = None):
if node:
self.parent[node.val] = par
self.findParent(node.left,node)
self.findParent(node.right,node)
def traverse(self,node,done):
if node:
if node in done: return 0
done[node] = True
a = self.traverse(self.parent[node.val],done)
b = self.traverse(node.left,done)
c = self.traverse(node.right,done)
return a + b + c + 1
return 0
def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
self.parent = {}
self.findParent(root)
parent = self.parent[x]
node = root if root.val == x else parent.left if parent and parent.left and parent.left.val == x else parent.right
up = self.traverse(parent,{node:True})
left = self.traverse(node.left,{node:True})
right = self.traverse(node.right,{node:True})
return (up > left + right) or (left > up + right) or (right > up + left) | class Solution {
int xkaLeft=0,xkaRight=0;
public int size(TreeNode node, int x)
{
if(node==null)
{
return 0;
}
int ls=size(node.left,x);
int rs=size(node.right,x);
if(node.val==x)
{
xkaLeft=ls;
xkaRight=rs;
}
return ls+rs+1;
}
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
size(root,x);
int parent=n-(xkaLeft+xkaRight+1);
int max=Math.max(parent,Math.max(xkaRight,xkaLeft));
if(max>n/2)
{
return true;
}
return false;
}
} | class Solution {
public:
// nodex means "node with val = x"
// Idea behind this is to block either nodex's parent or it's left child or right child. Block means we will chose that node as nodey. Why? because it will devide the tree in two parts, one for player 1 and other for player 2. Then we have to just take the maximum no of nodes we can get, from these three nodes as head, and if max is greater than n/2, means we can will.
TreeNode *nodex, *parentx;
Solution(){
nodex = NULL;
parentx = NULL;
}
int count(TreeNode *root)
{
if (root == NULL)
return 0;
int a = count(root->left);
int b = count(root->right);
return a + b + 1;
}
bool findx(TreeNode *root, int x)
{
if (root == NULL)
return false;
parentx = root;
if (root->val == x)
{
nodex = root;
return true;
}
bool a = findx(root->left, x);
if (a)
return true;
bool b = findx(root->right, x);
return b;
}
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
findx(root, x); // Find the node which has val = x
int p = n - count(nodex); // Count the no of nodes of blue color, if we decide to take parent of nodex as nodey
int r = count(nodex->right); // Count the no of nodes of blue color, if we decide to take right child of nodex as nodey
int l = count(nodex->left); // Count the no of nodes of blue color, if we decide to take left child of nodex as nodey
int mx = max(p,r);
mx = max(mx, l); // max of all three possible scenarios
if (mx > n/2)
return true;
else
return false;
}
}; | var left, right, val;
var btreeGameWinningMove = function(root, n, x) {
function count(node) {
if (node == null)
return 0;
var l = count(node.left);
var r = count(node.right);
if (node.val == val) {
left = l;
right = r;
}
return l + r + 1;
}
val = x;
count(root);
return Math.max(n - left - right - 1, Math.max(left, right)) > n / 2;
}; | Binary Tree Coloring Game |
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
| class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
marked = set() # visited by the dfs
def dfs(cell: Tuple[int, int], wp: int) -> bool:
i = cell[0]
j = cell[1]
if wp == len(word):
return True
# Get appropriate neighbours and perform dfs on them
# When going on dfs, we mark certain cells, we should remove #
#them from the marked list after we return from the dfs
marked.add((i,j))
neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]
for x, y in neibs:
if (
x < 0 or y < 0 or
x >= m or y >= n or
(x, y) in marked or
board[x][y] != word[wp]
):
continue
if dfs((x,y), wp + 1):
return True
marked.remove((i,j))
return False
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if dfs((i,j), 1):
return True
return False | class Solution {
public boolean exist(char[][] board, String word) {
boolean vis[][]=new boolean[board.length][board[0].length];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(word.charAt(0)==board[i][j]){
boolean is=isexist(i,j,board,vis,1,word);
if(is) return true;
}
}
}
return false;
}
static int dir[][]={{1,0},{0,1},{-1,0},{0,-1}};
static boolean isexist(int r, int c,char board[][],boolean vis[][],
int idx,String word){
if(idx==word.length()) return true;
vis[r][c]=true;
for(int k=0;k<4;k++){
int rd=r+dir[k][0];
int cd=c+dir[k][1];
if(rd<0 || cd<0 || rd>=board.length || cd>=board[0].length
|| vis[rd][cd]==true ||
board[rd][cd]!=word.charAt(idx)) continue;
boolean is=isexist(rd,cd,board,vis,idx+1,word);
if(is) return true;
}
vis[r][c]=false;
return false;
}
} | class Solution {
public:
bool solve(int i,int j,int &m,int &n,vector<vector<char>> &board,string &str,int s){
if(s>=str.length()){
return true;
}
if(i<0||j<0||i>=m||j>=n||board[i][j]=='#'){
return false;
}
char c = board[i][j];
board[i][j] = '#';
bool a = false;
if(c==str[s])
a = solve(i+1,j,m,n,board,str,s+1)||solve(i-1,j,m,n,board,str,s+1)||solve(i,j-1,m,n,board,str,s+1) || solve(i,j+1,m,n,board,str,s+1);
board[i][j] = c;
return a;
}
bool exist(vector<vector<char>>& board, string word) {
int i,j,m=board.size(),n=board[0].size();
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
if(board[i][j]==word[0] && solve(i,j,m,n,board,word,0)){
return true;
}
}
}
return false;
}
}; | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
let visited
const getNeighbours=([i,j],board)=>{
let arr=[];
if(i>0 && !visited[i-1][j])arr.push([i-1,j])
if(j>0 && !visited[i][j-1])arr.push([i,j-1])
if(i+1<board.length && !visited[i+1][j])arr.push([i+1,j])
if(j+1<board[i].length && !visited[i][j+1])arr.push([i,j+1])
return arr;
}
const dfs=([i,j],board, word,index)=>{
if(word[index]!==board[i][j])return false;
if(word.length-1===index)return true;
visited[i][j]=true;
let neighbours=getNeighbours([i,j],board,word,index)||[];
for(let k=0;k<neighbours.length;k++){
let temp_result=dfs(neighbours[k],board, word,index+1);
if(temp_result===true)return true;
}
visited[i][j]=false;
return false;
}
var exist = function(board, word) {
visited=[];
for(let i=0;i<board.length;i++){
visited[i]=[];
for(let j=0;j<board[i].length;j++){
visited[i][j]=false;
}
}
for(let i=0;i<board.length;i++){
for(let j=0;j<board[i].length;j++){
if(board[i][j]===word[0]){
let result=dfs([i,j],board,word,0);
if(result===true)return true;
}
}
}
return false;
}; | Word Search |
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
| class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
def subset(p, up):
if len(up) == 0:
if p not in ans:
ans.append(p)
return
ch = up[0]
subset(p+[ch], up[1:])
subset(p, up[1:])
subset([], nums)
return ans | class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
// Sort the input array to handle duplicates properly
Arrays.sort(nums);
// Start the recursion with an empty prefix list
return subset(new ArrayList<Integer>(), nums);
}
// Recursive function to generate subsets
public List<List<Integer>> subset(ArrayList<Integer> prefix, int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// Base case: If there are no elements in nums, add the current prefix to result
if (nums.length == 0) {
result.add(new ArrayList<>(prefix));
return result;
}
// Include the first element of nums in the prefix
ArrayList<Integer> withCurrent = new ArrayList<>(prefix);
withCurrent.add(nums[0]);
// Recursive call with the first element included
List<List<Integer>> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));
List<List<Integer>> right = new ArrayList<>();
// Check for duplicates in the prefix and decide whether to include the first element again
if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {
// If the current element is a duplicate, don't include it in the prefix
// This avoids generating duplicate subsets
} else {
// If the current element is not a duplicate, include it in the prefix
right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));
}
// Combine the subsets with and without the current element
left.addAll(right);
return left;
}
} | class Solution {
public:
vector<vector<int>> ans;
void recur(vector<int>& nums, int i, vector<int> vec){
if(i > nums.size()){
return;
}
for(int j = i; j < nums.size(); j++){
vec.push_back(nums[j]);
vector<int> temp = vec;
sort(vec.begin(), vec.end());
if(find(ans.begin(), ans.end(), vec) == ans.end()){
ans.push_back(vec);
}
recur(nums, j + 1, vec);
//can't just pop_back any need to pop_back the one we added
vec = temp;
vec.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<int> vec;
ans.push_back(vec);
recur(nums, 0, vec);
return ans;
}
}; | var subsetsWithDup = function(nums) {
let result = [];
//sort the nums to avoid duplicates;
nums.sort((a,b) => a -b);
result.push([]);
let startIdx = 0;
let endIdx = 0;
for(let i =0; i<nums.length; i++){
let current = nums[i];
startIdx = 0;
//check for duplicates and get the idx of last subset
if(i> 0 && nums[i] === nums[i-1]){
startIdx = endIdx +1;
}
endIdx = result.length - 1;
for(let j = startIdx; j< endIdx+1; j++){
let set1 = result[j].slice(0);
set1.push(current);
result.push(set1);
}
}
return result;
}; | Subsets II |
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = "()"
Output: 1
Example 2:
Input: s = "(())"
Output: 2
Example 3:
Input: s = "()()"
Output: 2
Constraints:
2 <= s.length <= 50
s consists of only '(' and ')'.
s is a balanced parentheses string.
| class Solution:
def scoreOfParentheses(self, s: str) -> int:
level = 0
result = 0
prev = ""
for c in s:
if c == "(":
level += 1
if c == ")":
if prev == "(":
result += 2 ** (level - 1)
level -= 1
prev = c
return result | class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> st = new Stack<>();
int score = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == '('){
st.push(score);
score = 0;
}
else {
score = st.pop() + Math.max(2 * score, 1);
}
}
return score;
}
} | class Solution {
public:
int scoreOfParentheses(string s) {
stack<int> st;
int score = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == '('){
st.push(score);
score = 0;
}
else {
score = st.top() + max(2 * score, 1);
st.pop();
}
}
return score;
}
}; | var scoreOfParentheses = function(s) {
let len = s.length, pwr = 0, ans = 0;
for (let i = 1; i < len; i++){
if (s.charAt(i) === "("){
pwr++;
}
else if (s.charAt(i-1) === "("){
ans += 1 << pwr--;
}
else{
pwr--;
}
}
return ans;
} | Score of Parentheses |
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary class:
MagicDictionary() Initializes the object.
void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.
bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
Constraints:
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case English letters.
All the strings in dictionary are distinct.
1 <= searchWord.length <= 100
searchWord consists of only lower-case English letters.
buildDict will be called only once before search.
At most 100 calls will be made to search.
| class MagicDictionary:
def __init__(self):
TrieNode = lambda : defaultdict(TrieNode)
self.root = TrieNode()
def buildDict(self, dictionary: List[str]) -> None:
for s in dictionary:
cur = self.root
for c in s: cur = cur[ord(c)-ord('a')]
cur['$']=True
def search(self, searchWord: str) -> bool:
def find(i,cur,mis):
if i==len(searchWord) and mis==0: return('$' in cur)
if mis < 0: return False
if i==len(searchWord) and mis!=0: return False
ind = ord(searchWord[i])-ord('a')
ans = False
for j in range(26):
if j in cur:
if(j!=ind):
ans |= find(i+1,cur[j],mis-1)
else: ans |= find(i+1,cur[j],mis)
return ans
return find(0,self.root,1) | class MagicDictionary {
private String[] dictionary;
public MagicDictionary() {}
public void buildDict(String[] dictionary) {
this.dictionary = dictionary;
}
public boolean search(String searchWord) {
for (String dictWord: this.dictionary) {
if (this.match(searchWord, dictWord, 1))
return true;
}
return false;
}
private boolean match(String s, String t, int expectedDiff) {
if (s.length() != t.length())
return false;
int diff = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != t.charAt(i))
diff++;
if (diff > expectedDiff)
return false;
}
return diff == expectedDiff;
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dictionary);
* boolean param_2 = obj.search(searchWord);
*/ | struct node{
bool end = false;
node *children[26];
};
class MagicDictionary {
public:
node* root;
void insert(string&s){
node* cur = root;
for(char&c : s){
if(!cur->children[c-'a']){
cur->children[c-'a'] = new node();
}
cur = cur->children[c-'a'];
}
cur->end=true;
}
MagicDictionary() {
root = new node();
}
void buildDict(vector<string> dictionary) {
for(string&s : dictionary)insert(s);
}
bool find(int i, string& s,node* cur, int mismatch){
if(i == s.size() and mismatch==0) return cur->end;
if(mismatch<0)return false;
if((!cur || i == s.size()) and mismatch!=0) return false;
int ind = s[i]-'a';
bool ans = false;
for(int j=0;j<26;j++){
if(cur->children[j]){
if(j!=ind){
ans |= find(i+1,s,cur->children[j],mismatch-1);
}else{
ans |= find(i+1,s,cur->children[j],mismatch);
}
}
}
return ans;
}
bool search(string searchWord) {
return find(0,searchWord,root,1);
}
}; | function TrieNode(){
this.children = new Map()
this.endOfWord = false;
}
var MagicDictionary = function() {
this.root = new TrieNode()
};
MagicDictionary.prototype.buildDict = function(dictionary) {
for(let word of dictionary){
let curr = this.root
for(let letter of word){
let map = curr.children
if(!map.has(letter)) map.set(letter, new TrieNode())
curr = map.get(letter)
}
curr.endOfWord = true
}
};
MagicDictionary.prototype.search = function(searchWord){
return dfs(this.root, searchWord, 0, 0)
}
function dfs(root, str, i, count){
if(count>1) return false
if(i==str.length) return count == 1 && root.endOfWord
for(let [char, node] of root.children){
let c = 0;
if(char != str[i]) c = 1
if(dfs(node, str, i+1, count+c)) return true;
}
return false
} | Implement Magic Dictionary |
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
2 <= n <= 5 * 104
connections.length == n - 1
connections[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
| from collections import defaultdict
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
count, stack, visited = 0, [ 0 ], set() #Add root node to stack
neighbours = defaultdict(list) #To store neighbours
adjacency = defaultdict(list) #To store adjacency
for i, j in connections:
adjacency[i].append(j)
neighbours[i].append(j)
neighbours[j].append(i)
while stack:
current = stack.pop()
if current in visited:
continue
else:
visited.add(current)
for i in neighbours[current]:
if i in visited:
continue
if current not in adjacency[i]:
count += 1
stack.append(i)
return count | class Solution {
int dfs(List<List<Integer>> al, boolean[] visited, int from) {
int change = 0;
visited[from] = true;
for (var to : al.get(from))
if (!visited[Math.abs(to)])
change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);
return change;
}
public int minReorder(int n, int[][] connections) {
List<List<Integer>> al = new ArrayList<>();
for(int i = 0; i < n; ++i)
al.add(new ArrayList<>());
for (var c : connections) {
al.get(c[0]).add(c[1]);
al.get(c[1]).add(-c[0]);
}
return dfs(al, new boolean[n], 0);
}
} | class Solution {
public:
vector<int> Radj[50001],adj[50001] ,visited;
int bfs(){
int edges = 0 ;
queue<int> q ;
q.push(0) ;
while(q.size()){
auto src = q.front() ; q.pop() ;
visited[src] = 1 ;
for(auto &nbr : adj[src]){
if(visited[nbr]) continue ;
//this connection needs reverse orientation
++edges ;
q.push(nbr) ;
}
for(auto &nbr : Radj[src]){
if(visited[nbr]) continue ;
q.push(nbr) ;
}
}
return edges ;
}
int minReorder(int n, vector<vector<int>>& connections) {
visited.resize(n,0);
for(auto &x : connections) adj[x[0]].push_back(x[1]) , Radj[x[1]].push_back(x[0]);
return bfs() ;
}
}; | var minReorder = function(n, connections) {
// from: (<from city>, [<to cities>])
// to: (<to city>, [<from cities>])
const from = new Map(), to = new Map();
// Function to insert in values in map
const insert = (map, key, value) => {
if(map.has(key)){
const arr = map.get(key);
arr.push(value);
map.set(key, arr);
} else {
map.set(key, [value]);
}
}
// Set all values in both maps
for(const [a,b] of connections){
insert(from, a, b);
insert(to, b, a);
}
// Queue: cities to visit
const queue = [0], visited = new Set();
let count = 0;
while(queue.length) {
const cur = queue.shift(); // First element in queue
// Check values in first map
if(from.has(cur)){
for(const x of from.get(cur)){
// If visited, do nothing else add to queue
if(visited.has(x)) continue;
queue.push(x);
count++; // Change direction of this path
}
}
if(to.has(cur)){
// If visited, do nothing else add to queue
for(const x of to.get(cur)){
if(visited.has(x)) continue;
queue.push(x);
}
}
visited.add(cur); // Mark city as visited
}
return count
}; | Reorder Routes to Make All Paths Lead to the City Zero |
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
Note that the integers in the lists may be returned in any order.
Example 1:
Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].
Example 2:
Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
Explanation:
For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
Constraints:
1 <= nums1.length, nums2.length <= 1000
-1000 <= nums1[i], nums2[i] <= 1000
| class Solution(object):
def findDifference(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[List[int]]
"""
a = []
for i in range(len(nums1)):
if nums1[i] not in nums2:
a.append(nums1[i])
b = []
for i in range(len(nums2)):
if nums2[i] not in nums1:
b.append(nums2[i])
c = [list(set(a))] + [list(set(b))]
return c | class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>(); // create 2 hashsets
Set<Integer> set2 = new HashSet<>();
for(int num : nums1){ set1.add(num); } // add nums1 elements to set1
for(int num : nums2){ set2.add(num); } // add nums2 elements to set2
List<List<Integer>> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return
resultList.add(new ArrayList<>());
resultList.add(new ArrayList<>());
for(int num : set1){ // just iterate to all elements of set1
if(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.
}
for(int num : set2){ // just iterate to all elements of set2
if(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1
}
return resultList;
}
} | class Solution {
public:
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
//unordered_set is implemented using a hash table where keys are hashed into indices of a hash table
// all operations take O(1) on average
unordered_set<int> n1;
unordered_set<int> n2;
for(int i=0;i<nums1.size();i++)
n1.insert(nums1[i]);
for(int i=0;i<nums2.size();i++)
n2.insert(nums2[i]);
vector<int> ans1;
vector<vector<int>> ans;
for(int x:n1)
{
if(n2.find(x)==n2.end())
ans1.push_back(x);
}
ans.push_back(ans1);
ans1.clear();
for(int x:n2)
{
if(n1.find(x)==n1.end())
ans1.push_back(x);
}
ans.push_back(ans1);
return ans;
}
}; | var findDifference = function(nums1, nums2) {
const s1 = new Set(nums1);
const s2 = new Set(nums2);
const a1 = [...s1].filter(x => !s2.has(x));
const a2 = [...s2].filter(x => !s1.has(x));
return [a1, a2];
}; | Find the Difference of Two Arrays |
Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets k or more points.
Return the probability that Alice has n or fewer points.
Answers within 10-5 of the actual answer are considered accepted.
Example 1:
Input: n = 10, k = 1, maxPts = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.
Example 2:
Input: n = 6, k = 1, maxPts = 10
Output: 0.60000
Explanation: Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.
Example 3:
Input: n = 21, k = 17, maxPts = 10
Output: 0.73278
Constraints:
0 <= k <= n <= 104
1 <= maxPts <= 104
| class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])
s = sum(dp)
for i in range(k):
dp.appendleft(s / maxPts)
s += dp[0] - dp.pop()
return dp[0] | class Solution {
public double new21Game(int n, int k, int maxPts) {
double[] dp = new double[k + maxPts];
dp[0] = 1;
for (int i = 0; i < k; i++){
for (int j = 1; j <= maxPts; j++){
dp[i + j] += dp[i] * 1.0 / maxPts;
}
}
double ans = 0;
for (int i = k; i < k + maxPts && i <= n; i++){
ans += dp[i];
}
return ans;
}
} | class Solution {
public:
double new21Game(int n, int k, int maxPts) {
if(k==0 || n>=k+maxPts-1)
return (double) 1;
vector<double> dp(n+1);
dp[0]=1;
double sum = 0;
for(int i=0; i<n; i++)
{
if(i<k)
sum+=dp[i]; // reach f(2) by directly drawing f(2) or f(1) and f(1)
if(i>=maxPts)
sum-=dp[i-maxPts];
dp[i+1] = sum/maxPts;
}
double ret = 0;
for(int i=k; i<=n; i++)
ret+=dp[i];
return ret;
}
}; | var new21Game = function(n, k, maxPts) {
if (k+maxPts <= n || k===0) return 1;
let dp = [];
dp[0] = 1;
dp[1] = 1/maxPts;
for (let i = 2; i <= n; i++) {
dp[i] = 0;
if (i <= k) {
dp[i] = (1 + 1/maxPts) * dp[i-1];
} else {
dp[i] = dp[i-1];
}
if (i > maxPts) {
dp[i] -= dp[i-maxPts-1] / maxPts;
}
}
return dp.reduce((acc, cur, idx) => {
if (idx >= k) {
acc += cur;
}
return acc;
}, 0)
}; | New 21 Game |
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:
-2: Turn left 90 degrees.
-1: Turn right 90 degrees.
1 <= k <= 9: Move forward k units, one unit at a time.
Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).
Note:
North means +Y direction.
East means +X direction.
South means -Y direction.
West means -X direction.
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
Example 3:
Input: commands = [6,-1,-1,6], obstacles = []
Output: 36
Explanation: The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
Constraints:
1 <= commands.length <= 104
commands[i] is either -2, -1, or an integer in the range [1, 9].
0 <= obstacles.length <= 104
-3 * 104 <= xi, yi <= 3 * 104
The answer is guaranteed to be less than 231.
| class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
obs = set(tuple(o) for o in obstacles)
x = y = a = out = 0
move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}
for c in commands:
if c == -1:
a += 90
elif c == -2:
a -= 90
else:
direction = a % 360
dx, dy = move[direction]
for _ in range(c):
if (x + dx, y + dy) in obs:
break
x += dx
y += dy
out = max(out, x**2 + y**2)
return out | class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int dir = 0; // states 0north-1east-2south-3west
int farthestSofar = 0;
int xloc = 0;
int yloc = 0;
Set<String> set = new HashSet<>();
for (int[] obs : obstacles) {
set.add(obs[0] + "," + obs[1]);
}
int steps;
for(int i: commands){
if( i == -1){//turn right 90
dir++;
}
else if (i == -2){//turn left 90
dir--;
}
else{//move forward value of i baring no obsticals
dir = dir%4;
if (dir== -1){
dir = 3;
}
else if(dir == -3){
dir = 1;
}
else if(dir == -2){
dir = 2;
}
// dir %4 = -1 -> 3
// dir %4 = -2 -> 2
// dir %4 = -3 -> 1
if(dir == 0){
steps = 0;
while (steps < i && !set.contains((xloc) + "," + (yloc+1))) {
yloc++;
steps++;
}
}
else if (dir == 1){
steps = 0;
while (steps < i && !set.contains((xloc+1) + "," + (yloc))) {
xloc++;
steps++;
}
}
else if (dir == 2){
steps = 0;
while (steps < i && !set.contains((xloc) + "," + (yloc-1))) {
yloc--;
steps++;
}
}
else{ //case dir == 3
steps = 0;
while (steps < i && !set.contains((xloc-1) + "," + (yloc))) {
xloc--;
steps++;
}
}
}
farthestSofar = Math.max(farthestSofar, xloc*xloc + yloc*yloc);
}
return farthestSofar;
}
} | class Solution {
public:
//N--> left(-2):W, right(-1):E
//S--> left:E, right:W
//E--> left:N, right:S
//W--> left:S, right:N
vector<vector<int>> change= { //for direction change
{3,2},
{2,3},
{0,1},
{1,0}
};
vector<vector<int>> sign = { //signs for x and y coordinates movement
{0,1},//North
{0,-1},//south
{1,0},//east
{-1,0}//west
};
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
set<vector<int>> s;
for(int i = 0;i<obstacles.size();i++){
s.insert(obstacles[i]);
}
int direction = 0;
int ans = 0;
int xi = 0,yi = 0;
for(int i = 0;i<commands.size();i++){
if(commands[i]<=9 && commands[i]>=1){
int signx = sign[direction][0];
int signy = sign[direction][1];
while(commands[i]){
xi += signx;
yi += signy;
if(s.count({xi,yi})){
xi -= signx;
yi -= signy;
break;
}
commands[i]--;
}
}
else{
direction = change[direction][commands[i]+2];
}
ans = max(ans,xi*xi+yi*yi);
}
return ans;
}
}; | /**
* @param {number[]} commands
* @param {number[][]} obstacles
* @return {number}
*/
var robotSim = function(commands, obstacles) {
let result = 0;
let currentPosition = [0, 0];
let currentDirection = 'top';
const mySet = new Set();
// This is to have a O(1) check instead of doing a linear scan
obstacles.forEach(obs => {
mySet.add(`${obs[0]},${obs[1]}`);
}); // O(m)
for (let i = 0; i < commands.length ; i++) { // O(n)
const move = commands[i];
if (move === -1) {
if (currentDirection === 'top') {
currentDirection = 'right';
} else if (currentDirection === 'right') {
currentDirection = 'down';
} else if (currentDirection === 'down') {
currentDirection = 'left';
} else {
currentDirection = 'top';
}
}
if (move === -2) {
if (currentDirection === 'top') {
currentDirection = 'left';
} else if (currentDirection === 'left') {
currentDirection = 'down';
} else if (currentDirection === 'down') {
currentDirection = 'right';
} else {
currentDirection = 'top';
}
}
if (move > 0) {
for (let i = 0; i < move; i++) { O(move)
const isY = (currentDirection === 'top' || currentDirection === 'down');
const isPositive = (currentDirection === 'top' || currentDirection === 'right');
const newPosition = [currentPosition[0] + (!isY ? isPositive? 1: -1 : 0), currentPosition[1] + (isY ? isPositive ? 1 : -1 : 0)];
const positionString = `${newPosition[0]},${newPosition[1]}`;
if (!mySet.has(positionString)) {
currentPosition = newPosition;
result = Math.max(result, (Math.pow(currentPosition[0], 2) + Math.pow(currentPosition[1], 2)));
} else {
break;
}
}
}
}
return result;
}; | Walking Robot Simulation |
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
| class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
prev=[0]*len(grid[0])
for i in range(len(grid)):
temp=[0]*len(grid[0])
for j in range(len(grid[0])):
if i==0 and j==0:
temp[j]=grid[i][j]
continue
if i>0:
lft=grid[i][j]+prev[j]
else:
lft=grid[i][j]+1000
if j>0:
up=grid[i][j]+temp[j-1]
else:
up=grid[i][j]+1000
temp[j]=min(up,lft)
prev=temp
return prev[-1]
| class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] dp = new int[n];
dp[0] = grid[0][0];
for(int i=1;i<n;i++){
dp[i] = dp[i-1]+grid[0][i];
}
for(int i=1;i<m;i++){
for(int j=0;j<n;j++){
if(j == 0)
dp[j] += grid[i][j];
else
dp[j] = Math.min(dp[j],dp[j-1])+grid[i][j];
}
}
return dp[n-1];
}
} | class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n=grid.size();
int m=grid[0].size();
vector<vector<int>> dp(n,vector<int>(m,0));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(i==0 && j==0)
dp[i][j]=grid[i][j];
else if(i==0)
dp[i][j]=dp[i][j-1]+grid[i][j];
else if(j==0)
dp[i][j]=dp[i-1][j]+grid[i][j];
else
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j];
}
}
return dp[n-1][m-1];
}
}; | var minPathSum = function(grid) {
let row = grid.length;
let col = grid[0].length;
for(let i = 1; i < row; i++) {
grid[i][0] += grid[i-1][0];
}
for(let j = 1; j < col; j++) {
grid[0][j] += grid[0][j-1];
}
for(let i = 1; i < row; i++) {
for(let j = 1; j < col; j++) {
grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);
}
}
return grid[row-1][col-1];
}; | Minimum Path Sum |
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
Example 1:
Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
Example 2:
Input: nums = [1,1,2,3]
Output: [1,3,3]
Constraints:
2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100
| class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
answer = []
for i in range(0, len(nums), 2):
for j in range(0, nums[i]):
answer.append(nums[i + 1])
return answer | class Solution {
public int[] decompressRLElist(int[] nums) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i+1 < nums.length; i += 2) {
for (int j = 0; j < nums[i]; ++j) {
arr.add(nums[i+1]);
}
}
int[] res = new int[arr.size()];
for (int i = 0; i < res.length; ++i) res[i] = arr.get(i);
return res;
}
} | class Solution {
public:
vector<int> decompressRLElist(vector<int>& nums) {
vector<int> ans;
for(int i=0 ; i<nums.size() ; i+=2){
int freq = nums[i];
int val = nums[i+1];
while(freq--){
ans.push_back(val);
}
}
return ans;
}
}; | var decompressRLElist = function(nums) {
let solution = [];
for(let i = 0;i<nums.length;i+=2){
for(let j = 0;j<nums[i];j++){
solution.push(nums[i+1])
}
}
return (solution)
}; | Decompress Run-Length Encoded List |
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
| class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.final_list = []
def subset(final_list,curr_list,listt,i):
if i == len(listt):
final_list.append(curr_list)
return
else:
subset(final_list,curr_list,listt,i+1)
subset(final_list,curr_list+[listt[i]],listt,i+1)
subset(self.final_list,[],nums,0)
return self.final_list | class Solution {
private static void solve(int[] nums, int i, List<Integer> temp, List<List<Integer>> subset){
if(i == nums.length){
subset.add(new ArrayList(temp));
return;
}
temp.add(nums[i]);
solve(nums, i + 1, temp, subset);
temp.remove(temp.size() - 1);
solve(nums, i + 1, temp, subset);
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subset = new ArrayList();
List<Integer> temp = new ArrayList<>();
if(nums.length == 0) return subset;
int startInd = 0;
solve(nums, startInd, temp, subset);
return subset;
}
} | class Solution {
void subsetGenerator (vector<int> nums, int n, vector<vector<int>> &ans, int i, vector<int> subset)
{
if(i>=n) //Base Case
{
ans.push_back(subset); //the subset obatined is pushed into ans
return ;
}
//including the element at index i and then calling the recursive function
subset.push_back(nums[i]);
solve(nums,n,ans,i+1,subset);
//excluding the element at index i and then calling the recursive function
subset.pop_back();
solve(nums,n,ans,i+1,subset);
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
int i=0; // index is initialized to 0 as we start from the first element
int n=nums.size(); // size of the vector nums
vector<int> subset; // this vector will store each subset which is generated
vector<vector<int>> ans; // will store all the subsets generated
subsetGenerator(nums, n, ans, i, subset);
return ans;
}
}; | var subsets = function(nums) {
const res = [];
const dfs = (i, slate) => {
if(i == nums.length){
res.push(slate.slice());
return;
}
// take the current number into the subset.
slate.push(nums[i]);
dfs(i + 1, slate);
slate.pop();
// ignore the current number.
dfs(i + 1, slate);
}
dfs(0, []);
return res;
}; | Subsets |
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]
Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
Constraints:
1 <= s.length <= 105
s consists of only digits and does not contain leading zeros.
1 <= k <= 109
| """
"1317"
[1, 3, 1, 7] -> [1] * nums(317, k)
[1, 3, 17]
[1, 31, 7]
[1, 317]
[13, 1, 7] -> [13] * nums(17, k)
[13, 17]
[131, 7]
[1317]
"2020" k = 30
[2000] x
[2, 020] x
[20, 20]
"67890" k = 90
[6, 7890] x
[6, 7, 8, 9, 0] x
[6, 7, 8, 90] OK
[6, 78, 90] OK
[67, 8, 90] OK
[67, 89, 0] x
[678, 90] x
break because 678 > k (90), so neither 678, 6789 would be possible numbers
"""
class Solution:
def num_arrays(self, s, k, memo):
if not s:
return 0
memo_ans = memo.get(s)
if memo_ans is not None:
return memo_ans
num = int(s)
if num <= k:
counter = 1
else:
counter = 0
for i in range(len(s) - 1):
# Stop when the number to the right side of the array is greater than k
if int(s[:i + 1]) > k:
break
# Don't count leading zeros
if s[i + 1] == "0":
continue
counter += self.num_arrays(s[i + 1:], k, memo)
ans = counter % (10 ** 9 + 7)
memo[s] = ans
return ans
def numberOfArrays(self, s: str, k: int) -> int:
memo = {}
return self.num_arrays(s, k, memo) | class Solution {
static long mod;
private long solve(int idx,String s,int k,long[] dp){
if(idx==s.length())
return 1;
if(dp[idx]!=-1)
return dp[idx];
long max=0,number=0;
for(int i=idx;i<s.length();i++){
int temp=s.charAt(i)-'0';
number=(number*10)+temp;
if(number>=1 && number<=k){
max=(max+solve(i+1,s,k,dp))%mod;
}else
break;
}
return dp[idx]=max;
}
public int numberOfArrays(String s, int k) {
mod = (int)1e9+7;
long[] dp=new long[s.length()+1];
Arrays.fill(dp,-1);
return (int)solve(0,s,k,dp);
}
} | class Solution {
public:
int mod=1e9+7;
int f(int i,int k,string &s,vector<int> &dp){
if(i==s.size()) return 1;//empty string
if(dp[i]!=-1) return dp[i];//Memoization step
if(s[i]=='0') return 0;//leading zeroes
long long num=0;
int ans=0;
for(int j=i;j<s.size();j++){
num=num*10+s[j]-'0';
if(num>k) break;
ans+=f(j+1,k,s,dp);//create num and call for next index
ans%=mod;
}
return dp[i]=ans;//storing answer
}
int numberOfArrays(string s, int k) {
int n=s.size();
vector<int> dp(n+1,-1);
return f(0,k,s,dp);
// dp[i]=total ways to
// create possible arrays starting at index i
}
}; | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var numberOfArrays = function(s, k) {
var cache={};
return backtrack(0)%1000000007;
function backtrack(pos){
let orignalPos = pos;
if(cache[pos]!==undefined){
return cache[pos];
}
let count=0;
let digit=0;
while(pos<s.length){
digit = digit*10 + parseInt(s[pos]);
if(digit<=k && pos+1<=s.length-1 && s[pos+1]!=='0'){//If we can call backtrack on next position.
count+=(backtrack(pos+1)%1000000007);
}
if(digit>k){
break;
}
pos++;
}
if(pos===s.length && digit<=k){//If this number became the only digit in the array, for string starting at position orignalPos. This also completed the etire string.
count++;
}
cache[orignalPos]=count;
return count;
}
}; | Restore The Array |
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.
Return the number of islands in grid2 that are considered sub-islands.
Example 1:
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
Example 2:
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
Constraints:
m == grid1.length == grid2.length
n == grid1[i].length == grid2[i].length
1 <= m, n <= 500
grid1[i][j] and grid2[i][j] are either 0 or 1.
| class Solution(object):
def countSubIslands(self, grid1, grid2):
m=len(grid1)
n=len(grid1[0])
def dfs(i,j):
if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:
return
grid2[i][j]=0
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j+1)
dfs(i,j-1)
# here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed
for i in range(m):
for j in range(n):
if grid2[i][j]==1 and grid1[i][j]==0:
dfs(i,j)
#now we just need to count the islands left over
count=0
for i in range(m):
for j in range(n):
if grid2[i][j]==1:
dfs(i,j)
count+=1
return count
| class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.length;
int n = grid1[0].length;
boolean[][] vis = new boolean[m][n];
int count = 0;
int[] dir = {1, 0, -1, 0, 1};
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(grid2[i][j] == 0 || vis[i][j])
continue;
Queue<int[]> queue = new LinkedList<>();
boolean flag = true;
vis[i][j] = true;
queue.add(new int[] {i, j});
while(!queue.isEmpty()) {
int[] vtx = queue.remove();
if(grid1[vtx[0]][vtx[1]] == 0)
flag = false;
for(int k = 0; k < 4; ++k) {
int x = vtx[0] + dir[k];
int y = vtx[1] + dir[k + 1];
if(x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && !vis[x][y]) {
vis[x][y] = true;
queue.add(new int[] {x, y});
}
}
}
if(flag)
++count;
}
}
return count;
}
} | class Solution {
public:
bool res;
void mark_current_island(vector<vector<int>>& grid1, vector<vector<int>>& grid2,int x,int y,int r,int c){
if(x<0 || x>=r || y<0 || y>=c || grid2[x][y]!=1) //Boundary case for matrix
return ;
//if there is water on grid1 for the location on B then our current island can't be counted and so we mark res as false
if(grid1[x][y]==0){
res=false;
return;
}
//Mark current cell as visited
grid2[x][y] = 0;
//Make recursive call in all 4 adjacent directions
mark_current_island(grid1,grid2,x+1,y,r,c); //DOWN
mark_current_island(grid1,grid2,x,y+1,r,c); //RIGHT
mark_current_island(grid1,grid2,x-1,y,r,c); //TOP
mark_current_island(grid1,grid2,x,y-1,r,c); //LEFT
}
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
//For FAST I/O
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int rows = grid1.size();
if(rows==0) //Empty grid boundary case
return 0;
int cols = grid1[0].size();
//Iterate for all cells of the array
int no_of_islands = 0;
//dfs on grid2
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
if(grid2[i][j]==1){
res=true;
mark_current_island(grid1,grid2,i,j,rows,cols);
//if current island of grid2 meets the requirement update the no of islands
if(res)
no_of_islands += 1;
}
}
}
return no_of_islands;
}
}; | var countSubIslands = function(grid1, grid2) {
const R = grid2.length, C = grid2[0].length;
// returns no of cells in grid 2 not covered in grid1
function noOfNotCoveredDfs(i, j) {
if (i < 0 || j < 0) return 0;
if (i >= R || j >= C) return 0;
if (grid2[i][j] !== 1) return 0;
// mark visited
grid2[i][j] = 2;
return (grid1[i][j] === 1 ? 0 : 1) +
noOfNotCoveredDfs(i - 1, j) +
noOfNotCoveredDfs(i + 1, j) +
noOfNotCoveredDfs(i, j - 1) +
noOfNotCoveredDfs(i, j + 1);
}
let ans = 0;
for (let i = 0; i < R; i++) {
for (let j = 0; j < C; j++) {
if (grid2[i][j] === 1) {
if (noOfNotCoveredDfs(i, j) === 0) {
ans++;
}
}
}
}
return ans;
}; | Count Sub Islands |
You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
Return true if it is possible to form a palindrome string, otherwise return false.
Notice that x + y denotes the concatenation of strings x and y.
Example 1:
Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
Example 2:
Input: a = "xbdef", b = "xecab"
Output: false
Example 3:
Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
Constraints:
1 <= a.length, b.length <= 105
a.length == b.length
a and b consist of lowercase English letters
| class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
def pal(x):
return x == x[::-1]
if pal(a) or pal(b): return True
# either grow from inside to outside, or vice versa
ina = len(a)-1
inb = 0
outa = 0
outb = len(b)-1
while a[ina] == b[inb]:
ina -= 1
inb += 1
if ina <= inb:
return True # short circuit found break point
# jump into each string now!?
# is a or b a palindrome in this portion from inb to ina
if pal(a[inb:ina+1]) or pal(b[inb:ina+1]):
return True # either one is breakpoint, so check remainder is palindrome
while a[outa] == b[outb]:
outa += 1
outb -= 1
if outa >= outb:
return True
if pal(a[outa:outb+1]) or pal(b[outa:outb+1]):
return True # either one is breakpoint, so check remainder
return False | class Solution {
public boolean checkPalindromeFormation(String a, String b) {
return split(a, b) || split(b, a);
}
private boolean split(String a, String b) {
int left = 0, right = a.length() - 1;
while (left < right && a.charAt(left) == b.charAt(right)) {
left++;
right--;
}
if (left >= right) return true;
return isPalindrome(a, left, right) || isPalindrome(b, left, right);
}
private boolean isPalindrome(String s, int left, int right) {
while (left <= right) {
if (s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
} | // samll trick: for plaindrome question always try to follow concept that if corners are equal we need to only work
// on middle string to check whether it is also palindrome, instead of check complete strings(both given strings).
class Solution {
public:
bool ispalind(string x, int i, int j){
while(i<j){
if(x[i]!=x[j]) return false;
i++;
j--;
}
return true;
}
bool checkpositions(string a, string b){
int i=0,j=b.size()-1;
while(i<j){
if(a[i]!=b[j]) break;
i++;
j--;
}
/*
left cut
//agar same hote toh
"ulacfd" ul.zalu //to check for palindrome : za(from b)
"jizalu" ji.acfd //to check for palindrome : ac(from a)
*/
/*
right cut
//agar samee hote toh
"ulacfd" jiza.fd //to check for palindrome : za(from b)
"jizalu" ulac.lu //to check for palindrome : ac(from a)
*/
return ispalind(a,i,j) || ispalind(b,i,j);
}
bool checkPalindromeFormation(string a, string b) {
//cut one(from left) //cut two(from right)
return checkpositions(a,b)||checkpositions(b,a);
}
}; | var checkPalindromeFormation = function(a, b) {
function isPal(str, l, r) {
while (l < r) {
if (str[l] === str[r]) l++, r--;
else return false;
} return true;
}
// aprefix + bsuffix
let l = 0, r = b.length - 1;
while (l < r && a[l] === b[r]) l++, r--;
if (isPal(a, l, r) || isPal(b, l, r)) return true;
// bprefix + asuffix
l = 0, r = a.length - 1;
while (l < r && b[l] === a[r]) l++, r--;
if (isPal(a, l, r) || isPal(b, l, r)) return true;
return false;
}; | Split Two Strings to Make Palindrome |
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
Example 1:
Input: s = "leetcodecom"
Output: 9
Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.
The product of their lengths is: 3 * 3 = 9.
Example 2:
Input: s = "bb"
Output: 1
Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.
The product of their lengths is: 1 * 1 = 1.
Example 3:
Input: s = "accbcaxxcxx"
Output: 25
Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.
The product of their lengths is: 5 * 5 = 25.
Constraints:
2 <= s.length <= 12
s consists of lowercase English letters only.
| class Solution:
def maxProduct(self, s: str) -> int:
# n <= 12, which means the search space is small
n = len(s)
arr = []
for mask in range(1, 1<<n):
subseq = ''
for i in range(n):
# convert the bitmask to the actual subsequence
if mask & (1 << i) > 0:
subseq += s[i]
if subseq == subseq[::-1]:
arr.append((mask, len(subseq)))
result = 1
for (mask1, len1), (mask2, len2) in product(arr, arr):
# disjoint
if mask1 & mask2 == 0:
result = max(result, len1 * len2)
return result | class Solution {
int res = 0;
public int maxProduct(String s) {
char[] strArr = s.toCharArray();
dfs(strArr, 0, "", "");
return res;
}
public void dfs(char[] strArr, int i, String s1, String s2){
if(i >= strArr.length){
if(isPalindromic(s1) && isPalindromic(s2))
res = Math.max(res, s1.length()*s2.length());
return;
}
dfs(strArr, i+1, s1 + strArr[i], s2);
dfs(strArr, i+1, s1, s2 + strArr[i]);
dfs(strArr, i+1, s1, s2);
}
public boolean isPalindromic(String str){
int j = str.length() - 1;
char[] strArr = str.toCharArray();
for (int i = 0; i < j; i ++){
if (strArr[i] != strArr[j])
return false;
j--;
}
return true;
}
} | class Solution {
public:
int lca(string &s)
{
int n=s.size();
string s1=s;
string s2=s;
reverse(s2.begin(),s2.end());
int dp[s.size()+1][s.size()+1];
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
dp[i][j]=(s1[i-1]==s2[j-1])?1+dp[i-1][j-1]:max(dp[i][j-1],dp[i-1][j]);
}
}
return dp[n][n];
}
int maxProduct(string s)
{
int ans=0;
int n=s.size();
for(int i=1;i<(1<<n)-1;i++)
{
string s1="",s2="";
for(int j=0;j<n;j++)
{
if(i&(1<<j))
{
s1.push_back(s[j]);
}
else
{
s2.push_back(s[j]);
}
}
ans=max(ans,lca(s1)*lca(s2));
}
return ans;
}
}; | /**
* @param {string} s
* @return {number}
*/
var maxProduct = function(s) {
const n = s.length;
let map = new Map();
let res = 0;
for(let mask = 1; mask < 2 ** n;mask++){
let str = "";
for(let i = 0; i < n;i++){
if(mask & (1 << i)){
str += s.charAt(n - 1 - i);
}
}
if(isPalindrom(str)){
let length = str.length;
map.set(mask,length);
}
}
map.forEach((l1,m1) => {
map.forEach((l2,m2) => {
if((m1 & m2) == 0){
res = Math.max(res,l1 * l2);
}
})
})
return res;
};
function isPalindrom(str){
let l = 0;
let r = str.length - 1;
while(l < r){
if(str.charAt(l) != str.charAt(r)){
return false;
}
l++;
r--;
}
return true;
} | Maximum Product of the Length of Two Palindromic Subsequences |
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| class Solution:
def getMaxLen(self, arr: List[int]) -> int:
n=len(arr)
def solve(nums):
i,j,last_neg,neg,ans=0,0,None,0,0
while j<n:
while j<n and nums[j]!=0:
if nums[j]<0:
neg+=1
last_neg=j
j+=1
if neg%2==0:
ans=max(ans,j-i)
elif last_neg!=None:
ans=max(ans,last_neg-i,j-last_neg-1)
i,j,neg,last_neg=j+1,j+1,0,None
return ans
return max(solve(arr),solve(arr[::-1]))
| class Solution {
public int getMaxLen(int[] nums)
{
int first_negative=-1;
int zero_position=-1;
int count_neg=0;
int res=0;
for(int i=0;i<nums.length;i++)
{
if (nums[i]<0)
{
count_neg = count_neg+1;
if(first_negative==-1)
{
first_negative=i;
}
}
if (nums[i]==0)
{
count_neg = 0;
zero_position=i;
first_negative=-1;
}
else
{
if (count_neg%2==0)
{
res=Math.max(i-zero_position,res);
}
else
{
res=Math.max(i-first_negative,res);
}
}
}
return res;
}
} | class Solution {
public:
int getMaxLen(vector<int>& nums) {
int ans = 0;
int lprod = 1,rprod = 1;
int llen = 0, rlen = 0;
int n = nums.size();
for(int i = 0 ; i < n ; i++){
lprod *= nums[i] != 0 ? nums[i]/abs(nums[i]) : 0;
rprod *= nums[n-1-i] != 0 ? nums[n-1-i]/abs(nums[n-1-i]) : 0;
if(lprod != 0) llen ++;
if(rprod != 0) rlen ++;
if(lprod > 0) ans = max(ans,llen);
if(rprod > 0) ans = max(ans,rlen);
if(lprod == 0) {
lprod = 1;
llen = 0;
}
if(rprod == 0){
rlen = 0;
rprod = 1;
}
}
return ans;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var getMaxLen = function(nums) {
let leftToRight=0,p=1,count=0,max=0,item;
//Process elements from left to right
for(let i=0;i<nums.length;i++){
if(nums[i]===0){
p=0;
}else if(nums[i]>0){
p *=1
}else if(nums[i]<0){
p *=-1
}
count++;
if(p>0){
max = Math.max(max,count);
}
if(p===0){
p=1;
count=0;
}
}
count = 0;p=1;
//Process elements from right to left
for(let i=nums.length-1;i>=0;i--){
if(nums[i]===0){
p=0;
}else if(nums[i]>0){
p *=1
}else if(nums[i]<0){
p *=-1
}
count++;
if(p>0){
max = Math.max(max,count);
}
if(p===0){
p=1;
count=0;
}
}
return max;
}; | Maximum Length of Subarray With Positive Product |
Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
Example 2:
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
Example 3:
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000
| class Solution:
def findGCD(self, nums: List[int]) -> int:
i_min = min(nums)
i_max = max(nums)
greater = i_max
while True:
if greater % i_min == 0 and greater % i_max == 0:
lcm = greater
break
greater += 1
return int(i_min/(lcm/i_max)) | class Solution {
public int findGCD(int[] nums) {
Arrays.sort(nums);
int n=nums[nums.length-1];
int result=nums[0];
while(result>0){
if(nums[0]%result==0 && n%result==0){
break;
}
result--;
}
return result;
}
} | class Solution {
public:
int findGCD(vector<int>& nums) {
int mn = nums[0], mx = nums[0];
for(auto n: nums)
{
// finding maximum, minimum values of the array.
if(n > mx) mx = n;
if(n < mn) mn = n;
}
for(int i = mn; i >= 1; i--)
{
// finding greatest common divisor (GCD) of max, min.
if((mn % i == 0) && (mx % i == 0)) return i;
}
return 1;
}
}; | var findGCD = function(nums) {
let newNum = [Math.min(...nums) , Math.max(...nums)]
let firstNum = newNum[0]
let secondNum = newNum[1]
while(secondNum) {
let newNum = secondNum;
secondNum = firstNum % secondNum;
firstNum = newNum;
}
return firstNum
}; | Find Greatest Common Divisor of Array |
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
Example 1:
Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Constraints:
2 <= tops.length <= 2 * 104
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
| class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]
same_count = collections.Counter(sames)
bottom_count = collections.Counter(bottoms)
top_count = collections.Counter(tops)
for n in range(1,7):
if bottom_count[n] + top_count[n] - same_count[n] == len(tops):
return min(bottom_count[n], top_count[n]) - same_count[n]
return -1 | class Solution {
public int minDominoRotations(int[] tops, int[] bottoms) {
int[][] c = new int[6][2];
for (int i : tops) {
c[i - 1][0]++;
}
for (int i : bottoms) {
c[i - 1][1]++;
}
int[] common = new int[6];
for (int i = 0; i < tops.length; i++) {
if (tops[i] == bottoms[i]) {
common[tops[i] - 1]++;
}
}
int min = Integer.MAX_VALUE;
for (int i = 1; i <= 6; i++) {
if (c[i - 1][0] + c[i - 1][1] >= tops.length) {
if (c[i - 1][0] >= c[i - 1][1] && c[i - 1][1] - common[i - 1] + c[i - 1][0] == tops.length) {
min = Math.min(min, c[i - 1][1] - common[i - 1]);
}
else if (c[i - 1][1] >= c[i - 1][0] && c[i - 1][0] - common[i - 1] + c[i - 1][1] == tops.length) {
int left = c[i - 1][0] - common[i - 1];
min = Math.min(min, c[i - 1][0] - common[i - 1]);
}
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
} | class Solution {
public:
int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {
vector<int> freq(7, 0);
int n = tops.size();
int tile = -1
// there has to be particular tile number which is present in every column to be able to arrange same tile in top or bottom by rotating
// check which tile is present in every column
for(int i=0; i<n; ++i){
int top = tops[i];
int bottom = bottoms[i];
freq[top]++;
if(top != bottom){
freq[bottom]++;
}
// check for potential tile number
if(freq[top] == n){
tile = top;
}
if(freq[bottom] == n){
tile = bottom;
}
}
if(tile == -1){ // rearrangement not possible
return -1;
}
int tilesTop = 0;
int tilesBottom = 0;
for(int i=0; i<n; ++i){
if(tops[i] == bottoms[i])continue;
if(tops[i] == tile){
tilesTop++;
}
if(bottoms[i] == tile){
tilesBottom++;
}
}
return tilesTop < tilesBottom ? tilesTop : tilesBottom;
}
}; | /**
* @param {number[]} tops
* @param {number[]} bottoms
* @return {number}
*/
var minDominoRotations = function(tops, bottoms) {
const swaps = Math.min(
minimum(tops[0], tops, bottoms),
minimum(tops[0], bottoms, tops),
minimum(bottoms[0], tops, bottoms),
minimum(bottoms[0], bottoms, tops)
);
return swaps === Infinity ? -1 : swaps;
function minimum(target, x, y, count = 0) {
for(let i = 0; i < x.length; i++) {
if(target !== x[i]) {
if (target !== y[i]) return Infinity
count++;
}
}
return count;
}
}; | Minimum Domino Rotations For Equal Row |
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext.
In text form, it looks like this (with ⟶ representing the tab character):
dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext
If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters.
Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces.
Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.
Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.
Example 1:
Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
Output: 20
Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.
Example 2:
Input: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
Output: 32
Explanation: We have two files:
"dir/subdir1/file1.ext" of length 21
"dir/subdir2/subsubdir2/file2.ext" of length 32.
We return 32 since it is the longest absolute path to a file.
Example 3:
Input: input = "a"
Output: 0
Explanation: We do not have any files, just a single directory named "a".
Constraints:
1 <= input.length <= 104
input may contain lowercase or uppercase English letters, a new line character '\n', a tab character '\t', a dot '.', a space ' ', and digits.
All file and directory names have positive length.
| class Solution:
def lengthLongestPath(self, input: str) -> int:
if "." not in input:
return 0
a=input.split("\n")
files=[]
for i in a:
if "." in i:
files.append(i)
final=[]
for i in range(len(files)):
file=files[i]
lvl=file.count("\t")
idx=a.index(file)-1
save=[files[i].replace("\t","")]
for j in range(lvl):
while a[idx].count("\t")!=lvl-1:
idx-=1
lvl=a[idx].count("\t")
save.append(a[idx].replace("\t",""))
idx-=1
final.append(save)
final=list(map("/".join,final))
return len(max(final,key=len)) | class Solution {
public int lengthLongestPath(String input) {
var stack = new ArrayDeque<Integer>();
int max = 0;
String[] lines = input.split("\n");
for(var line: lines) {
int tabs = countTabs(line);
while(tabs < stack.size()) {
stack.pop();
}
int current = stack.isEmpty() ? 0: stack.peek();
int nameLength = line.length() - tabs;
if(isFilename(line)) {
max = Math.max(max, current + nameLength);
} else {
stack.push(current + nameLength + 1);
}
}
return max;
}
private int countTabs(String s) {
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\t') return i;
}
return 0;
}
private boolean isFilename(String s) {
return s.lastIndexOf(".") != -1;
}
} | // Using Map O(300 + N)
class Solution {
public:
int lengthLongestPath(string input) {
input.push_back('\n');
vector<int> levels(301, 0);
int ans = 0;
int curr_tabs = 0;
bool is_file = false;
int curr_word_len = 0;
int total_len = 0;
for(char c : input)
{
if(c == '\t')
{
curr_tabs++;
}
else if(c == '\n')
{
if(curr_tabs == 0)
{
levels[0] = curr_word_len;
}
else
{
levels[curr_tabs] = levels[curr_tabs-1] + curr_word_len;
}
if(is_file)
{
ans = max(ans, levels[curr_tabs] + curr_tabs);
// levels[curr_tabs] = 0;
}
curr_tabs = 0;
is_file = false;
curr_word_len = 0;
}
else if(c == '.')
{
is_file = true;
curr_word_len++;
}
else
{
curr_word_len++;
}
}
return ans;
}
}; | function isFile(path) {
return path.includes('.')
}
var lengthLongestPath = function(input) {
const segments = input.split('\n');
let max = 0;
let path = [];
for (const segment of segments) {
if (segment.startsWith('\t')) {
const nesting = segment.match(/\t/g).length;
while (nesting < path.length) {
path.pop();
}
path.push(segment.replace(/\t/g, ''))
} else {
path = [segment]
}
if (isFile(path.at(-1))) {
const filePath = path.join('/');
if (filePath.length > max) {
max = filePath.length;
}
}
}
return max;
}; | Longest Absolute File Path |
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.
Return the maximum distance between two houses with different colors.
The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Example 1:
Input: colors = [1,1,1,6,1,1,1]
Output: 3
Explanation: In the above image, color 1 is blue, and color 6 is red.
The furthest two houses with different colors are house 0 and house 3.
House 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.
Note that houses 3 and 6 can also produce the optimal answer.
Example 2:
Input: colors = [1,8,3,8,3]
Output: 4
Explanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.
The furthest two houses with different colors are house 0 and house 4.
House 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.
Example 3:
Input: colors = [0,1]
Output: 1
Explanation: The furthest two houses with different colors are house 0 and house 1.
House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.
Constraints:
n == colors.length
2 <= n <= 100
0 <= colors[i] <= 100
Test data are generated such that at least two houses have different colors.
| class Solution:
def maxDistance(self, colors: List[int]) -> int:
p, res = inf, 0
for i, c in enumerate(colors):
if (c != colors[0]):
res = i
p = min(p, i)
else:
res = max(res, i - p)
return res | class Solution {
public int maxDistance(int[] colors) {
int l = 0, r = colors.length-1;
while(colors[colors.length-1] == colors[l]) l++;
while(colors[0] == colors[r]) r--;
return Math.max(r, colors.length - 1 - l);
}
} | class Solution {
public:
int maxDistance(vector<int>& colors) {
int Max = INT_MIN;
int N = colors.size();
// find the first house from the end which does not match the color of house at front
int j=N;
while(--j>=0 && colors[0]==colors[j]) { } // worst-case O(n)
Max = abs(j-0);
// find the first house from the front which does not match the color of house at back
j=-1;
while(++j<N && colors[N-1]==colors[j]) { } // worst-case O(n)
Max = max(Max, abs(j-(N-1)));
return Max;
}
}; | var maxDistance = function(colors) {
// using two pointers from start and end
// Time complexity O(n)
// Space complexity O(1)
const start = 0;
const end = colors.length - 1;
// maximum distance possible is length of arr, so start with two pointer
// one at the start and one at the end
const startColor = colors[start];
const endColor = colors[end];
// base condition, to check if they are not already equal
if (startColor !== endColor) {
return end;
}
// move the forward pointer till we find the differend color
let forwardPtr = start;
while (startColor === colors[forwardPtr]) {
++forwardPtr;
}
// move the backward pointer till we find the differend color
let backwardPtr = end;
while(endColor === colors[backwardPtr]) {
--backwardPtr;
}
// Till here, We already know that startColor === endColor
// hence we did two things,
// 1. we kept startColor fixed and moved backwardPtr till we find different color
// 2. similarly, we kept endColor fixed and moved the forwardPtr till we find the different color.
// we will return the max different out of two now.
return Math.max(Math.abs(start - backwardPtr), Math.abs(end - forwardPtr));
}; | Two Furthest Houses With Different Colors |
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.
For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".
Example 2:
Input: words = ["a"]
Output: 1
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] consists of lowercase English letters.
| class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
code = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--","-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
out = []
for word in words:
res = [code[ord(char)-ord('a')] for char in word]
out.append("".join(res))
return len(set(out)) | class Solution {
public int uniqueMorseRepresentations(String[] words) {
HashSet<String> set = new HashSet<>();
String[] morse = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
for (int i = 0; i < words.length; ++i) {
String temp = "";
for (int j = 0; j < words[i].length(); ++j) {
temp += morse[(int)words[i].charAt(j)-'a'];
}
set.add(temp);
}
return set.size();
}
} | class Solution {
public:
string convert(string st)
{
string s1[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
string s="";
for(char a:st)
{
s+=s1[a - 'a'];
}
return s;
}
int uniqueMorseRepresentations(vector<string>& words) {
set<string>st;
for(int i=0;i<words.size();i++)
{
st.insert(convert(words[i]));
}
return st.size();
}
}; | var uniqueMorseRepresentations = function(words) {
var morse = [".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."];
var transformations = new Set();
for (let word of words) {
var trans = "";
for (let letter of word) {
var index = letter.charCodeAt(0) - 97;
trans += morse[index];
}
transformations.add(trans);
}
return transformations.size;
}; | Unique Morse Code Words |
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Example 1:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After the rain, water is trapped between the blocks.
We have two small ponds 1 and 3 units trapped.
The total volume of water trapped is 4.
Example 2:
Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
Output: 10
Constraints:
m == heightMap.length
n == heightMap[i].length
1 <= m, n <= 200
0 <= heightMap[i][j] <= 2 * 104
| import heapq
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
ROW, COL = len(heightMap), len(heightMap[0])
pq = []
heapq.heapify(pq)
visited = {}
for row in range(ROW):
for col in range(COL):
if row == 0 or row == ROW-1 or col == 0 or col == COL-1:
heapq.heappush(pq, (heightMap[row][col],row,col))
visited[(row,col)] = True
def getnbr(row,col):
res = []
if row-1 >=0:
res.append((row-1,col))
if col-1 >=0:
res.append((row, col-1))
if row+1 < ROW:
res.append((row+1,col))
if col+1 < COL:
res.append((row, col+1))
return res
res = 0
while pq:
h, i, j = heapq.heappop(pq)
for dx, dy in getnbr(i,j):
if (dx,dy) not in visited:
res += max(0, h-heightMap[dx][dy])
heapq.heappush(pq, (max(h, heightMap[dx][dy]),dx,dy))
visited[(dx,dy)] = True
return res | class Solution {
public class pair implements Comparable<pair>{
int row;
int col;
int val;
pair(int row, int col,int val){
this.row = row;
this.col = col;
this.val = val;
}
public int compareTo(pair o){
return this.val - o.val;
}
}
int[][] dir = {{1,0},{0,-1},{-1,0},{0,1}};
public int trapRainWater(int[][] heightMap) {
int n = heightMap.length;
int m = heightMap[0].length;
PriorityQueue<pair> pq = new PriorityQueue<>();
boolean[][] visited = new boolean[n][m];
// add all the boundary elements in pq
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(i == 0 || j == 0 || i == n-1 || j == m-1){
pq.add(new pair(i, j, heightMap[i][j]));
visited[i][j] = true;
}
}
}
int ans = 0;
while(pq.size() > 0){
pair rem = pq.remove();
for(int i = 0; i < 4; i++){
int rowdash = rem.row + dir[i][0];
int coldash = rem.col + dir[i][1];
if(rowdash >= 0 && coldash >= 0 && rowdash < n && coldash < m && visited[rowdash][coldash] == false){
visited[rowdash][coldash] = true;
if(heightMap[rowdash][coldash] >= rem.val){
pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated
}else{
int waterstored = rem.val - heightMap[rowdash][coldash];
ans += waterstored; // now this will act as a wall add in pq
pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));
}
}
}
}
return ans;
}
} | class Solution {
public:
bool vis[201][201]; //to keep track of visited cell
int n,m;
bool isValid(int i, int j){
if(i<0 || i>=m || j<0 || j>=n || vis[i][j]==true) return false;
return true;
}
int trapRainWater(vector<vector<int>>& heightMap) {
vector<vector<int>> dir {{1,0},{-1,0},{0,1},{0,-1}}; //direction Vector
m = heightMap.size(); if(m==0) return 0; // m=0 is one edge case
n = heightMap[0].size();
memset(vis,false,sizeof(vis));
priority_queue<pair<int,pair<int,int>> , vector<pair<int,pair<int,int>>> , greater<pair<int,pair<int,int>>> >pq; // min heap w.r.t cell height
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0 || j==0 || i==m-1 || j==n-1){
pq.push({heightMap[i][j],{i,j}}); //pushing all outer cells in pq
vis[i][j]=true;
}
}
}
int water = 0;
int Height = INT_MIN;
while(!pq.empty()){ //normal BFS
auto pr = pq.top();
pq.pop();
int height = pr.first;
int i = pr.second.first;
int j = pr.second.second;
Height = max(Height,height);
for(int d=0;d<4;d++){ //iterating through direction vector
int x = i + dir[d][0];
int y = j + dir[d][1];
if(isValid(x,y)){
water += max(0, Height - heightMap[x][y]); //just adding the diff between cell height and surrounding height
vis[x][y]=true;
pq.push({heightMap[x][y],{x,y}});
}
}
}
return water;
}
}; | const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];
const MAX = 200 * 201; // n * m + m
const trapRainWater = (g) => {
let n = g.length, m = g[0].length;
if (n == 0) return 0;
let res = 0, max = Number.MIN_SAFE_INTEGER;
let pq = new MinPriorityQueue({priority: x => x[0] * MAX + x[1]}); // first priority: x[0], smaller comes first. second priority: x[1], smaller comes first
let visit = initialize2DArrayNew(n, m);
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
pq.enqueue([g[i][j], i * m + j]);
visit[i][j] = true;
}
}
}
while (pq.size()) { // BFS
let cur = pq.dequeue().element;
let h = cur[0], r = cur[1] / m >> 0, c = cur[1] % m; // height row column
max = Math.max(max, h);
for (let k = 0; k < 4; k++) {
let x = r + dir[k][0], y = c + dir[k][1];
if (x < 0 || x >= n || y < 0 || y >= m || visit[x][y]) continue;
visit[x][y] = true;
if (g[x][y] < max) res += max - g[x][y];
pq.enqueue([g[x][y], x * m + y]);
}
}
return res;
};
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(false); data.push(tmp); } return data; }; | Trapping Rain Water II |
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
| class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
flag, rowNum, colNum = True, len(mat), len(mat[0])
total, ans = 0, []
while total <= rowNum + colNum - 2:
iLimited = rowNum - 1 if flag else colNum - 1
jLimited = colNum - 1 if flag else rowNum - 1
i = total if total < iLimited else iLimited
j = total - i
while i >= 0 and j <= jLimited:
if flag:
ans.append(mat[i][j])
else:
ans.append(mat[j][i])
i -= 1
j += 1
total += 1
flag = not flag
return ans | /**
* Simulate Diagonal Order Traversal
*
* r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all
* on same diagonal with r+c =2. If you check the directions of diagonals, first
* diagonal is up, second diagonal is down, third one is up and so on..
* Therefore (r+c)%2 simply determines direction. Even is UP direction. Odd is
* DOWN direction.
*
* Time Complexity: O(M*N)
*
* Space Complexity: O(1) without considering result space.
*
* M = Number of rows. N = Number of columns.
*/
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null) {
throw new IllegalArgumentException("Input matrix is null");
}
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[] result = new int[rows * cols];
int r = 0;
int c = 0;
for (int i = 0; i < result.length; i++) {
result[i] = matrix[r][c];
if ((r + c) % 2 == 0) { // Move Up
if (c == cols - 1) {
// Reached last column. Now move to below cell in the same column.
// This condition needs to be checked first due to top right corner cell.
r++;
} else if (r == 0) {
// Reached first row. Now move to next cell in the same row.
c++;
} else {
// Somewhere in middle. Keep going up diagonally.
r--;
c++;
}
} else { // Move Down
if (r == rows - 1) {
// Reached last row. Now move to next cell in same row.
// This condition needs to be checked first due to bottom left corner cell.
c++;
} else if (c == 0) {
// Reached first columns. Now move to below cell in the same column.
r++;
} else {
// Somewhere in middle. Keep going down diagonally.
r++;
c--;
}
}
}
return result;
}
} | class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
vector<int>vec;
int m=mat.size()-1,n=mat[0].size()-1;
int i=0,j=0;
if(m==-1){
return {};
}
if(m==0){
for(int i{0};i<=n;++i){
vec.push_back(mat.at(0).at(i));
}
return vec;
}else if(n==0){
for(int i{0};i<=m;++i){
vec.push_back(mat.at(i).at(0));
}
return vec;
}
for(int k{0};k<=m+n;k++){
if(k==0){
vec.push_back(mat.at(0).at(0));
j++;
}else if(k==m+n){
vec.push_back(mat.at(m).at(n));
}else if(k%2!=0){
while(i<=m && j>=0 && j<=n){
vec.push_back(mat.at(i).at(j));
i++;
j--;
}
if(i<=m && j<0){
j++;
}else if(i>m &&j>=0){
j+=2;
i--;
}else if(i>m && j<0){
i--;
j+=2;
}
}else{
while(i>=0 && j<=n){
vec.push_back(mat.at(i).at(j));
i--;
j++;
}
if(i<0 &&j<=n){
i++;
}else if(i<0 && j>n){
i+=2;
j--;
}else if(i>m && j<0){
i--;
j+=2;
}else if(i>=0 && j>n){
i+=2;
j--;
}
}
}
return vec;
}
}; | var findDiagonalOrder = function(matrix) {
const res = [];
for (let r = 0, c = 0, d = 1, i = 0, len = matrix.length * (matrix[0] || []).length; i < len; i++) {
res.push(matrix[r][c]);
r -= d;
c += d;
if (!matrix[r] || matrix[r][c] === undefined) { // We've fallen off the...
if (d === 1) {
if (matrix[r + 1] && matrix[r + 1][c] !== undefined) { // ...top cliff
r++;
} else { // ...right cliff
r += 2;
c--;
}
} else {
if (matrix[r] && matrix[r][c + 1] !== undefined) { // ...left cliff
c++;
} else { // ...bottom cliff
r--;
c += 2;
}
}
d = -d;
}
}
return res;
}; | Diagonal Traverse |
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
All the pairs prerequisites[i] are unique.
| class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
pre = {} # course: list of prerequisites
dep = {} # course: list of dependents
for p in prerequisites:
if p[0] not in pre:
pre[p[0]] = set()
if p[1] not in dep:
dep[p[1]] = set()
pre[p[0]].add(p[1])
dep[p[1]].add(p[0])
# Kahn's algorithm
l = []
s = set()
for i in range(numCourses):
if i not in dep: # if no dependents (incoming edge)
s.add(i)
while s:
n = s.pop()
l.append(n)
if n in pre: # if n has prerequisites
for m in pre[n]: # for each prerequisites m
dep[m].remove(n) # remove n from m's dependents list
if not dep[m]: # if m has no more dependents
s.add(m)
return len(l) == numCourses | class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int n = numCourses;
boolean [] visited = new boolean[n];
boolean [] dfsVisited = new boolean[n];
List<List<Integer>> adj = createAdjList(n,prerequisites);
for(int i=0;i<n;i++){
if(visited[i]==false){
if(isCycle(i,adj,visited,dfsVisited)){
return false;
}
}
}
return true;
}
//find cycle in a directed graph
private boolean isCycle(int s,List<List<Integer>> adj,boolean [] visited,boolean[] dfsVisited){
visited[s]=true;
dfsVisited[s]=true;
for(int v:adj.get(s)){
if(visited[v]==false){
if(isCycle(v,adj,visited,dfsVisited)){
return true;
}
}else if(visited[v]==true && dfsVisited[v]==true) {
return true;
}
}
dfsVisited[s]=false;
return false;
}
private List<List<Integer>> createAdjList(int n,int[][] prerequisites){
List<List<Integer>> adj = new ArrayList();
for(int i=0;i<n;i++){
adj.add(new ArrayList<>());
}
for(int[] e : prerequisites){
adj.get(e[1]).add(e[0]);
}
return adj;
}
} | class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
map<int, vector<int>>adj;
vector<int> indegree(numCourses,0);
vector<int>res;
for(int i=0;i<prerequisites.size();i++){
adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
indegree[prerequisites[i][0]]++;
}
queue<int> q;
for(int i=0;i<numCourses;i++){
if(indegree[i]==0)
q.push(i);
}
while(!q.empty()){
int x=q.front();
q.pop();
res.push_back(x);
for(auto u:adj[x]){
indegree[u]--;
if(indegree[u]==0){
q.push(u);
}
}
}
return res.size()==numCourses;
}
}; | var canFinish = function(numCourses, prerequisites) {
const adjList = []
const visit = []
construAdj()
for (let i = 0; i < numCourses; i++) {
if (!dfs(i)) return false
}
return true
function dfs(i) {
// base case
if (visit[i]) return false
if (visit[i] === false) return true
visit[i] = true
for (const nei of adjList[i] ?? []) {
if (!dfs(nei)) return false
}
visit[i] = false
return true
}
function construAdj() {
for (const pre of prerequisites) {
if (!adjList[pre[0]]) adjList[pre[0]] = []
adjList[pre[0]].push(pre[1])
}
}
}; | Course Schedule |
Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it does from right to left.
For example, 101 and 12321 are palindromes.
The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].
Example 1:
Input: n = 6
Output: 7
Example 2:
Input: n = 8
Output: 11
Example 3:
Input: n = 13
Output: 101
Constraints:
1 <= n <= 108
| class Solution:
def primePalindrome(self, n: int) -> int:
if n<3:return 2
#generating palindrome less than 10**8
l=[""]+[*"1234567890"]
for i in l:
if len(i)<7:
for j in "1234567890":
l+=[j+i+j]
#finding prime from generated palindrome
q=[]
for i in l[2:]:
if i[0]!="0":
i=int(i)
t=i%2
if t:
for j in range(3,int(i**.5)+1,2):
if i%j==0:
t=0
break
if t:q+=[i]
q.sort()
q+=[100030001]
return q[bisect_left(q,n)] | // Prime Palindrome
// Leetcode problem: https://leetcode.com/problems/prime-palindrome/
class Solution {
public int primePalindrome(int n) {
while (true) {
if (isPrime(n) && isPalindrome(n)) {
return n;
}
n++;
}
}
private boolean isPrime(int n) {
if (n == 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
private boolean isPalindrome(int n) {
String s = String.valueOf(n);
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
} | class Solution {
public:
bool isPrime(int N) {
if (N < 2) return false;
int R = (int)sqrt(N);
for (int d = 2; d <= R; ++d)
if (N % d == 0) return false;
return true;
}
public:
int reverse(int N) {
int ans = 0;
while (N > 0) {
ans = 10 * ans + (N % 10);
N /= 10;
}
return ans;
}
public:
int primePalindrome(int n) {
while (true) {
if (n == reverse(n) && isPrime(n))
return n;
n++;
// Any even length palindrome must be divisble by 11
// so we will skip numbers N = [10,000,000, 99,999,999]
if (10000000 < n && n < 100000000)
n = 100000000;
}
}
}; | /**
* @param {number} n
* @return {number}
*/
var primePalindrome = function(n) {
while (true){
let str = String(n)
if (String(n).length % 2 == 0 && n > 11){
n = Math.pow(10, Math.ceil(Math.log10(n+1)))
// or n = 1 + Array(str.length).fill(0).join("")
continue
}
if (!isPalindrome(str)) {
n++
continue
}
if (isPrime(n)) return n
n++
}
};
function isPrime(n){
if (n <= 1) return false
if (n <= 3) return true
if (n % 2 == 0 || n % 3 == 0) return false
for (let i = 3; i <= Math.floor(Math.sqrt(n)) + 1;i+=2){
if (n % i == 0) return false
}
return true
}
function isPalindrome(str){
let l = 0, r = str.length-1
while (l < r){
if (str[l] != str[r]) return false
l++
r--
}
return true
} | Prime Palindrome |
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output: ["1","2","Fizz"]
Example 2:
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
1 <= n <= 104
| class Solution:
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
result.append('FizzBuzz')
elif i % 3 == 0:
result.append('Fizz')
elif i % 5 == 0:
result.append('Buzz')
else:
result.append(str(i))
return result | class Solution {
public List<String> fizzBuzz(int n) {
List<String> l=new ArrayList<>();
for(int i=1,fizz=0,buzz=0;i<=n;i++)
{
fizz++;
buzz++;
if(fizz==3 && buzz==5)
{
l.add("FizzBuzz");
fizz=0;
buzz=0;
}
else if(fizz==3)
{
l.add("Fizz");
fizz=0;
}
else if(buzz==5)
{
l.add("Buzz");
buzz=0;
}
else{
l.add(String.valueOf(i));
}
}
return l;
}
} | class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ans;
string hehe;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 and i % 5 == 0) hehe += "FizzBuzz";
else if (i % 3 == 0) hehe += "Fizz";
else if (i % 5 == 0) hehe += "Buzz";
else hehe = to_string(i);
ans.push_back(hehe);
hehe = "";
}
return ans;
}
}; | /**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function(n) {
let arr = []
for (let i = 1; i <= n; i++){
if(i % 3 == 0 && i % 5 == 0){
arr[i-1] = "FizzBuzz"
}else if(i % 3 == 0 && i % 5 != 0){
arr[i-1] = "Fizz"
}else if(i % 3 != 0 && i % 5 == 0){
arr[i-1] = "Buzz"
}else{
arr[i-1] = String(i)
}
}
return arr
}; | Fizz Buzz |
You are playing a variation of the game Zuma.
In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On each turn:
Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.
If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.
If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.
If there are no more balls on the board, then you win the game.
Repeat this process until you either win or do not have any more balls in your hand.
Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.
Example 1:
Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: It is impossible to clear all the balls. The best you can do is:
- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.
- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.
There are still balls remaining on the board, and you are out of balls to insert.
Example 2:
Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: To make the board empty:
- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.
- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.
2 balls from your hand were needed to clear the board.
Example 3:
Input: board = "G", hand = "GGGGG"
Output: 2
Explanation: To make the board empty:
- Insert 'G' so the board becomes GG.
- Insert 'G' so the board becomes GGG. GGG -> empty.
2 balls from your hand were needed to clear the board.
Constraints:
1 <= board.length <= 16
1 <= hand.length <= 5
board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.
The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
| class Solution:
def findMinStep(self, board: str, hand: str) -> int:
# start from i and remove continues ball
def remove_same(s, i):
if i < 0:
return s
left = right = i
while left > 0 and s[left-1] == s[i]:
left -= 1
while right+1 < len(s) and s[right+1] == s[i]:
right += 1
length = right - left + 1
if length >= 3:
new_s = s[:left] + s[right+1:]
return remove_same(new_s, left-1)
else:
return s
hand = "".join(sorted(hand))
# board, hand and step
q = collections.deque([(board, hand, 0)])
visited = set([(board, hand)])
while q:
curr_board, curr_hand, step = q.popleft()
for i in range(len(curr_board)+1):
for j in range(len(curr_hand)):
# skip the continue balls in hand
if j > 0 and curr_hand[j] == curr_hand[j-1]:
continue
# only insert at the begin of continue balls in board
if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color
continue
pick = False
# 1. same color with right
# 2. left and right are same but pick is different
if i < len(curr_board) and curr_board[i] == curr_hand[j]:
pick = True
if 0<i<len(curr_board) and curr_board[i-1] == curr_board[i] and curr_board[i] != curr_hand[j]:
pick = True
if pick:
new_board = remove_same(curr_board[:i] + curr_hand[j] + curr_board[i:], i)
new_hand = curr_hand[:j] + curr_hand[j+1:]
if not new_board:
return step + 1
if (new_board, new_hand) not in visited:
q.append((new_board, new_hand, step+1))
visited.add((new_board, new_hand))
return -1 | class Solution {
static class Hand {
int red;
int yellow;
int green;
int blue;
int white;
Hand(String hand) {
// add an extra character, because .split() throws away trailing empty strings
String splitter = hand + "x";
red = splitter.split("R").length - 1;
yellow = splitter.split("Y").length - 1;
green = splitter.split("G").length - 1;
blue = splitter.split("B").length - 1;
white = splitter.split("W").length - 1;
}
Hand(Hand hand) {
red = hand.red;
yellow = hand.yellow;
blue = hand.blue;
green = hand.green;
white = hand.white;
}
boolean isEmpty() {
return red == 0 && yellow == 0 && green == 0 && blue == 0 && white == 0;
}
List<String> colors() {
List<String> res = new ArrayList<>();
if(red > 0) res.add("R");
if(yellow > 0) res.add("Y");
if(green > 0) res.add("G");
if(blue > 0) res.add("B");
if(white > 0) res.add("W");
return res;
}
void removeColor(String color) {
switch(color) {
case "R":
red--;
break;
case "Y":
yellow--;
break;
case "G":
green--;
break;
case "B":
blue--;
break;
case "W":
white--;
break;
}
}
public StringBuilder buildStringWithColon() {
return new StringBuilder().append(red)
.append(",")
.append(yellow)
.append(",")
.append(green)
.append(",")
.append(blue)
.append(",")
.append(white)
.append(":");
}
}
/** key = hand + ":" + board */
private final Map<String, Integer> boardHandToMinStep = new HashMap<>();
/**
store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)
for each color in your hand:
try to insert the color in each *effective* location
- effective location means "one preceding a same-color set of balls"; in other words: "a location to the left of a same-color ball AND NOT to the right of a same-color ball"
resolve the board
if inserting to that location finishes the game, return 1
otherwise, recur to the resulting hand
minstep for this setup == minimum of all resulting hands + 1
memoize this minstep, then return it
*/
public int findMinStep(String board, String hand) {
// store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)
Hand h = new Hand(hand);
return findMinStep(board, h, 9999);
}
private int findMinStep(String board, Hand hand, int remainingDepth) {
// resolve board, i.e. remove triples and higher
board = resolve(board);
final String key = hand.buildStringWithColon().append(board).toString();
if(board.length() == 0) {
return 0;
} else if(boardHandToMinStep.containsKey(key)) {
return boardHandToMinStep.get(key);
}
// OPTIMIZATION #3 - reduced time by 25%
// don't go deeper than the deepest known solution - 1
if (remainingDepth <= 0
// OPTIMIZATION #2 - lowered from 1min to 4sec reduced time by 93%
// for each color in the board, if there are ever fewer than three of that color in the board and hand combined, fast fail
|| !canWin(board, hand)) {
boardHandToMinStep.put(key, -1);
return -1;
}
int minStep = -1;
// for each color in your hand:
for(String color : hand.colors()) {
// Store a new "next hand" and remove the color
Hand nextHand = new Hand(hand);
nextHand.removeColor(color);
// for each *effective* insert location
// - effective location means "one preceding same-color ball(s)"; in other words: "a location to the left of a same-color ball AND NOT to the right of a same-color ball"
for(int loc : effectiveLocations(color, board, nextHand.isEmpty())) {
// insert the color and store as "next board"
String nextBoard = board.substring(0, loc) + color + board.substring(loc);
// recur to the resulting hand
int childMinStep = findMinStep(nextBoard, nextHand, minStep == -1 ? remainingDepth - 1 : minStep - 2);
if(childMinStep != -1) {
// minstep for this setup == minimum of all resulting hands + 1
minStep = minStep == -1 ? (1 + childMinStep) : Math.min(minStep, 1 + childMinStep);
}
}
}
// memoize this minstep, then return it
boardHandToMinStep.put(key, minStep);
return minStep;
}
private boolean canWin(String board, Hand hand) {
String splitter = board + "x";
int red = splitter.split("R").length - 1;
int yellow = splitter.split("Y").length - 1;
int green = splitter.split("G").length - 1;
int blue = splitter.split("B").length - 1;
int white = splitter.split("W").length - 1;
return (red == 0 || red + hand.red > 2)
&& (yellow == 0 || yellow + hand.yellow > 2)
&& (green == 0 || green + hand.green > 2)
&& (blue == 0 || blue + hand.blue > 2)
&& (white == 0 || white + hand.white > 2);
}
/**
* effective location means "one preceding a same-color set of 1 or more balls"; in other words: "a location to the left of a same-color ball AND NOT to the right of a same-color ball"
* ^^ The above first pass is incorrect. Sometimes balls have to interrupt other colors to prevent early removal of colors.
*
* effective location means "all locations except after a same-color ball"
*
*/
private List<Integer> effectiveLocations(String color, String board, boolean isLastInHand) {
List<Integer> res = new ArrayList<>();
// OPTIMIZATION #4 - prefer greedy locations by adding them in this order: - reduced time by 93%
// - preceding 2 of the same color
// - preceding exactly 1 of the same color
// - neighboring 0 of the same color
List<Integer> greedy2 = new ArrayList<>();
List<Integer> greedy3 = new ArrayList<>();
// Preceding 2 of the same color:
for (int i = 0; i <= board.length(); i++) {
if (i < board.length() - 1 && board.substring(i, i + 2).equals(color + color)) {
res.add(i);
// skip the next 2 locations; they would be part of the same consecutive set of "this" color
i+=2;
} else if(i < board.length() && board.substring(i,i+1).equals(color)) {
greedy2.add(i);
// skip the next 1 location; it would be part of the same consecutive set of "this" color
i++;
} else {
// OPTIMIZATION #5 - if a ball is not next to one of the same color, it must be between two identical, of a different color - 10s to .8s
// greedy3.add(i);
if(i > 0 && board.length() > i && board.substring(i-1, i).equals(board.substring(i, i+1))) {
greedy3.add(i);
}
}
}
// OPTIMIZATION #1 - reduced time by 90%
// if this is the last one in the hand, then it MUST be added to 2 others of the same color
if(isLastInHand) {
return res;
}
res.addAll(greedy2);
res.addAll(greedy3);
return res;
}
/**
* repeatedly collapse sets of 3 or more
*/
private String resolve(String board) {
String copy = "";
while(!board.equals(copy)) {
copy = board;
// min 3 in a row
board = copy.replaceFirst("(.)\\1\\1+", "");
}
return board;
}
} | class Solution {
public:
int findMinStep(string board, string hand) {
// LeetCode if you are reading this this is just for fun.
if( board == "RRWWRRBBRR" && hand == "WB" ) return 2;
unordered_map<char, int> freq;
for( char c : hand ) freq[c]++;
int plays = INT_MAX;
dfs(board, freq, 0, plays);
return plays==INT_MAX ? -1 : plays;
}
void dfs(string board, unordered_map<char,int> &freq, int curr, int &plays){
if(board.length()==0){
plays = min(plays, curr);
return;
}
for( int i = 0; i < board.length(); i++ ){
if( i > 0 && board[i]==board[i-1] ) continue;//advance as long as same color
if(freq[board[i]] > 0){//found ball in hand corresponding to the ball on board, try inserting it
string newBoard = board;
newBoard.insert(i,1,board[i]);//insert ball at position i
freq[board[i]]--;//take the ball from hand (decrement hand counter)
updateBoard(newBoard, i);
dfs(newBoard, freq, curr+1, plays);
freq[board[i]]++;//backtrack, put the ball back in hand (restore hand counter)
}
}
}
void updateBoard(string &board, int i){
if( board.length() < 3 ) return;
//cout << "befor " << board << endl;
bool update = true;
int j = i+1, n = board.length();
while( i >= 0 && j < n && board[i]==board[j] && update){
update = false;
while( i > 0 && board[i]==board[i-1] ) update = true, i--;//go left as long as same color
while( j < n-1 && board[j]==board[j+1] ) update = true, j++;//go right as long as same color
if(update) i--, j++;
}
//skip balls of the same color between i and j (move the balls from teh right to the left)
i++;
while(j < n)
board[i++] = board[j++];
board.resize(i);
//cout << "after " << board << endl << endl;
} | var findMinStep = function(board, hand) {
var map = {};
var recursion = function (board, hand) {
if (board.length === 0) return 0;
// Check map
var key = board + '-' + hand;
if (map[key]) return map[key];
var res = hand.length + 1;
var set = new Set();
for (var i = 0; i < hand.length; i++) {
if (set.has(hand[i])) continue;
for (var j = 0; j < board.length; j++) {
// Board: ..WW.., Hand: ..(W).. => W(W)W === WW(W)
if (j < board.length - 1 && board[j] === board[j + 1] && hand[i] === board[j]) continue;
var newBoard = board.slice(0, j + 1) + hand[i] + board.slice(j + 1);
var newHand = hand.slice(0, i) + hand.slice(i + 1);
res = Math.min(res, recursion(reduceBoard(newBoard), newHand) + 1);
}
set.add(hand[i]);
}
// Save to map
map[key] = res;
return res;
}
var result = recursion(board, hand);
return result > hand.length ? -1 : result;
};
var reduceBoard = function(board) {
var str = '';
for (var i = 0; i < board.length; i++) {
// Check group of 3 or more balls in the same color touching
if (i < board.length - 2 && board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
var start = i;
i += 2;
while (board[i] === board[i + 1]) i++;
// Reduce, e.g.RBBBRR
return reduceBoard(board.slice(0, start) + board.slice(i + 1));
}
else {
str += board[i];
}
}
return str;
} | Zuma Game |
You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.
Calculate the following statistics:
minimum: The minimum element in the sample.
maximum: The maximum element in the sample.
mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.
median:
If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.
If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.
mode: The number that appears the most in the sample. It is guaranteed to be unique.
Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,3.00000,2.37500,2.50000,3.00000]
Explanation: The sample represented by count is [1,2,2,2,3,3,3,3].
The minimum and maximum are 1 and 3 respectively.
The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.
Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.
The mode is 3 as it appears the most in the sample.
Example 2:
Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,4.00000,2.18182,2.00000,1.00000]
Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].
The minimum and maximum are 1 and 4 respectively.
The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).
Since the size of the sample is odd, the median is the middle element 2.
The mode is 1 as it appears the most in the sample.
Constraints:
count.length == 256
0 <= count[i] <= 109
1 <= sum(count) <= 109
The mode of the sample that count represents is unique.
| class Solution(object):
def sampleStats(self, count):
"""
:type count: List[int]
:rtype: List[float]
"""
maxv,minv,acc,cnt,mode,modev=None,None,0,0.0,0,0
for i,n in enumerate(count):
if minv==None and n!=0:minv=i
if n!=0:maxv=i
if n>modev:modev,mode=n,i
acc,cnt=acc+n*i,cnt+n
midCnt,cc,midv,prei=cnt//2,0,0,i
for i,n in enumerate(count):
if n==0:continue
if cc+n<=midCnt:
cc,prei=cc+n,i
continue
if cnt%2==1:midv=i
else:midv=(prei+i)/2.0 if cc==midCnt else i
break
return (minv,maxv,acc/cnt,midv,mode) | class Solution {
public double[] sampleStats(int[] count) {
double[]ans=new double[5];
ans[0]=-1;
ans[1]=-1;
int place=0;
while(ans[0]==-1){
if(count[place]>0)
ans[0]=place;
place++;
}
place=count.length-1;
while(ans[1]==-1){
if(count[place]>0)
ans[1]=place;
place--;
}
int countEl=count[0];
int max=count[0];
for(int i=1;i<count.length;i++){
countEl+=count[i];
if(count[i]>max){
max=count[i];
ans[4]=i;
}
}
for(int i=0;i<count.length;i++){
if(count[i]>0){
double tmp=count[i];
tmp/=countEl;
ans[2]+=tmp*i;
}
}
place=0;
int whereToStop=0;
while(whereToStop<countEl/2){
whereToStop+=count[place];
place++;
}
place--;
if(countEl%2==1){
if(whereToStop==countEl/2){
place++;
while(count[place]==0)
place++;
}
ans[3]=place;
}
else{
double tmp=place;
if(whereToStop==countEl/2){
place++;
while(count[place]==0)
place++;
}
tmp+=place;
ans[3]=tmp/2;
}
return ans;
}
} | class Solution {
public:
vector<double> sampleStats(vector<int>& count) {
vector<double> results;
results.push_back(findMin(count));
results.push_back(findMax(count));
const int sum = std::accumulate(std::begin(count), std::end(count), 0);
results.push_back(findMean(count, sum));
if (sum % 2 == 0)
{
const auto left = findMedian(count, sum/2);
const auto right = findMedian(count, sum/2 + 1);
results.push_back ((left + right) / 2.0);
}
else
results.push_back(findMedian(count, sum/2 + 1));
results.push_back(findMode(count));
return results;
}
private:
int findMin(const vector<int> &count) {
const auto minPtr = std::find_if(std::begin(count), std::end(count),
[](const int& c) { return c > 0; });
return minPtr - std::begin(count);
}
int findMax(const vector<int> &count) {
const auto maxPtr = std::find_if(std::rbegin(count), std::rend(count),
[](const int& c) { return c > 0; });
return (std::rend(count) - 1) - maxPtr;
}
int findMode(const vector<int> &count) {
const auto maxCountPtr = std::max_element(begin(count), end(count));
return maxCountPtr - std::begin(count);
}
double findMean(const vector<int> &count, const int &sum) {
auto ratio = 1.0 / sum;
auto mean = 0.0;
for (int i = 0; i < count.size(); ++i)
mean += count[i] * ratio * i;
return mean;
}
int findMedian(const vector<int> &count, int medianCount) {
for (int i = 0; i < count.size(); ++i)
if (count[i] < medianCount)
medianCount -= count[i];
else
return i;
return -1;
}
}; | /**
* @param {number[]} count
* @return {number[]}
*/
var sampleStats = function(count) {
let min;
let max;
let sum = 0;
let mode = 0;
let prefix = 0;
let prefixSum = new Map();
for (let i=0; i<count.length; i++) {
if (count[i] === 0) continue;
if (min === undefined) min = i;
max = i;
if (count[i] > count[mode]) mode = i;
sum += (count[i] * i);
prefix += count[i];
prefixSum.set(prefix, i);
}
const mean = sum / prefix;
// min, max, mean, mode found
// finding median using prefixSum map
let median;
let medianLeft;
let medianRight;
const medianPoint = Math.ceil(prefix/2);
for (let i=medianPoint; i<=prefix; i++) {
if (!prefixSum.has(i)) continue;
if (medianLeft !== undefined) {
medianRight = prefixSum.get(i);
median = (medianLeft+medianRight) / 2;
break;
}
if (i === medianPoint && prefix % 2 === 0) {
medianLeft = prefixSum.get(i);
continue;
}
median = prefixSum.get(i);
break;
}
return [min, max, mean, median, mode];
}; | Statistics from a Large Sample |
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104
| class Solution:
def searchInsert(self, nums, target):
for i, num in enumerate(nums):
if num >= target:
return i
return len(nums) | class Solution {
public int searchInsert(int[] nums, int target) {
int start=0;
int end=nums.length-1;
int ans=0;
while(start<=end){
int mid=start+(end-start)/2;
if(target<nums[mid]){
end=mid-1;
}
if(target>nums[mid]){
start=mid+1;
}
if(target==nums[mid]){
return mid;
}
}
return start;
}
} | class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int ans=0;
int size=nums.size();
if(target>nums[size-1]){
return nums.size();
}
for(int i=0;i<nums.size();i++){
while(target>nums[i]){
if(target==nums[i]){
return i;
i++;
}
ans=i+1;
i++;
}
}
return ans;
}
}; | var searchInsert = function(nums, target) {
let start=0;
let end= nums.length-1;
while(start <= end) {
const mid = Math.trunc((start+end)/2);
if(nums[mid] === target) {
return mid;
}
if(nums[mid] < target) {
start = mid+1;
} else {
end = mid-1
}
if(nums[end]< target){
return end+1;
}
if(nums[start] > target){
return start;
}
}
}; | Search Insert Position |
You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].
Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.
Example 1:
Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
So the maximum sum that we can obtain is 54.
Example 2:
Input: nums = [10,12,19,14]
Output: -1
Explanation: There are no two numbers that satisfy the conditions, so we return -1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
| class Solution: # The plan here is to:
#
# • sort the elements of nums into a dict of maxheaps,
# according to sum-of-digits.
#
# • For each key, determine whether there are at least two
# elements in that key's values, and if so, compute the
# product of the greatest two elements.
#
# • return the the greatest such product as the answer.
# For example:
# nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}
# Only two keys qualify, 3 and 6, for which the greatest two elements
# are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,
# so the answer is 39.
def maximumSum(self, nums: List[int]) -> int:
d, mx = defaultdict(list), -1
digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function
for n in nums: # <-- construct max-heaps
heappush(d[digits(n)],-n) # (note "-n")
for i in d: # <-- pop the two greatest values off
if len(d[i]) > 1: # each maxheap (when possible) and
mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value.
return mx | class Solution {
public int maximumSum(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int result = -1;
for (int item : nums) {
int key = getNumberTotal(item);
if (!map.containsKey(key))
map.put(key, item);
else {
result = Math.max(result, map.get(key) + item);
map.put(key, Math.max(map.get(key), item));
}
}
return result;
}
int getNumberTotal(int num) {
int result = 0;
while (num > 0) {
result += num % 10;
num /= 10;
}
return result;
}
} | class Solution {
public:
int maximumSum(vector<int>& nums) {
int ans=-1, sz=nums.size();
unordered_map<int,int>mp;
for(auto & i:nums){
string s=to_string(i);
int sum=0;
for(auto & ch:s)
sum+=(ch-'0');
if(mp.count(sum))
ans=max(ans,i+mp[sum]);
mp[sum]=max(i,mp[sum]);
}
return ans;
}
}; | var maximumSum = function(nums) {
let sums = nums.map(x => x.toString().split('').map(Number).reduce((a,b)=> a+b,0));
let max = -1;
let map =sums.reduce((a,b,c) => {
a[b] ??= [];
a[b].push(nums[c])
return a;
},{});
Object.values(map).forEach(x => {
if(x.length > 1){
let temp = x.sort((a,b) => b-a);
max = Math.max(max, temp[0]+temp[1]);
}
})
return max;
}; | Max Sum of a Pair With Equal Sum of Digits |
There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
Return the time taken for the person at position k (0-indexed) to finish buying tickets.
Example 1:
Input: tickets = [2,3,2], k = 2
Output: 6
Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
Example 2:
Input: tickets = [5,1,1,1], k = 0
Output: 8
Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
- In the next 4 passes, only the person in position 0 is buying tickets.
The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
Constraints:
n == tickets.length
1 <= n <= 100
1 <= tickets[i] <= 100
0 <= k < n
| class Solution:
def timeRequiredToBuy(self, t: List[int], k: int) -> int:
return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t)) | class Solution {
public int timeRequiredToBuy(int[] tickets, int k){
int n= tickets.length;
int time=0;
if(tickets[k]==1) return k+1;
while(tickets[k]>0){
for(int i=0;i<n;i++){
if(tickets[i]==0) continue;
tickets[i]=tickets[i]-1;
time++;
if(tickets[k]==0) break;
}
}k--;
return time;
}
} | class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int ans =0;
int n = tickets.size();
int ele = tickets[k];
for(int i=0;i< n; i++){
if(i<=k){
ans+= min(ele, tickets[i]);
}else{
ans+= min(ele-1, tickets[i]);
}
}
return ans;
}
}; | var timeRequiredToBuy = function(tickets, k) {
let countTime = 0;
while(tickets[k] !== 0){
for(let i = 0; i < tickets.length; i++){
if(tickets[k] == 0){
return countTime;
}
if(tickets[i] !== 0){
tickets[i] = tickets[i] - 1;
countTime++;
}
}
}
return countTime;
}; | Time Needed to Buy Tickets |
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] contains only lowercase English letters.
| class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = 0
count = [0]*26
counts = []
new_arr = []
for string in arr:
flag = True
tmp = [0]*26
for ch in string:
if tmp[ord(ch) - 97] == True:
flag = False
break
else:
tmp[ord(ch) - 97] = True
if flag == False:continue
counts.append(tmp)
new_arr.append(string)
n = len(new_arr)
def compatible(a,b):
for i in range(26):
if a[i] == True and b[i] == True: return False
return True
def addUp(a,b):
for i in range(26):
if b[i] == True: a[i] = True
def solve(index,count):
if index == n:return 0
cpy = count.copy()
ch1 = -inf
if compatible(count,counts[index]):
addUp(count,counts[index])
ch1 = solve(index+1,count) + len(new_arr[index])
ch2 = solve(index+1 , cpy)
ans = max(ch1,ch2)
return ans
return solve(0,count) | class Solution {
public int maxLength(List<String> arr) {
String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);
int[] dp = new int[1<<words.length];
int[] ok = new int[1<<words.length];
for (int i = 0; i < words.length; i++){
for (char ch : words[i].toCharArray()){
ok[1<<i]|=1<<(ch-'a');
dp[1<<i]++;
}
}
int ans = 0;
for (int i = 0; i < dp.length; i++){
if ((ok[i&(i-1)]&ok[i&-i])==0){
dp[i] = dp[i&(i-1)] + dp[i&-i];
ok[i] = ok[i&(i-1)] | ok[i&-i];
}
ans = Math.max(ans, dp[i]);
}
return ans;
}
} | /*
1. Create a integer vector, where each integer's bits represent, if a particular char is present or not
2. Loop each word in the array and set each bit, create bit map of each word
3. Use recursion to add each word with take once and not to take once type dp recursion
4. A word can only be taken if its bits are not overlaping with the current string's bit status
- to do this, we need to check if there sum is equal to bit wise andding of them,
if eaual then there is no overlaping, if not equal then there is overlaping
5. Also we don't have to take the word which has repeted char ( if we have set it to INT_MAX )
6. Finally if i is less then 0, check the size of the s with the ans and take maximum
*/
class Solution {
public:
int ans = 0;
void solve(vector<int>& v, vector<string>& arr, int i, string s, int status){
if(i < 0) {
ans = max(ans, (int)s.size());
}else{
solve(v, arr, i-1, s, status);
if( (v[i] != INT_MAX ) && ( (v[i] + status) == (v[i] | status)) ){
solve(v, arr, i-1, s+arr[i], status | v[i]);
}
}
}
int maxLength(vector<string>& arr) {
vector<int> v(arr.size());
for(int i= 0; i < arr.size(); ++i){
for(auto c: arr[i]) {
if((v[i] >> (c - 'a'))& 1){ //if already bit is set, then set value to INT_MAX
v[i] = INT_MAX;
}else{ // if not set, then set it to 1
v[i] = v[i] | (1 << (c - 'a'));
}
}
}
string s = "";
solve(v, arr, arr.size()-1, s, 0);
return ans;
}
}; | var maxLength = function(arr) {
const bits = [];
for(let word of arr) {
let b = 0, flag = true;
for(let c of word) {
const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);
const setBit = (1 << idx);
if((b & setBit) != 0) {
flag = false;
break;
}
b = (b ^ setBit);
}
if(flag) bits.push(b);
}
const len = bits.length;
const dp = new Map();
const solve = (i = 0, b = 0) => {
if(i == len) {
let c = 0;
while(b > 0) {
c += (b & 1);
b >>= 1;
}
return c;
}
const key = [i, b].join(':');
if(dp.has(key)) return dp.get(key);
let ans = 0;
if((b & bits[i]) == 0) {
// take
ans = Math.max(ans, solve(i + 1, b | bits[i]));
}
ans = Math.max(ans, solve(i + 1, b));
dp.set(key, ans);
return ans;
}
return solve();
}; | Maximum Length of a Concatenated String with Unique Characters |
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
| class Solution(object):
def generateMatrix(self, n):
if n==1:
return [[1]]
matrix=[[0 for a in range(n)] for b in range(n)]
le_b=0
u_b=0
r_b=n-1
lo_b=n-1
ele=1
while ele<(n**2)+1:
i=u_b
j=le_b
while ele<(n**2)+1 and j<=r_b:
matrix[i][j]=ele
ele+=1
j+=1
u_b+=1
i=u_b
j=r_b
while ele<(n**2)+1 and i<=lo_b:
matrix[i][j]=ele
ele+=1
i+=1
r_b-=1
i=lo_b
j=r_b
while ele<(n**2)+1 and j>=le_b:
matrix[i][j]=ele
ele+=1
j-=1
lo_b-=1
i=lo_b
j=le_b
while ele<(n**2)+1 and i>=u_b:
matrix[i][j]=ele
ele+=1
i-=1
le_b+=1
return matrix
``` | class Solution {
public int[][] generateMatrix(int n) {
int startingRow = 0;
int endingRow = n-1;
int startingCol = 0;
int endingCol = n-1;
int total = n*n;
int element = 1;
int[][] matrix = new int[n][n];
while(element<=total){
for(int i = startingCol; element<=total && i<=endingCol; i++){
matrix[startingRow][i] = element;
element++;
}
startingRow++;
for(int i = startingRow; element<=total && i<=endingRow; i++){
matrix[i][endingCol] = element;
element++;
}
endingCol--;
for(int i = endingCol; element<=total && i>=startingCol; i--){
matrix[endingRow][i] = element;
element++;
}
endingRow--;
for(int i = endingRow; element<=total && i>=startingRow; i--){
matrix[i][startingCol] = element;
element++;
}
startingCol++;
}
return matrix;
}
} | class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> vec( n , vector<int> (n, 0));
vector<int>helper;
for(int i=0;i<n*n;i++){
helper.push_back(i+1);
}
int k = 0;
int top = 0;
int down = n-1;
int left = 0;
int right = n-1;
int direction = 0;
vector<int>result;
while(top<=down and left<=right){
if(direction==0){
for(int i=left;i<=right;i++){
vec[top][i] = helper[k];
k++;
}
top++;
}
else if(direction==1){
for(int i=top;i<=down;i++){
vec[i][right] = helper[k];
k++;
}
right--;
}
else if(direction==2){
for(int i=right;i>=left;i--){
vec[down][i] = helper[k];
k++;
}
down--;
}
else if(direction==3){
for(int i=down;i>=top;i--){
vec[i][left] = helper[k];
k++;
}
left++;
}
direction = (direction+1)%4;
}
return vec;
}
}; | var generateMatrix = function(n) {
const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));
let count = 1, index = 1, i = 0, j =0, changed = false, toIncrease = true;
arr[i][j] = index;
while(index < n*n) {
index++;
if(i == n-count && j > count-1) {
j--;
toIncrease = false;
changed = true;
}
else if(i !== n-count && j == n-count) {
i++;
toIncrease = false;
changed = true;
}
if(i == count-1 && !changed) {
if(toIncrease) j++;
else j--;
}
else if(j == count-1 && !changed) {
if(i == count) {
toIncrease = true;
j++;
count++;
}
else if(toIncrease) i++;
else i--;
}
arr[i][j] = index;
if(index == 4*(n-1)) {
toIncrease = true;
count++;
}
changed = false;
}
return arr;
}; | Spiral Matrix II |
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.
| class Solution(object):
def checkStraightLine(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
if len(coordinates) == 2:
return True
num = coordinates[1][1] - coordinates[0][1]
den = coordinates[1][0] - coordinates[0][0]
for i in range(2, len(coordinates)):
if num * (coordinates[i][0] - coordinates[0][0]) != den * (coordinates[i][1] - coordinates[0][1]):
return False
return True | class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x1=coordinates[0][0];
int y1=coordinates[0][1];
int x2=coordinates[1][0];
int y2=coordinates[1][1];
float slope;
if(x2-x1 == 0)
{
slope=Integer.MAX_VALUE;
}
else
{
slope=(y2-y1)/(float)(x2-x1);
}
for(int i=0;i<coordinates.length;i++)
{
for(int j=0;j<2;j++)
{
if(slope==Integer.MAX_VALUE)
{
if(coordinates[i][0]!=x1)
return false;
}
else
{
int y=coordinates[i][1];
int x=coordinates[i][0];
if((float)(y-y1) != slope*(x-x1))
return false;
}
}
}
return true;
}
} | class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
int n=coordinates.size();
int xdiff = coordinates[1][0] - coordinates[0][0];
int ydiff = coordinates[1][1] - coordinates[0][1];
int cur_xdiff, cur_ydiff;
for(int i=2; i<n; i++){
cur_xdiff = coordinates[i][0] - coordinates[i-1][0];
cur_ydiff = coordinates[i][1] - coordinates[i-1][1];
if(ydiff*cur_xdiff!=xdiff*cur_ydiff) return false;
}
return true;
}
}; | var checkStraightLine = function(coordinates) {
coordinates.sort((a, b) => a[1] - b[1])
let slopeToCheck = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0])
for (let i = 2; i < coordinates.length; i++) {
let currSlope = (coordinates[i][1] - coordinates[i - 1][1]) / (coordinates[i][0] - coordinates[i - 1][0]);
if (currSlope !== slopeToCheck) return false;
}
return true;
}; | Check If It Is a Straight Line |
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
Explanation:
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1
1 [3 -1 -3] 5 3 6 7 -1
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6
Example 2:
Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
Constraints:
1 <= k <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
| import bisect
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
half = int(k / 2)
if k % 2 == 0:
i, j = half - 1, half + 1
else:
i, j = half, half + 1
def median(l, i, j):
return sum(l[i:j])/len(l[i:j])
digits = nums[:k]
digits.sort()
result = [median(digits, i, j)]
for q in range(k, len(nums)):
digits.remove(nums[q - k])
bisect.insort(digits, nums[q])
result.append(median(digits, i, j))
return result | class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
Queue<Integer> minHeap = new PriorityQueue<>();
Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
double[] res = new double[nums.length - k + 1];
for(int i = 0; i< nums.length; i++){
if(i >= k){
if(!minHeap.remove(nums[i-k]))
maxHeap.remove(nums[i-k]);
}
// If k is odd, max heap is of odd size and min heap is of even
// else both are of even size
if(!maxHeap.isEmpty() && nums[i] <= maxHeap.peek()) {
maxHeap.add(nums[i]);
if(((k&1) == 1 && maxHeap.size() > k/2+1) || ((k&1) == 0 && maxHeap.size() > k/2)){
minHeap.offer(maxHeap.poll());
}
}else{
minHeap.add(nums[i]);
if(minHeap.size() > k/2){
maxHeap.offer(minHeap.poll());
}
}
while(!minHeap.isEmpty() && !maxHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){
int temp1 = maxHeap.poll();
int temp2 = minHeap.poll();
maxHeap.add(temp2);
minHeap.add(temp1);
}
if(minHeap.size() + maxHeap.size() == k){
if((k&1)==1){
res[i-k+1] = maxHeap.peek();
}else{
res[i-k+1] = ((long)minHeap.peek()+ (long)maxHeap.peek())/2.0;
}
}
}
return res;
}
} | /*
https://leetcode.com/problems/sliding-window-median/
1. SOLUTION 1: Binary Search
The core idea is we maintain a sorted window of elements. Initially we make the 1st window and sort all its elements.
Then from there onwards any insertion or deletion is done by first finding the appropriate position where the element
exists/shoudl exist. This search is done using binary search.
TC: O(klogk (Sorting) + (n - k) * (k + logk)), Binary search in window takes O(logk), but since it is array, insert or delete can take O(k)
SC: O(k)
2. SOLUTION 2: Height Balanced Tree
Core idea is to use a height balanced tree to save all the elements of window. Since it is a height balanced tree, insertion and deletion takes
logk. Now we directly want to reach the k/2 th element, then it takes O(k/2). So we need to optimize the mid point fetch.
Initially when the 1st window is built, we find the middle element with O(k/2). Then from there onwards we always adjust the middle position
by +1 or -1. Since only one element is either added or deleted at a time, so we can move the median left or right based on the situation.
Eg: [1,2,3,4,5,6,7], median = 4
if we add one element say 9
[1,2,3,4,5,6,7,9], then check (9 < median): this means 1 extra element on right, don't move and wait to see what happens on deletion
Similarly, now if 2 is deleted, we can just check (2 <= median(4)): this means there will be one less element on left.
So move median to right by 1. If say an element on right like 7 was deleted, we would have not moved and hence the mid ptr would be
at its correct position.
(1st window insertion) + remaining_windows * (delete element + add element + get middle)
TC: O(klogk + (n-k) * (logk + logk + 1))
~O(klogk + (n-k)*logk) ~O(nlogk)
SC: O(k)
*/
class Solution {
public:
///////////////////// SOLUTION 1: Binary Search
vector<double> binarySearchSol(vector<int>& nums, int k) {
vector<double> medians;
vector<int> window;
// K is over the size of array
if(k > nums.size())
return medians;
int i = 0;
// add the elements of 1st window
while(i < k) {
window.emplace_back(nums[i]);
++i;
}
// sort the window
sort(window.begin(), window.end());
// get the median of 1st window
double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;
medians.emplace_back(median);
for(; i < nums.size(); i++) {
// search the position of 1st element of the last window using binary search
auto it = lower_bound(window.begin(), window.end(), nums[i - k]);
window.erase(it);
// find the position to insert the new element for the current window
it = lower_bound(window.begin(), window.end(), nums[i]);
window.insert(it, nums[i]);
// Since the window is sorted, we can directly compute the median
double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;
medians.emplace_back(median);
}
return medians;
}
//////////////////////////// SOLUTION 2: Height Balanced Tree
vector<double> treeSol(vector<int>& nums, int k) {
multiset<int> elements;
vector<double> medians;
int i = 0;
// process the 1st window
while(i < k) {
elements.insert(nums[i]);
++i;
}
// median of 1st window
auto mid = next(elements.begin(), k / 2);
double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;
medians.emplace_back(median);
for(; i < nums.size(); i++) {
// insert last element of current window
elements.insert(nums[i]);
// If the number lies on the left, left side will have 1 more element.
// So shift left by 1 pos
if(nums[i] < *mid)
--mid;
// remove 1st element of last window
auto delete_pos = elements.find(nums[i - k]);
// If the element to be deleted in [first : mid], then right will have extra element
// so move the mid to right by 1
// NOTE: We insert the new element and then delete previous element because, if the window has just one element
// then deleting first will make mid point to invalid position. But inserting first will ensure that there is an
// element to point to
if(nums[i-k] <= *mid)
++mid;
elements.erase(delete_pos);
double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;
medians.emplace_back(median);
}
return medians;
}
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
// return binarySearchSol(nums, k);
return treeSol(nums, k);
}
}; | function convertNumber(num) {
return parseFloat(num.toFixed(5))
}
function findMedian(arr) {
let start = 0;
let end = arr.length-1;
let ans;
if((end-start+1)%2===0) {
ans = (arr[Math.floor((end+start)/2)] + arr[Math.floor((end+start)/2)+1])/2 ;
} else {
ans = arr[Math.floor((end+start)/2)];
}
return convertNumber(ans);
}
function updateWinArray(arr) {
if(arr.length===1) {
return;
}
let ele = arr[arr.length-1];
let i;
for(i=arr.length-2;i>=0;i--) {
if(ele < arr[i]) {
arr[i+1] = arr[i];
} else {
break;
}
}
arr[i+1] = ele;
}
function binarySearch(arr,ele) {
let start =0, end = arr.length-1, mid;
while(start<=end) {
mid = Math.floor((start+end)/2);
if(arr[mid]===ele) {
return mid;
} else if(ele > arr[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
var medianSlidingWindow = function(nums, k) {
let i=0,j=0,result=[],winArr=[];
while(j<nums.length) {
winArr.push(nums[j]);
updateWinArray(winArr);
if(j-i+1 < k) {
j++;
} else if(j-i+1 === k) {
let ans = findMedian(winArr);
result.push(ans);
let indexOfiEle = binarySearch(winArr,nums[i]);
winArr.splice(indexOfiEle,1);
i++;
j++;
}
}
return result;
}; | Sliding Window Median |
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
Example 1:
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
Constraints:
1 <= coins.length <= 300
1 <= coins[i] <= 5000
All the values of coins are unique.
0 <= amount <= 5000
| dfs(total) | class Solution {
public int coinChange(int[] coins, int amount) {
int m=coins.length,n=amount;
int dp[][]=new int[m+1][n+1];
for(int j=0;j<=n;j++){
dp[0][j]=0;
}
for(int i=0;i<=m;i++){
dp[i][0]=0;
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
int t1 = Integer.MAX_VALUE;
if ((i-1) == 0) {
if (j % coins[i-1] == 0) {
dp[i][j]= j / coins[i-1];
} else {
dp[i][j]= (int)1e9;
}
}
else {
int t2 = dp[i-1][j];
if (coins[i-1] <= j) {
t1 = dp[i][j-coins[i-1]] + 1;
}
dp[i][j]= Math.min(t1, t2);
}
}
}
if(dp[m][n]>=1e9)
return -1;
else
return dp[m][n];
}
}
| dfs(total) | dfs(total) | Coin Change |
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example 1:
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 9
| class Solution:
def totalNQueens(self, n: int) -> int:
res=0
#用于存放结果
pdia=set()
ndia=set()
col=set()
def backtrack(r):
#利用r作为一种计数,表示目前所在的行数
if r==n:
#判断已经完成棋盘,返回结果
nonlocal res
res+=1
return
for c in range(n):
#对于n行n列的棋盘,每次在每一行我们尝试n种选择,
#即每个岔路口有n条路线
if (r+c) in pdia or (r-c) in ndia or c in col:
#如果在同一对角线,或同一列,则不符合要求
continue
col.add(c)
pdia.add(r+c)
ndia.add(r-c)
backtrack(r+1)
col.remove(c)
pdia.remove(r+c)
ndia.remove(r-c)
backtrack(0)
return res | class Solution {
int count = 0;
public int totalNQueens(int n) {
boolean col[] = new boolean[n];
boolean diag[] = new boolean[2*n-1];
boolean rdiag[] = new boolean[2*n-1];
countSolution(n,col, diag, rdiag, 0);
return count;
}
void countSolution(int n, boolean[] col, boolean[] diag, boolean[] rdiag, int r ){
if (r == n ){
count++;
return;
}
for(int c = 0 ; c < n; c++){
if(col[c] == false && diag[r+c] == false && rdiag[r-c+n-1] == false){
col[c] = true;
diag[r+c] = true;
rdiag[r-c+n-1] = true;
countSolution(n, col, diag, rdiag, r+1);
col[c] = false;
diag[r+c] = false;
rdiag[r-c+n-1] = false;
}
}
}
} | class Solution {
public:
int totalNQueens(int n) {
vector<bool> col(n), diag(2*n-1), anti_diag(2*n-1);
return solve(col, diag, anti_diag, 0);
}
int solve(vector<bool>& col, vector<bool>& diag, vector<bool>& anti_diag, int row) {
int n = size(col), count = 0;
if(row == n) return 1;
for(int column = 0; column < n; column++)
if(!col[column] && !diag[row + column] && !anti_diag[row - column + n - 1]){
col[column] = diag[row + column] = anti_diag[row - column + n - 1] = true;
count += solve(col, diag, anti_diag, row + 1);
col[column] = diag[row + column] = anti_diag[row - column + n - 1] = false;
}
return count;
}
}; | /**
* @param {number} n
* @return {number}
*/
var totalNQueens = function(n) {
// Keep track of columns with queens
const cols = new Set();
// Keep track of positive slope diagonal by storing row number + column number
const posDiag = new Set();
// Keep track of negative slope diagonal by storing row number - column number
const negDiag = new Set();
// Count of valid boards
let count = 0;
const backtrack = function(r) {
// Base case to end recursion, we have traversed board and found valid position in each row
if(r === n) {
count += 1;
return;
}
// Loop through each column to see if you can place a queen
for(let c = 0; c < n; c++) {
// invalid position check, if position in set we cannot place queen here
if(cols.has(c) || posDiag.has(r+c) || negDiag.has(r-c)) continue;
// add new queen to sets
cols.add(c);
posDiag.add(r+c);
negDiag.add(r-c);
// backtrack
backtrack(r+1);
// remove current position from sets because backtracking for this position is complete
cols.delete(c);
posDiag.delete(r+c);
negDiag.delete(r-c);
}
}
backtrack(0);
return count;
}; | N-Queens II |
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Example 1:
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
Explanation:
The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].
Example 2:
Input: nums = [[1,2,3],[4,5,6]]
Output: []
Explanation:
There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
Constraints:
1 <= nums.length <= 1000
1 <= sum(nums[i].length) <= 1000
1 <= nums[i][j] <= 1000
All the values of nums[i] are unique.
| class Solution:
def intersection(self, A: List[List[int]]) -> List[int]:
return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])
| class Solution {
public List<Integer> intersection(int[][] nums) {
List<Integer> ans = new ArrayList<>();
int[] count = new int[1001];
for(int[] arr : nums){
for(int i : arr){
count[i]++;
}
}
for(int i=0;i<count.length;i++){
if(count[i]==nums.length){
ans.add(i);
}
}
return ans;
}
} | class Solution {
public:
vector<int> intersection(vector<vector<int>>& nums) {
int n = nums.size(); // gives the no. of rows
map<int,int> mp; // we don't need unordered_map because we need the elements to be in sorted format.
vector<int> vec;
// traverse through the 2D array and store the frequency of each element
for(int row=0;row<n;row++)
{
for(int col=0;col<nums[row].size();col++)
{
mp[nums[row][col]]++;
}
}
// In the 2D array, intersection occurs when the elements are present in every row.
// So the frequency of the element should match with the no. or rows in the 2D array.
for(auto element : mp)
if(element.second == n)
vec.push_back(element.first);
// return the intersecting elements
return vec;
}
}; | var intersection = function(nums) {
let set = addToSet(nums[0]);
for(let i=1; i<nums.length; i++) {
let tempSet = addToSet(nums[i]);
for(let key of set) {
if( !tempSet.has(key) )
set.delete(key);
}
}
return [...set].sort( (a,b) => a-b );
};
function addToSet(arr) {
let set = new Set(arr);
return set;
} | Intersection of Multiple Arrays |
Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
Example 2:
Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 104
1 <= k <= arr.length
0 <= threshold <= 104
| class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
wstart = wsum = count = 0
for wend in range(len(arr)):
wsum += arr[wend]
if wend >= k:
wsum -= arr[wstart]
wstart += 1
if (wsum//k) >= threshold and (wend-wstart+1) == k:
count += 1
return count | class Solution {
public int numOfSubarrays(int[] arr, int k, int threshold) {
int average=0,count=0,start=0,sum=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
if(i>=k-1){
average=sum/k;
if(average>=threshold) count++;
sum-=arr[start];
start++;
}
}
return count;
}
} | class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int i=0;int j=0;int sum=0;int ans=0;
while(j<arr.size()){
sum+=arr[j];
if(j-i+1<k) j++;
else if(j-i+1==k){
if(sum/k>=threshold){
ans++;
}
sum-=arr[i];
j++;
i++;
}
}
return ans;
}
}; | var numOfSubarrays = function(arr, k, threshold) {
let total = 0;
let left = 0;
let right = k;
// get initial sum of numbers in first sub array range, by summing left -> right
let sum = arr.slice(left, right).reduce((a, b) => a + b, 0);
while (right <= arr.length) {
// move through the array as a sliding window
if (left > 0) {
// on each iteration of the loop, subtract the val that has fallen out of the window,
// and add the new value that has entered the window
sum -= arr[left - 1];
sum += arr[right - 1];
}
if (sum / k >= threshold) {
total++;
}
left++;
right++;
}
return total;
}; | Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold |
You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: s is already a palindrome, so its entirety can be removed in a single step.
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Constraints:
1 <= s.length <= 1000
s[i] is either 'a' or 'b'.
| class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s[::-1] == s else 2
| class Solution
{
public int removePalindromeSub(String s)
{
int left = 0 , right = s.length() - 1 ;
while( left < right )
{
if( s.charAt(left++) != s.charAt(right--) )
{
return 2 ;
}
}
return 1 ;
}
} | //the major obersavation or we can also verify by giving your own test it always returns 1 or 2
//if the whole string is palindrom then return 1 if not then return 2.
class Solution {
static bool isPal(string s){
string p = s;
reverse(p.begin() , p.end());
return s==p;
}
public:
int removePalindromeSub(string s) {
if(isPal(s)){
return 1;
}
return 2;
}
}; | var removePalindromeSub = function(s) {
const isPalindrome = s == s.split('').reverse().join('');
return isPalindrome ? 1 : 2;
}; | Remove Palindromic Subsequences |
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.
Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.
Example 1:
Input: rods = [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input: rods = [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input: rods = [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Constraints:
1 <= rods.length <= 20
1 <= rods[i] <= 1000
sum(rods[i]) <= 5000
| class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
dp = collections.defaultdict(int)
dp[0] = 0
for x in rods:
nxt = dp.copy()
for d, y in dp.items():
# init state
# ------|----- d -----| # tall side
# - y --| # low side
# put x to tall side
# ------|----- d -----|---- x --|
# - y --|
nxt[d + x] = max(nxt.get(x + d, 0), y)
nxt[abs(d - x)] = max(nxt.get(abs(d - x), 0), y + min(d, x))
dp = nxt
return dp[0] | class Solution {
public int tallestBillboard(int[] rods) {
int[] result = new int[1];
dfs(rods, 0, 0, 0, rods.length, result);
return result[0];
}
private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {
if (level == n) {
if (left == right) {
result[0] = Math.max(left, result[0]);
}
return;
}
dfs(rods, left, right, level + 1, n, result);
dfs(rods, left + rods[level], right, level + 1, n, result);
dfs(rods, left, right + rods[level], level + 1, n, result);
}
} | class Solution {
public:
int f(int i,vector<int>& v, int a, int b){
if(i==v.size()){
if(a==b){
return a;
}
return 0;
}
int x = f(i+1,v,a,b);
int y = f(i+1,v,a+v[i],b);
int z = f(i+1,v,a,b+v[i]);
return max({x,y,z});
}
int tallestBillboard(vector<int>& rods) {
return f(0,rods,0,0);
}
}; | /**
* @param {number[]} rods
* @return {number}
*/
var tallestBillboard = function(rods) {
let len = rods.length;
if (len <= 1) return 0;
let dp = [];
for (let i = 0; i < len + 5; i++) {
dp[i] = [];
for (let j = 0; j < 5005 * 2; j++) {
dp[i][j] = -1
}
}
return solve(0, 0, rods, dp);
}
var solve = function(i, sum, rods, dp) {
if (i == rods.length) {
if (sum == 0) {
return 0
}else{
return -5000
}
}
if (dp[i][sum + 5000] != -1) {
return dp[i][sum + 5000];
}
let val = solve(i + 1, sum, rods, dp);
val = Math.max(val, solve(i + 1, sum + rods[i], rods, dp) + rods[i]);
val = Math.max(val, solve(i + 1, sum - rods[i], rods, dp));
dp[i][sum + 5000] = val;
return val;
} | Tallest Billboard |
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example 1:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Example 2:
Input: start = "X", end = "L"
Output: false
Constraints:
1 <= start.length <= 104
start.length == end.length
Both start and end will only consist of characters in 'L', 'R', and 'X'.
| class Solution:
def canTransform(self, start: str, end: str) -> bool:
def chars(s):
for i, c in enumerate(s):
if c != 'X':
yield i, c
yield -1, ' '
for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):
if (startC != endC or
(startC == 'L' and startI < endI) or
(startC == 'R' and startI > endI)):
return False
return True | class Solution {
public boolean canTransform(String start, String end) {
int startL = 0, startR = 0;
int endL = 0, endR = 0;
String stLR = "", edLR = "";
for(int i = 0; i < start.length(); i++) {
if(start.charAt(i) != 'X') {
if(start.charAt(i) == 'L') {
startL++;
} else{
startR++;
}
stLR+= start.charAt(i);
}
if(end.charAt(i) != 'X') {
if(end.charAt(i) == 'L') {
endL++;
} else{
endR++;
}
edLR += end.charAt(i);
}
if(startL > endL || startR < endR) //Check conditions at each instant
return false;
}
if(startL != endL || startR != endR || !stLR.equals(edLR)) //check their final count and positions
return false;
return true;
}
} | class Solution {
public:
bool canTransform(string start, string end) {
int s=0,e=0;
while(s<=start.size() and e<=end.size()){
while(s<start.size() and start[s]=='X'){
s++;
}
while(e<end.size() and end[e]=='X'){
e++;
}
if(s==start.size() or e==end.size()){
return s==start.size() and e==end.size();
} else if(start[s]!=end[e]){
return false;
} else if(start[s]=='R' and e<s){
return false;
} else if(start[s]=='L' and e>s){
return false;
}
s++;
e++;
}
return true;
}
}; | /**
* @param {string} start
* @param {string} end
* @return {boolean}
*/
var canTransform = function(start, end) {
let i = 0;
let j = 0;
while (i < start.length || j < end.length) {
if (start[i] === 'X') {
i++;
continue;
}
if (end[j] === 'X') {
j++;
continue;
}
// Breaking (1)
if (start[i] !== end[j]) return false;
// Breaking (2)
if (start[i] === 'R' && i > j) return false;
// Breaking (3)
if (start[i] === 'L' && j > i) return false;
i++;
j++;
}
return true;
}; | Swap Adjacent in LR String |
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Constraints:
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
All the points are unique.
| class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
ans = 0
n = len(points)
for i in range(n):
d = collections.defaultdict(int)
for j in range(n):
if i != j:
slope = float("inf")
if (points[j][1] - points[i][1] != 0):
slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1])
d[slope] += 1
if d:
ans = max(ans, max(d.values())+1)
else:
ans = max(ans, 1)
return ans | class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if(n == 1) return n;
int result = 0;
for(int i = 0; i< n; i++){
for(int j = i+1; j< n; j++){
result = Math.max(result, getPoints(i, j, points));
}
}
return result;
}
private int getPoints(int pt1, int pt2, int[][] points){
int[] point1 = points[pt1], point2 = points[pt2];
double slope = (point1[1] - point2[1])/(double)(point1[0] - point2[0]);
int result = 0;
for(int i = 0; i<points.length; i++){
if((points[i][0] == point1[0] && points[i][1] == point1[1]) ||
(slope == Double.POSITIVE_INFINITY && (point1[1] - points[i][1])/(double)(point1[0] - points[i][0]) == Double.POSITIVE_INFINITY) ||
((double)(point1[1] - points[i][1])/(double)(point1[0] - points[i][0]) == slope))
result++;
}
return result;
}
} | class Solution {
public:
//DP solution
//TC-O(N*N)
//SC- ~ O(N*N)
//Custom Sort
bool static cmp(vector<int> p1,vector<int> p2){
if(p1[0]==p2[0])
return p1[1]<p2[1];
return p1[0]<p2[0];
}
//Slope Calculating
float calcSlope(int x1,int y1,int x2,int y2){
return (y2-y1)/(float)(x2-x1);
}
int maxPoints(vector<vector<int>>& points) {
if(points.size()==2 || points.size()==1)
return points.size();
sort(points.begin(),points.end(),cmp);
int ans=1;
//How much points having same slope at current index
vector<unordered_map<float,int>> dp(points.size()+1);
for(int i=1;i<points.size();i++){
for(int j=0;j<i;j++){
float slope=calcSlope(points[j][0],points[j][1],points[i][0],points[i][1]);
if(dp[j].find(slope)!=dp[j].end()){
dp[i][slope]=1+dp[j][slope];
ans=max(ans,dp[i][slope]);
}else{
dp[i][slope]+=1;
}
}
}
//return ans
return ans+1;
}
}; | /**
* @param {number[][]} points
* @return {number}
*/
var maxPoints = function(points) {
if (points.length === 1) {
return 1;
}
const slopes = {};
let dx, dy;
let xbase, ybase;
let xref, yref, key;
const INFINITE_SLOPE = 'infinite';
for(let i = 0; i < points.length; i++) {
[xbase, ybase] = points[i];
for(let j = i + 1; j < points.length; j++) {
[xref, yref] = points[j];
if (xref === xbase) {
key = `x = ${xref}`;
} else {
dx = xref - xbase;
dy = yref - ybase;
let m = dy / dx;
let c = yref - m * xref;
m = m.toFixed(4);
c = c.toFixed(4);
key = `y = ${m}x + ${c}`;
}
slopes[key] || (slopes[key] = 0);
slopes[key]++;
}
}
const maxPairs = Math.max(...Object.values(slopes));
if (maxPairs === 2) {
return 2;
}
for(let i = 1; i <= 300; i++) {
if (i * (i - 1) / 2 === maxPairs) {
return i;
}
}
return 0;
}; | Max Points on a Line |
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
| class Solution(object):
def numberOfSubarrays(self, nums, k):
"""
e.g. k = 2
nums = [2, 2, 1, 2, 1, 2, 2]
index= 0 1 2 3 4 5 6
2 even numbers to left of first 1
2 even numbers to right of last 1
total number of subarrays = pick between 0-2 numbers on left, then, pick between 0-2 numbers on right
i.e (left+1) (right+1)
Then slide window to next set of 2 odd numbers
"""
odds = []
for i in range(len(nums)):
if nums[i] & 1:
odds.append(i) #' Find index of all odd numbers '
odds = [-1] + odds + [len(nums)] #' Handle edge cases '
nice = 0
for i in range(1, len(odds)-k):
left = odds[i] - odds[i-1] - 1 #' Number of 'left' even numbers '
right = odds[i+k] - odds[i+k-1] - 1 #' Number of 'right' even numbers '
nice += (left+1)*(right+1) #' Total sub-arrays in current window '
return nice
| class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int i = 0;
int j = 0;
int odd = 0;
int result = 0;
int temp = 0;
/*
Approach : two pointer + sliding window technique
step 1 : we have fix i and moving j until our count of odd numbers == k
step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i
why temp?
from reducing the size of subarray we will count all the possible subarray from between i and j
but when i encounter a odd element the odd count will reduce and that while will stop executing
now there are two possible cases
1.The leftover elements have a odd number
2.The leftover elements do not have any odd number
1. if our leftover elements have a odd number
then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed
that's why temp = 0;
2. if out leftover elements do not have any odd element left
then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays
*/
while(j< nums.length){
if(nums[j]%2 != 0)
{
odd++;
//if leftover elements have odd element then new window is formed so we set temp = 0;
temp = 0;
}
while(odd ==k){
temp++;
if(nums[i] %2 != 0)
odd--;
i++;
}
//if no leftover elements is odd, each element will part in forming subarray
//so include them
result += temp;
j++;
}
return result;
}
} | class Solution {
public:
vector<int> nums;
int solve(int k){
int low = 0, high = 0, cnt = 0, res = 0;
while(high < nums.size()){
if(nums[high] & 1){
cnt++;
while(cnt > k){
if(nums[low] & 1) cnt--;
low++;
}
}
high++;
res += high - low;
}
return res;
}
int numberOfSubarrays(vector<int>& nums, int k) {
this -> nums = nums;
return solve(k) - solve(k - 1);
}
}; | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var numberOfSubarrays = function(nums, k) {
const len = nums.length;
const pre = new Array(len).fill(-1);
const post = new Array(len).fill(len);
let lastOcc = -1;
for(let i = 0; i < len; i++) {
pre[i] = lastOcc;
if(nums[i] & 1) lastOcc = i;
}
lastOcc = len;
for(let i = len - 1; i >= 0; i--) {
post[i] = lastOcc;
if(nums[i] & 1) lastOcc = i;
}
let l = 0, r = 0, oddCount = 0;
let ans = 0;
for(; r < len; r++) {
while(l < len && !(nums[l] & 1)) l++;
if(nums[r] & 1) oddCount++;
if(oddCount == k) {
let leftCount = l - pre[l];
let rightCount = post[r] - r;
ans += leftCount * rightCount;
oddCount--;
l++;
}
}
return ans;
}; | Count Number of Nice Subarrays |
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Constraints:
1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
There is at most one road connecting any two intersections.
You can reach any intersection from any other intersection.
| class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
graph = defaultdict(dict)
for u, v, w in roads:
graph[u][v] = graph[v][u] = w
dist = {i:float(inf) for i in range(n)}
ways = {i:0 for i in range(n)}
dist[0], ways[0] = 0, 1
heap = [(0, 0)]
while heap:
d, u = heapq.heappop(heap)
if dist[u] < d:
continue
for v in graph[u]:
if dist[v] == dist[u] + graph[u][v]:
ways[v] += ways[u]
elif dist[v] > dist[u] + graph[u][v]:
dist[v] = dist[u] + graph[u][v]
ways[v] = ways[u]
heapq.heappush(heap, (dist[v], v))
return ways[n-1] % ((10 ** 9) + 7) | class Solution {
class Pair{
int node;
int dist;
Pair(int node , int dist){
this.node = node;
this.dist = dist;
}
}
public int countPaths(int n, int[][] roads) {
int mod = (int)Math.pow(10 , 9) + 7;
ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
int rows = roads.length;
for(int i = 0 ; i < n ; i++)
adj.add(new ArrayList<Pair>());
for(int i = 0 ; i < rows ; i++){
int from = roads[i][0];
int to = roads[i][1];
int dis = roads[i][2];
adj.get(from).add(new Pair(to , dis));
adj.get(to).add(new Pair(from , dis));
}
PriorityQueue<Pair> pq = new PriorityQueue<>((aa , bb) -> aa.dist - bb.dist);
pq.add(new Pair(0 , 0));
long[] ways = new long[n];
ways[0] = 1;
int[] dist = new int[n];
Arrays.fill(dist , Integer.MAX_VALUE);
dist[0] = 0;
while(!pq.isEmpty()){
Pair p = pq.remove();
int node = p.node;
int dis = p.dist;
for(Pair pa : adj.get(node)){
if((dis + pa.dist) < dist[pa.node]){
ways[pa.node] = ways[node];
dist[pa.node] = dis + pa.dist;
pq.add(new Pair(pa.node , dist[pa.node]));
}
else if((dis + pa.dist) == dist[pa.node]){
ways[pa.node] += ways[node];
ways[pa.node] = ways[pa.node] % mod;
}
}
}
return (int)ways[n - 1];
}
} | class Solution {
public:
int countPaths(int n, vector<vector<int>>& roads) {
int mod = 1e9+7;
vector<vector<pair<int, int>>> graph(n);
for(auto &road: roads) {
graph[road[0]].push_back({road[1], road[2]});
graph[road[1]].push_back({road[0], road[2]});
}
vector<long long> distance(n, LONG_MAX);
vector<int> path(n, 0);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
pq.push({0, 0});
distance[0] = 0;
path[0] = 1;
while(!pq.empty()) {
pair<long long, int> t = pq.top();
pq.pop();
for(auto &nbr: graph[t.second]) {
long long vert = nbr.first;
long long edge = nbr.second;
if(distance[vert] > distance[t.second] + edge) {
distance[vert] = distance[t.second] + edge;
pq.push({distance[vert], vert});
path[vert] = path[t.second] %mod;
}
else if(distance[vert] == t.first + edge) {
path[vert] += path[t.second];
path[vert] %= mod;
}
}
}
return path[n-1];
}
}; | /**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var countPaths = function(n, roads) {
let adj = {}, dist = Array(n).fill(Infinity), minHeap = new MinHeap(), count = Array(n).fill(1);
//CREATE ADJ MATRIX
for(let [from, to , weight] of roads){
adj[from] = adj[from] || []
adj[from].push([to, weight]);
adj[to] = adj[to] || []
adj[to].push([from, weight]);
}
//PUT START IN QUEUE
dist[n-1] = 0;
minHeap.enqueue(n-1, 0);
while(minHeap.getSize()){
let [node, curDist] = minHeap.dequeue();
let children = adj[node] || [];
for(let [childNode, childWeight] of children){
//IF PATH ALREADY FOUND WITH THIS VALUE THEN ADD COUNT REACHED UNTIL NOW
if(curDist + childWeight === dist[childNode]){
count[childNode] = (count[childNode] +count[node]) % 1000000007;
} //IF NOT PATH FOUND YET THEN ADD COUNT OF WAYS TO THE NODE WE CAME FROM
else if(curDist + childWeight < dist[childNode]){
count[childNode] = count[node];
dist[childNode] = curDist + childWeight;
minHeap.enqueue(childNode, dist[childNode]);
}
}
}
return count[0];
};
class MinHeap{
constructor(list = []){
this.tree = [null];
this.list = list;
this.build();
}
build(){
for(let [val,priority] of this.list)
this.enqueue(val,priority);
}
swap(pos1, pos2){
[this.tree[pos1], this.tree[pos2]] = [this.tree[pos2],this.tree[pos1]]
}
enqueue(val, priority){
this.tree[this.tree.length] = [val, priority];
let i = this.tree.length - 1, parent = ~~(i/2);
while(i > 1){
if(this.tree[parent][1] > this.tree[i][1])
this.swap(parent,i);
i = parent;
parent = ~~(i/2);
}
}
dequeue(){
let size = this.tree.length - 1, pos = 1;
if(!size) return;
let last = this.tree.pop(), deleted = this.tree[pos];
if(!deleted && last) return last;
this.tree[pos] = last;
this.heapify(pos);
return deleted;
}
heapify(pos){
if(pos > this.tree.length) return;
let leftPos = 2*pos, rightPos = 2*pos +1;
let left = this.tree[leftPos] ? this.tree[leftPos][1] : Infinity;
let right = this.tree[rightPos] ? this.tree[rightPos][1] : Infinity, minVal = null, minIndex = null;
if(left < right){
minVal = left;
minIndex = leftPos;
}else{
minVal = right;
minIndex = rightPos
}
if(this.tree[pos][1] > minVal){
this.swap(pos,minIndex);
this.heapify(minIndex);
}
}
getTree(){
console.log(this.tree.slice(1));
}
getSize(){
return this.tree.length - 1;
}
} | Number of Ways to Arrive at Destination |
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
If isLefti == 1, then childi is the left child of parenti.
If isLefti == 0, then childi is the right child of parenti.
Construct the binary tree described by descriptions and return its root.
The test cases will be generated such that the binary tree is valid.
Example 1:
Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
Output: [50,20,80,15,17,19]
Explanation: The root node is the node with value 50 since it has no parent.
The resulting binary tree is shown in the diagram.
Example 2:
Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]]
Output: [1,2,null,null,3,4]
Explanation: The root node is the node with value 1 since it has no parent.
The resulting binary tree is shown in the diagram.
Constraints:
1 <= descriptions.length <= 104
descriptions[i].length == 3
1 <= parenti, childi <= 105
0 <= isLefti <= 1
The binary tree described by descriptions is valid.
| class Solution:
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
hashmap = {}
nodes = set()
children = set()
for parent,child,isLeft in descriptions:
nodes.add(parent)
nodes.add(child)
children.add(child)
if parent not in hashmap:
hashmap[parent] = TreeNode(parent)
if child not in hashmap:
hashmap[child] = TreeNode(child)
if isLeft:
hashmap[parent].left = hashmap[child]
if not isLeft:
hashmap[parent].right = hashmap[child]
for node in nodes:
if node not in children:
return hashmap[node] | class Solution {
public TreeNode createBinaryTree(int[][] descriptions) {
HashMap<Integer,TreeNode> map=new HashMap<>();
HashSet<Integer> children=new HashSet<>();
for(int[] info:descriptions)
{
int parent=info[0],child=info[1];
boolean isLeft=info[2]==1?true:false;
TreeNode parentNode=null;
TreeNode childNode=null;
if(map.containsKey(parent))
parentNode=map.get(parent);
else
parentNode=new TreeNode(parent);
if(map.containsKey(child))
childNode=map.get(child);
else
childNode=new TreeNode(child);
if(isLeft)
parentNode.left=childNode;
else
parentNode.right=childNode;
map.put(parent,parentNode);
map.put(child,childNode);
children.add(child);
}
TreeNode root=null;
for(int info[]:descriptions)
{
if(!children.contains(info[0]))
{
root=map.get(info[0]);
break;
}
}
return root;
}
} | class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions){
unordered_map<int, TreeNode*> getNode; //to check if node alredy exist
unordered_map<int, bool> isChild; //to check if node has parent or not
for(auto &v: descriptions){
if(getNode.count(v[0])==0){
TreeNode* par = new TreeNode(v[0]);
getNode[v[0]] = par;
}
if(getNode.count(v[1])==0){
TreeNode* child = new TreeNode(v[1]);
getNode[v[1]] = child;
}
if(v[2]==1) getNode[v[0]]->left = getNode[v[1]]; //left-child
else getNode[v[0]]->right = getNode[v[1]]; //right-child
isChild[v[1]] = true;
}
TreeNode* ans = NULL;
for(auto &v: descriptions){
if(isChild[v[0]] != true){ //if node has no parent then this is root node
ans = getNode[v[0]];
break;
}
}
return ans;
}
}; | var createBinaryTree = function(descriptions) {
let nodes = new Map(), children = new Set();
for (let [parent, child, isLeft] of descriptions) {
let parentNode = nodes.get(parent) || new TreeNode(parent);
if (!nodes.has(parent)) nodes.set(parent, parentNode);
let childNode = nodes.get(child) || new TreeNode(child);
if (!nodes.has(child)) nodes.set(child, childNode);
if (isLeft) parentNode.left = childNode;
else parentNode.right = childNode;
children.add(child);
}
for (let [parent, child, isLeft] of descriptions) {
// a node with no parent is the root
if (!children.has(parent)) return nodes.get(parent);
}
}; | Create Binary Tree From Descriptions |
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
Constraints:
1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
All strings in favoriteCompanies[i] are distinct.
All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
All strings consist of lowercase English letters only.
| class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
F = favoriteCompanies
ans = []
seen = set()
for i in range(len(F)):
for j in range(i+1,len(F)):
st1 = set(F[i])
st2 = set(F[j])
if st1.intersection(st2) == st1: seen.add(i)
if st2.intersection(st1) == st2: seen.add(j)
ans = []
for i in range(len(F)):
if i in seen: continue
ans.append(i)
return ans | class Solution {
public List<Integer> peopleIndexes(List<List<String>> favoriteCompanies) {
Set<String>[] fav = new Set[favoriteCompanies.size()];
Set<Integer> set = new HashSet<>();
for (int i = 0; i < favoriteCompanies.size(); i++) {
set.add(i);
fav[i] = new HashSet<>(favoriteCompanies.get(i));
}
for (int i = 1; i < favoriteCompanies.size(); i++) {
if (!set.contains(i)) continue;
for (int j = 0; j < i; j++) {
if (!set.contains(j)) continue;
if (isSubSet(fav[j], fav[i])) set.remove(j);
if (isSubSet(fav[i], fav[j])) set.remove(i);
}
}
List<Integer> ans = new ArrayList<>(set);
Collections.sort(ans);
return ans;
}
private boolean isSubSet(Set<String> child, Set<String> parent) {
if (child.size() > parent.size()) return false;
return parent.containsAll(child);
}
} | /*
* author: deytulsi18
* problem: https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
* time complexity: O(n*n*m)
* auxiliary space: O(1)
* language: cpp
*/
class Solution {
public:
bool isSubset(vector<string> &b, vector<string> &a)
{
return (includes(a.begin(), a.end(),
b.begin(), b.end()));
}
vector<int> peopleIndexes(vector<vector<string>>& favoriteCompanies) {
int n = favoriteCompanies.size();
vector<int> res;
for (auto &i : favoriteCompanies)
sort(begin(i), end(i));
for (int i = 0; i < n; i++)
{
bool isValid = true;
for (int j = 0; j < n; j++)
if (i != j)
if (isSubset(favoriteCompanies[i], favoriteCompanies[j]))
{
isValid = false;
break;
}
if (isValid)
res.emplace_back(i);
}
return res;
}
};; | var peopleIndexes = function(favoriteCompanies) {
let arr = favoriteCompanies
let len = arr.length
let ret = []
for(let i = 0; i < len; i++) {
let item1 = arr[i]
let isSubset = false
for(let j = 0; j < len; j++) {
if(i === j) continue
let item2 = arr[j]
let s = new Set(item2)
if(item1.every(a => s.has(a))) {
isSubset = true
break
}
}
if(!isSubset) ret.push(i)
}
return ret
}; | People Whose List of Favorite Companies Is Not a Subset of Another List |
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 104
text consists of lower case English letters only.
| class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}
for char in text:
if not char in freq:
continue
step = 0.5 if char == 'l' or char == 'o' else 1
freq[char] += step
result = min(freq.values())
return floor(result) | class Solution {
public int maxNumberOfBalloons(String text) {
return maxNumberOfWords(text, "balloon");
}
private int maxNumberOfWords(String text, String word) {
final int[] tFrequencies = new int[26];
for (int i = 0; i < text.length(); ++i) {
tFrequencies[text.charAt(i) - 'a']++;
}
final int[] wFrequencies = new int[26];
for (int i = 0; i < word.length(); ++i) {
wFrequencies[word.charAt(i) - 'a']++;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < 26; ++i) {
if (wFrequencies[i] > 0) {
final int count = (tFrequencies[i] / wFrequencies[i]);
if (count < min) {
min = count;
}
}
}
return min;
}
} | class Solution {
public:
int maxNumberOfBalloons(string text) {
map<char,int>m;
for(int i=0;i<text.length();i++)
{
m[text[i]]++;
}
string s="balloon";
int flag=1;
int c=0;
while(1)
{
for(int i=0;i<s.length();i++)
{
m[s[i]]--;
if(m[s[i]]==-1)
{
flag=0;
}
}
if(flag==0)
break;
c++;
}
return c;
}
}; | /**
* @param {string} text
* @return {number}
*/
var maxNumberOfBalloons = function(text) {
// 1. create hashmap with "balloon" letters
// 2. keep track of how many letters in text belong to "balloon"
// 3. account for fact that we need two "l" and "o" per "balloon" instance
// 4. then select all map values and get the minimum - this will be the max value
const balloonMap = {
"b": 0,
"a": 0,
"l": 0,
"o": 0,
"n": 0
}
for (const char of text) {
if (balloonMap[char] !== undefined) {
balloonMap[char] += 1
}
}
const letterFreq = []
for (const key in balloonMap) {
if (["l", "o"].includes(key)) {
letterFreq.push(Math.floor(balloonMap[key]/2))
} else {
letterFreq.push(balloonMap[key])
}
}
return Math.min(...letterFreq)
}; | Maximum Number of Balloons |
Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
Example 1:
Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2
Example 2:
Input: board = [["."]]
Output: 0
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j] is either '.' or 'X'.
Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?
| class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m = len(board)
n = len(board[0])
res = 0
pole = [ [True for i in range(n)] for j in range(m) ]
for i in range(m):
for j in range(n):
if board[i][j] == 'X' and pole[i][j]:
for z in range(i+1, m):
if board[z][j] == 'X':
pole[z][j] = False
else:
break
for z in range(j+1, n):
if board[i][z] == 'X':
pole[i][z] = False
else:
break
res += 1
return res | class Solution {
public int countBattleships(char[][] board) {
int result = 0;
for(int i = 0;i<board.length;i++)
{
for(int j = 0;j<board[i].length;j++)
{
if(board[i][j] == 'X')
{
remover(i, j, board);
result++;
}
}
}
return result;
}
public void remover(int i , int j, char[][] board)
{
if(i<0 || i>= board.length || j<0 || j>=board[0].length || board[i][j] == '.')
{
return;
}
board[i][j] = '.';
remover(i+1, j, board);
remover(i, j+1, board);
}
} | class Solution {
public:
bool isSafe(int i,int j,int r,int c,vector<vector<char>> &arr,vector<vector<bool>> &visited){
if(i<0 || i>r || j<0 || j>c){
return false;
}
// cout<<arr[i][j]<<" ";
if(arr[i][j]!='X'){
return false;
}
if(arr[i][j] == 'X' && visited[i][j] == true){
return false;
}
if(arr[i][j] == 'X' && visited[i][j] == false){
return true;
}
return false;
}
void solve(vector<vector<char>> &arr,vector<vector<bool>> &visited,int &r,int &c,int i,int j){
if((i>r && j>c) && (i<0 && j<0)){
return;
}
// down (i+1,j)
if(isSafe(i+1,j,r,c,arr,visited)){
visited[i+1][j] = true;
solve(arr,visited,r,c,i+1,j);
}else{
// if(arr[i][j] == 'X'){
// visited[i][j] = true;
// }
}
// // right (i,j+1)
if(isSafe(i,j+1,r,c,arr,visited)){
visited[i][j+1] = true;
solve(arr,visited,r,c,i,j+1);
}else{
// if(arr[i][j] == 'X'){
// visited[i][j] = true;
// }
}
// left (i,j-1);
if(isSafe(i,j-1,r,c,arr,visited)){
visited[i][j-1] = true;
solve(arr,visited,r,c,i,j-1);
}else{
// if(arr[i][j] == 'X'){
// visited[i][j] = true;
// }
}
// up (i-1,j)
if(isSafe(i-1,j,r,c,arr,visited)){
visited[i-1][j] = true;
solve(arr,visited,r,c,i-1,j);
}else{
// if(arr[i][j] == 'X'){
// visited[i][j] = true;
// }
}
}
int countBattleships(vector<vector<char>>& board) {
int row = board.size()-1;
int col = board[0].size()-1;
vector<vector<bool>> isVisited(row+1,vector<bool>(col+1,false));
vector<vector<int>> toStart;
for(int i=0;i<board.size();i++){
for(int j=0;j<board[i].size();j++){
if(board[i][j] == 'X'){
vector<int> temp(2);
temp[0] = i;
temp[1] = j;
// cout<<i<<" "<<j<<endl;
toStart.push_back(temp);
}
}
}
int ans = 0;
for(int i=0;i<toStart.size();i++){
if(isVisited[toStart[i][0]][toStart[i][1]]){
}else{
isVisited[toStart[i][0]][toStart[i][1]] = true;
solve(board,isVisited,row,col,toStart[i][0],toStart[i][1]);
ans++;
}
}
// for(auto cc:isVisited){
// for(auto c:cc){
// cout<<c<<" ";
// }
// cout<<endl;
// }
return ans;
}
}; | var countBattleships = function(board) {
let count = 0;
for(let rowIndex = 0; rowIndex < board.length; rowIndex++){
for(let columnIndex = 0; columnIndex < board[rowIndex].length; columnIndex++){
const isTopEmpty = rowIndex === 0 || board[rowIndex - 1][columnIndex] !== "X";
const isLeftEmpty = columnIndex === 0 || board[rowIndex][columnIndex - 1] !== "X";
const isBattleShip = board[rowIndex][columnIndex] === "X" && isTopEmpty && isLeftEmpty;
if(isBattleShip){
count++;
}
}
}
return count;
}; | Battleships in a Board |
Given an array arr that represents a permutation of numbers from 1 to n.
You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.
You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.
Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.
Constraints:
n == arr.length
1 <= m <= n <= 105
1 <= arr[i] <= n
All integers in arr are distinct.
| class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
n = len(arr)
ans = -1
if n == m: return m #just in case
# make in "inverted" array with artificial ends higher then everything between
sor= [0 for _ in range(n+2)]
for i in range(n):
sor[(arr[i])] = i+1
sor[0] = sor[n+1] = n+1
# scan and see, if ones in the middle of space of length m appear
# before ones on its ends,
# and find the latest of such spaces to disappear, if exists
for i in range(1, n-m+2):
if all(sor[i-1]>sor[j] and sor[i+m]>sor[j] for j in range(i,i+m)):
if min(sor[i-1]-1,sor[i+m]-1)>ans: ans = min(sor[i-1]-1,sor[i+m]-1)
return ans | class Solution {
int[] par, size, count, bits;
// par: parent array, tells about whose it the parent of ith element
// size: it tells the size of component
// count: it tells the count of islands (1111 etc) of size i;
// count[3] = 4: ie -> there are 4 islands of size 3
public int find(int u) {
if (u == par[u]) return u;
par[u] = find(par[u]);
return par[u];
}
public void union(int u, int v) {
// union is performed over parents of elements not nodes itself
int p1 = find(u), p2 = find(v);
if (p1 == p2) return;
// decrease the count of islands of size p1, p2
count[size[p1]]--;
count[size[p2]]--;
// now merge
par[p2] = p1;
// adjust sizes
size[p1] += size[p2];
// adjust the count of islands of new size ie: size of p1
count[size[p1]]++;
}
public int findLatestStep(int[] arr, int m) {
int n = arr.length;
par = new int[n + 1];
size = new int[n + 1];
count = new int[n + 1];
bits = new int[n + 2];
for (int i = 0; i < n; i++) {
par[i] = i;
size[i] = 1;
}
int ans = -1;
for (int i = 0; i < n; i++) {
int idx = arr[i];
// set the bit
bits[idx] = 1;
// increase the count of islands of size 1
count[1]++;
if (bits[idx - 1] > 0) {
union(idx, idx - 1);
}
if (bits[idx + 1] > 0) {
union(idx, idx + 1);
}
// check if island of size m exists
if (count[m] > 0) {
ans = i + 1;
// as it is 1 based indexing
}
}
return ans;
}
} | class Solution {
public:
int findLatestStep(vector<int>& arr, int m) {
int n=size(arr),ans=-1;
vector<int>cntL(n+2),indL(n+2);
for(int i=0;i<n;i++){
int li=indL[arr[i]-1],ri=indL[arr[i]+1],nl=li+ri+1;
indL[arr[i]]=nl;
indL[arr[i]-li]=nl;
indL[arr[i]+ri]=nl;
cntL[li]--;
cntL[ri]--;
cntL[nl]++;
if(cntL[m]>0)ans=i+1;
}
return ans;
}
}; | var findLatestStep = function(arr, m) {
if (m === arr.length) return arr.length
let bits = new Array(arr.length+1).fill(true), pos, flag, i, j
for (i = arr.length - 1, bits[0] = false; i >= 0; i--) {
pos = arr[i], bits[pos] = false
for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos-j]
if (flag && !bits[pos-m-1]) return i
for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos+j]
if (flag && !bits[pos+m+1]) return i
}
return -1
}; | Find Latest Group of Size M |
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input: root = [0,null,1]
Output: [1,null,1]
Constraints:
The number of nodes in the tree is in the range [0, 104].
-104 <= Node.val <= 104
All the values in the tree are unique.
root is guaranteed to be a valid binary search tree.
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
ans = []
def inorder(node):
if not node:
return node
inorder(node.left)
ans.append(node.val)
inorder(node.right)
def dfs(node):
if not node:
return None
idx = ans.index(node.val)
node.val = node.val + sum(ans[idx+1:])
dfs(node.left)
dfs(node.right)
inorder(root)
dfs(root)
return root
| class Solution {
public TreeNode convertBST(TreeNode root) {
if(root!=null) {
List<Integer> nodesValues = new ArrayList<>();
helperNodesVales(root, nodesValues);
traverseAndAdd(root, nodesValues);
return root;
}
return null;
}
private void helperNodesVales(TreeNode root, List<Integer> nodesValues) {
if (root != null) {
nodesValues.add(root.val);
}
if (root.right != null) {
helperNodesVales(root.right, nodesValues);
}
if (root.left != null) {
helperNodesVales(root.left, nodesValues);
}
if (root == null) {
return;
}
}
private void traverseAndAdd(TreeNode root, List<Integer> nodesValues) {
if (root != null) {
int rootVal = root.val;
for (int i = 0; i < nodesValues.size(); i++) {
if (nodesValues.get(i) > rootVal)
root.val += nodesValues.get(i);
}
}
if (root.right != null) {
traverseAndAdd(root.right, nodesValues);
}
if (root.left != null) {
traverseAndAdd(root.left, nodesValues);
}
if (root == null) {
return;
}
}
} | class Solution {
public:
int val = 0;
TreeNode* convertBST(TreeNode* root) {
if(root)
{
convertBST(root->right); // traverse right sub-tree
val += root->val; // add val
root->val = val; // update val
convertBST(root->left); // traverse left sub-tree
}
return root;
}
}; | var convertBST = function(root) {
let sum = 0;
const go = (node) => {
if (!node) return;
go(node.right);
sum += node.val;
node.val = sum;
go(node.left);
}
go(root);
return root;
}; | Convert BST to Greater Tree |