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 an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. Example 2: Input: arr = [7] Output: 0 Explanation: Start index is the last index. You do not need to jump. Example 3: Input: arr = [7,6,9,6,9,6,9,7] Output: 1 Explanation: You can jump directly from index 0 to index 7 which is last index of the array.   Constraints: 1 <= arr.length <= 5 * 104 -108 <= arr[i] <= 108
from collections import deque class Solution: def minJumps(self, arr: List[int]) -> int: minSteps = 0 queue = deque() queue.append(0) n = len(arr) visited = set() visited.add(0) d = {i:[] for i in arr} for i, val in enumerate(arr): d[val].append(i) while queue: for _ in range(len(queue)): idx = queue.popleft() if idx == n - 1: return minSteps for i in [*d[arr[idx]], idx - 1, idx + 1]: if i not in visited and 0 <= i < n: visited.add(i) queue.append(i) d[arr[idx]].clear() minSteps += 1
/* Here we are using map and queue map for storing the array elements and where are the other indices of the same element and queue for BFS Initially we start with 0 index So we offer it to the queue Now until the queue is empty we have to do few things for a given position i> check the next index (i+1) ii> check the previous index(i-1) iii> check all the indices of the list whih are present in the map once these three things have been done we will remove the element that is arr[i] because if we did not remove it we are going to do the same repeated task over and over again and this will result in stack overflow so it is important to remove the indices which have been visited once every time we check the queue we incease the answer because viewing a queue means that we are not at the last index I hope the idea was clear :) you'll understand better when you see the code */ class Solution { public int minJumps(int[] arr) { int n = arr.length; if(n <= 1) return 0; Map<Integer, List<Integer>> mp = new HashMap<>(); for(int i = 0;i < arr.length ; i++) { if(!mp.containsKey(arr[i])) { mp.put(arr[i],new ArrayList<>()); } List<Integer> ls = mp.get(arr[i]); ls.add(i); } //System.out.print(mp); Queue<Integer> q = new LinkedList<>(); q.offer(0); int ans = 0; while(!q.isEmpty()) { ans++; int size = q.size(); for(int i = 0;i < size;i++) { int j = q.poll(); //adding j+1 if(j+1 < n && mp.containsKey(arr[j+1])) { if(j+1 == n-1) return ans; q.offer(j+1); } //adding j-1 if(j-1 > 0 && mp.containsKey(arr[j-1])) { q.offer(j-1); } //adding list indices if(mp.containsKey(arr[j])) { for(int k : mp.get(arr[j])) { //if(k == n-1) return ans; if(k != j) { if(k == n-1) return ans; q.offer(k); } } mp.remove(arr[j]); } } } return ans; } }
class Solution { public: int minJumps(vector<int>& arr) { int n = arr.size(); unordered_map<int, vector<int>>mp; for (int i = 0; i < n; i++) mp[arr[i]].push_back(i); queue<int>q; vector<bool>visited(n, false); q.push(0); int steps = 0; while(!q.empty()) { int size = q.size(); while(size--) { int currIdx = q.front(); q.pop(); if (currIdx == n - 1) return steps; //================================================================ //EXPLORE ALL POSSIBLE OPTIONS if (currIdx + 1 < n && !visited[currIdx + 1]) //OPTION-1 (Move Forward) { visited[currIdx + 1] = true; q.push(currIdx + 1); } if (currIdx - 1 >= 0 && !visited[currIdx - 1]) //OPTION-2 (Move Backward) { visited[currIdx - 1] = true; q.push(currIdx - 1); } for (int newIdx : mp[arr[currIdx]]) //OPTION-3 (Move to same valued idx) { //newIdx coud be before currIdx or after currIdx if (!visited[newIdx]) { visited[newIdx] = true; q.push(newIdx); } } //=================================================================== mp[arr[currIdx]].clear(); //EXPLAINED BELOW :) } steps++; } return -1; } };
/** * @param {number[]} arr * @return {number} */ var minJumps = function(arr) { if(arr.length <= 1) return 0; const graph = {}; for(let idx = 0; idx < arr.length; idx ++) { const num = arr[idx]; if(graph[num] === undefined) graph[num] = []; graph[num].push(idx); } let queue = []; const visited = new Set(); queue.push(0); visited.add(0); let steps = 0; while(queue.length) { const nextQueue = []; for(const idx of queue) { if(idx === arr.length - 1) return steps; const num = arr[idx]; for(const neighbor of graph[num]) { if(!visited.has(neighbor)) { visited.add(neighbor); nextQueue.push(neighbor); } } if(idx + 1 < arr.length && !visited.has(idx + 1)) { visited.add(idx + 1); nextQueue.push(idx + 1); } if(idx - 1 >= 0 && !visited.has(idx - 1)) { visited.add(idx - 1); nextQueue.push(idx - 1); } graph[num].length = 0; } queue = nextQueue; steps ++; } return -1; };
Jump Game IV
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x. &nbsp; Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. Example 2: Input: richer = [], quiet = [0] Output: [0] &nbsp; Constraints: n == quiet.length 1 &lt;= n &lt;= 500 0 &lt;= quiet[i] &lt; n All the values of quiet are unique. 0 &lt;= richer.length &lt;= n * (n - 1) / 2 0 &lt;= ai, bi &lt; n ai != bi All the pairs of richer are unique. The observations in richer are all logically consistent.
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: length = len(quiet) arr = [i for i in range(length)] indegree = [0 for _ in range(length)] graph = collections.defaultdict(list) dq = collections.deque([]) for a, b in richer: # Note that the graph is uni-directional graph[a].append(b) indegree[b] += 1 for i in range(length): if not indegree[i]: dq.append(i) while dq: node = dq.popleft() for vertex in graph[node]: indegree[vertex] -= 1 if quiet[arr[node]] < quiet[arr[vertex]]: arr[vertex] = arr[node] if not indegree[vertex]: dq.append(vertex) return arr
class Solution { ArrayList<ArrayList<Integer>> adj =new ArrayList<>(); int res[]; public int[] loudAndRich(int[][] richer, int[] quiet) { int n=quiet.length; res=new int[n]; Arrays.fill(res,-1); for(int i=0;i<n;i++) adj.add(new ArrayList<Integer>()); for(int i=0;i<richer.length;i++) { if(adj.get(richer[i][1])==null) adj.add(new ArrayList<>()); adj.get(richer[i][1]).add(richer[i][0]); } for(int i=0;i<n;i++) dfs(i,quiet); return res; } public int dfs(int node ,int[] quiet) { if(res[node]==-1) { res[node]=node; for(int v:adj.get(node)){ int cand=dfs(v,quiet); if(quiet[cand]<quiet[res[node]]) res[node]=cand; } } return res[node]; } }
class Solution { public: int dfs(int node,vector<int> &answer,vector<int> adjList[],vector<int>& quiet) { if(answer[node]==-1) { answer[node] = node; for(int child:adjList[node]) { int cand = dfs(child,answer,adjList,quiet); if(quiet[cand]<quiet[answer[node]]) answer[node] = cand; } } return answer[node]; } vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) { int n = quiet.size(); vector<int> adjList[n]; for(auto x:richer) { int v = x[0]; int u = x[1]; adjList[u].push_back(v); } vector<int> answer(n,-1); for(int node =0;node<n;node++) { dfs(node,answer,adjList,quiet); } return answer; } };
var loudAndRich = function(richer, quiet) { const map = new Map(); for (const [rich, poor] of richer) { map.set(poor, (map.get(poor) || new Set()).add(rich)); } const memo = new Map(); const getQuietest = (person) => { if (memo.has(person)) return memo.get(person); const richerList = map.get(person); let min = quiet[person]; let quietest = person; if (!richerList) { memo.set(person, quietest); return quietest; } for (const rich of richerList) { if (quiet[getQuietest(rich)] < min) { min = quiet[getQuietest(rich)]; quietest = getQuietest(rich); } } memo.set(person, quietest); return quietest; } const answer = []; for (let i=0; i<quiet.length; i++) { answer.push(getQuietest(i)); } return answer; };
Loud and Rich
Given an integer number n, return the difference between the product of its digits and the sum of its digits. &nbsp; Example 1: Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 &nbsp; Constraints: 1 &lt;= n &lt;= 10^5
class Solution: def subtractProductAndSum(self, n: int) -> int: n_to_list = list(str(n)) sum_of_digits = 0 for num in n_to_list: sum_of_digits = sum_of_digits + int(num) product_of_digits = 1 for num in n_to_list: product_of_digits = product_of_digits * int(num) answer = product_of_digits - sum_of_digits return answer
class Solution { public int subtractProductAndSum(int n) { int mul=1,sum=0; while(n!=0){ sum=sum+n%10; mul=mul*(n%10); n=n/10; } return mul-sum; } }
class Solution { public: int subtractProductAndSum(int n) { vector<int> digit; int product=1; int sum=0; while(n>0){ digit.push_back(n%10); n/=10; } for(int i=0;i<digit.size();i++){ product*=digit[i]; sum+=digit[i]; } return product-sum; } };
var subtractProductAndSum = function(n) { let product=1,sum=0 n=n.toString().split('') n.forEach((x)=>{ product *=parseInt(x) sum +=parseInt(x) } ) return product-sum };
Subtract the Product and Sum of Digits of an Integer
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] &lt; perm[i + 1], and s[i] == 'D' if perm[i] &gt; perm[i + 1]. Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them. &nbsp; Example 1: Input: s = "IDID" Output: [0,4,1,3,2] Example 2: Input: s = "III" Output: [0,1,2,3] Example 3: Input: s = "DDI" Output: [3,2,0,1] &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s[i] is either 'I' or 'D'.
class Solution: def diStringMatch(self, s: str) -> List[int]: result = [] min_ = 0 max_ = len(s) for x in s: if x=="I": result.append(min_) min_ += 1 elif x=="D": result.append(max_) max_ -= 1 result.append(min_) return result
class Solution { public int[] diStringMatch(String s) { int low = 0; int high = s.length(); int[] ans = new int[s.length() + 1]; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == 'I'){ ans[i] = low++; } else{ ans[i] = high--; } } ans[s.length()] = high; return ans; } }
class Solution { public: vector<int> diStringMatch(string s) { int p=0, j=s.size(); vector<int>v; for(int i=0; i<=s.size(); i++) { if(s[i]=='I')v.push_back(p++); else v.push_back(j--); } return v; } };
var diStringMatch = function(s) { let i = 0, d = s.length, arr = []; for(let j = 0; j <= s.length; j += 1) { if(s[j] === 'I') arr.push(i++); else arr.push(d--); } return arr; };
DI String Match
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. &nbsp; Example 1: Input: nums = [3,6,1,2,5], k = 2 Output: 2 Explanation: We can partition nums into the two subsequences [3,1,2] and [6,5]. The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2. The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1. Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed. Example 2: Input: nums = [1,2,3], k = 1 Output: 2 Explanation: We can partition nums into the two subsequences [1,2] and [3]. The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1. The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0. Since two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3]. Example 3: Input: nums = [2,2,4,5], k = 0 Output: 3 Explanation: We can partition nums into the three subsequences [2,2], [4], and [5]. The difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0. The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0. The difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0. Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 105 0 &lt;= k &lt;= 105
class Solution: def partitionArray(self, nums: List[int], k: int) -> int: nums.sort() ans = 1 # To keep track of starting element of each subsequence start = nums[0] for i in range(1, len(nums)): diff = nums[i] - start if diff > k: # If difference of starting and current element of subsequence is greater # than K, then only start new subsequence ans += 1 start = nums[i] return ans
class Solution { public int partitionArray(int[] nums, int k) { Arrays.sort(nums); int c = 1, prev = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] - nums[prev] <= k) continue; c++; prev = i; } return c; } }
class Solution { public: int partitionArray(vector<int>& nums, int k) { int n(size(nums)), res(0); sort(begin(nums), end(nums)); for (int start=0, next=0; start<n;) { while (next<n and nums[next]-nums[start] <= k) next++; start = next; res++; } return res; } };
/** * @param {number[]} nums * @param {number} k * @return {number} */ var partitionArray = function(nums, k) { nums.sort((a,b) =>{ return a-b}) let n = nums.length ,ans=0 for(let i=0 ; i<n; i++){ let ele = nums[i] while(i<n && nums[i]-ele<=k) i++ i-- ans++ } return ans };
Partition Array Such That Maximum Difference Is K
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 &lt;= i &lt; j &lt; nums.length and nums[i] &gt; nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 3, k = 0 Output: 1 Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. Example 2: Input: n = 3, k = 1 Output: 2 Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. &nbsp; Constraints: 1 &lt;= n &lt;= 1000 0 &lt;= k &lt;= 1000
class Solution: def kInversePairs(self, n: int, k: int) -> int: # Complexity: # - Time: O(N*K) # - Space: O(K) # Special cases that can be short-circuited right away # - For k=0, there's only one solution, which is having the numbers in sorted order # DP(n, 0) = 1 if k == 0: return 1 # - There can't be more than n*(n-1)/2 inverse pairs, which corresponds to the numbers in reverse order # DP(n, k) = 0 for all k > n*(n-1)/2 if k > n * (n - 1) // 2: return 0 # For the general case, we notice that: # DP(n+1, k) = sum(DP(n, i) for i in [max(0, k-n), k]) # i.e., adding an additional number (the biggest one n+1): # - We can have it at the end, in which case it doesn't create any reverse pairs, # and so the number of configurations with k reverse pairs is DP(n,k) # - Or we can have it one before the end, in which case it creates exactly reverse pairs, # and so the number of configurations with k reverse pairs is DP(n,k-1) # - And so on and so forth, such that having it `i` places before the end create exactly `i` reverse pairs, # and so the number of configurations with k reverse pairs is DP(n,k-i) # This relationship allows us to compute things iteratively with a rolling window sum kLine = [0] * (k + 1) kLine[0] = 1 previousKLine = kLine.copy() maxFeasibleK = 0 for m in range(2, n + 1): previousKLine, kLine = kLine, previousKLine rollingWindowSum = 1 maxFeasibleK += m - 1 endKLineIdx = min(k, maxFeasibleK) + 1 intermediateKLineIdx = min(endKLineIdx, m) for kLineIdx in range(1, intermediateKLineIdx): rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx]) % _MODULO kLine[kLineIdx] = rollingWindowSum for kLineIdx in range(intermediateKLineIdx, endKLineIdx): rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx] - previousKLine[kLineIdx - m]) % _MODULO kLine[kLineIdx] = rollingWindowSum return kLine[k] _MODULO = 10 ** 9 + 7
class Solution { public int kInversePairs(int n, int k) { int MOD = 1000000007; int[][] opt = new int[k + 1][n]; for (int i = 0; i <= k; i++) { for (int j = 0; j < n; j++) { if (i == 0) { opt[i][j] = 1; } else if (j > 0) { opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD; if (i >= j + 1) { opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD; } } } } return opt[k][n - 1]; } }
class Solution { public: int mod = (int)(1e9 + 7); int dp[1001][1001] = {}; int kInversePairs(int n, int k) { //base case if(k<=0) return k==0; if(dp[n][k]==0){ dp[n][k] = 1; for(int i=0; i<n; i++){ dp[n][k] = (dp[n][k] + kInversePairs(n-1,k-i))%mod; } } return dp[n][k]-1; } };
var kInversePairs = function(n, k) { const dp = new Array(n+1).fill(0).map(el => new Array(k+1).fill(0)) const MOD = Math.pow(10, 9) + 7 for(let i = 0; i < n+1; i++) { dp[i][0] = 1 } for(let i = 1; i <= n; i++) { for(let j = 1; j <= k; j++) { dp[i][j] = (dp[i][j-1] + dp[i-1][j] % MOD) - (j >= i ? dp[i-1][j-i] : 0)%MOD } } return dp[n][k] % MOD };
K Inverse Pairs Array
You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. &nbsp; Example 1: Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3] Example 2: Input: root = [4,2,7,1,3], val = 5 Output: [] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 5000]. 1 &lt;= Node.val &lt;= 107 root is a binary search tree. 1 &lt;= val &lt;= 107
# 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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: def search(root): if not root:return None if root.val==val: return root elif root.val<val: ans=search(root.right) if ans: return ans return None else: ans=search(root.left) if ans: return ans return None return search(root)
class Solution { public TreeNode searchBST(TreeNode root, int val) { if (root == null) return root; if (root.val == val) { return root; } else { return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val); } } }
// Recursive class Solution { public: TreeNode* searchBST(TreeNode* root, int& val) { if(root==NULL) return NULL; if(root->val==val) return root; if(root->val>val) return searchBST(root->left,val); return searchBST(root->right,val); } }; // Iterative class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { while(root){ if(root->val==val) return root; root=root->val>val?root->left:root->right; } return NULL; } };
//====== Recursion ====== var searchBST = function(root, val) { if (!root) return null; if (root.val===val) return root; return searchBST(root.left, val) || searchBST(root.right, val) } //====== Iteration ====== var searchBST = function(root, val) { if (!root) return null; let node = root while (node) { if (node.val === val) return node; else node = node.val > val ? node.left : node.right } return node }
Search in a Binary Search Tree
You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations: Compute multiplication, reading from left to right; Then, Compute addition, reading from left to right. You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules: If an answer equals the correct answer of the expression, this student will be rewarded 5 points; Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points; Otherwise, this student will be rewarded 0 points. Return the sum of the points of the students. &nbsp; Example 1: Input: s = "7+3*1*2", answers = [20,13,42] Output: 7 Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42] A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42] The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7. Example 2: Input: s = "3+5*2", answers = [13,0,10,13,13,16,16] Output: 19 Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16] A student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16] The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19. Example 3: Input: s = "6+0*1", answers = [12,9,6,4,8,6] Output: 10 Explanation: The correct answer of the expression is 6. If a student had incorrectly done (6+0)*1, the answer would also be 6. By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points. The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10. &nbsp; Constraints: 3 &lt;= s.length &lt;= 31 s represents a valid expression that contains only digits 0-9, '+', and '*' only. All the integer operands in the expression are in the inclusive range [0, 9]. 1 &lt;= The count of all operators ('+' and '*') in the math expression &lt;= 15 Test data are generated such that the correct answer of the expression is in the range of [0, 1000]. n == answers.length 1 &lt;= n &lt;= 104 0 &lt;= answers[i] &lt;= 1000
class Solution: def scoreOfStudents(self, s: str, answers: List[int]) -> int: @cache def fn(lo, hi): """Return possible answers of s[lo:hi].""" if lo+1 == hi: return {int(s[lo])} ans = set() for mid in range(lo+1, hi, 2): for x in fn(lo, mid): for y in fn(mid+1, hi): if s[mid] == "+" and x + y <= 1000: ans.add(x + y) elif s[mid] == "*" and x * y <= 1000: ans.add(x * y) return ans target = eval(s) cand = fn(0, len(s)) ans = 0 for x in answers: if x == target: ans += 5 elif x in cand: ans += 2 return ans
class Solution { HashMap<String , HashSet<Integer>> cache ; public int scoreOfStudents(String s, int[] answers) { cache = new HashMap(); HashSet<Integer> total_possible_ans = getPossibleAns(s); int correct_ans = getCorrectAns(s); int total_score = 0 ; for(int i=0 ; i<answers.length ; i++){ if(answers[i] == correct_ans){ total_score += 5 ; }else if(total_possible_ans.contains(answers[i])){ total_score += 2 ; } } return total_score ; } public HashSet<Integer> getPossibleAns(String s){ if(cache.containsKey(s)){ return cache.get(s) ; } HashSet<Integer> possible_ans = new HashSet() ; for(int i = 0 ; i<s.length() ; i++){ char cur = s.charAt(i) ; HashSet<Integer> left = new HashSet() ; HashSet<Integer> right = new HashSet() ; if(cur == '+' || cur == '*'){ left = getPossibleAns(s.substring(0 , i)); right = getPossibleAns(s.substring(i+1)); } for(Integer l : left){ for(Integer r : right){ if(cur == '+'){ if(l+r > 1000) continue ; // skiping for ans that are greater than 1000 possible_ans.add(l+r); }else if(cur == '*'){ if(l*r > 1000) continue ; // skiping for ans that are greater than 1000 possible_ans.add(l*r); } } } } if(possible_ans.isEmpty() && s.length() <= 1){ possible_ans.add(Integer.parseInt(s)); } cache.put(s , possible_ans); return possible_ans ; } public int getCorrectAns(String s) { Stack<Integer> stack = new Stack() ; for(int i = 0 ; i<s.length() ; i++){ // push only integers into stack if(s.charAt(i) != '+' && s.charAt(i) != '*'){ stack.push(Character.getNumericValue(s.charAt(i))) ; } // If operator is '*' , then take the last element from stack and multiply with next element // Also push into stack , and then increment i also , to avoid pushing the same next element into stack again if(s.charAt(i) == '*'){ int cur = stack.pop(); int next = Character.getNumericValue(s.charAt(i+1)) ; stack.push(cur * next); i++ ; } } // Now sum all the element in the stack to get result for '+' operator int total_sum = stack.pop() ; while(!stack.isEmpty()){ total_sum += stack.pop() ; } return total_sum ; } }
class Solution { int eval(int a, int b, char op) { if (op == '+') { return a + b; } else { return a * b; } } unordered_map<string_view, unordered_set<int>> mp; unordered_set<int> potential; unordered_set<int>& solve(string_view s) { if (auto it = mp.find(s); it != mp.end()) { return it->second; } bool res = true; int n = 0; unordered_set<int> ans; for (int i = 0; i < s.size(); i++) { char c = s[i]; if (c >= '0' && c <= '9') { n = n * 10 + (c - '0'); } else { n = 0; res = false; for (int l : solve(s.substr(0, i))) { for (int r : solve(s.substr(i + 1))) { int res2 = eval(l, r, c); if (res2 <= 1000) { ans.insert(res2); } } } } } if (res) { ans.insert(n); } return mp[s] = ans; } public: int scoreOfStudents(string s, vector<int>& answers) { int ans = 0, correct = 0; stack<int> ns, op; unordered_map<char, int> prec{ {'+', 1}, {'*', 2}, {'(', 0} }; int n = 0; for (int i = 0; i < s.size(); i++) { char c = s[i]; if (c >= '0' && c <= '9') { n = n * 10 + (c - '0'); } else if (c == '(') { op.push(c); } else if (c == ')') { ns.push(n); while (op.top() != '(') { int b = ns.top(); ns.pop(); int a = ns.top(); ns.pop(); ns.push(eval(a, b, op.top())); op.pop(); } op.pop(); n = ns.top(); ns.pop(); } else { ns.push(n); n = 0; int p = prec[c]; while (!op.empty() && prec[op.top()] >= p) { int b = ns.top(); ns.pop(); int a = ns.top(); ns.pop(); ns.push(eval(a, b, op.top())); op.pop(); } op.push(c); } } ns.push(n); while (!op.empty()) { int b = ns.top(); ns.pop(); int a = ns.top(); ns.pop(); ns.push(eval(a, b, op.top())); op.pop(); } correct = ns.top(); string_view sv{s.data(), s.size()}; solve(sv); for (int n2 : mp[sv]) { potential.insert(n2); } for (int n2 : answers) { if (n2 == correct) { ans += 5; } else if (potential.find(n2) != potential.end()) { ans += 2; } } return ans; } };
var scoreOfStudents = function(s, answers) { let correct=s.split('+').reduce((a,c)=>a+c.split('*').reduce((b,d)=>b*d,1),0), n=s.length,dp=[...Array(n)].map(d=>[...Array(n)]) let dfs=(i=0,j=n-1)=>{ if(dp[i][j]!==undefined) return dp[i][j] if(i===j) return dp[i][j]=[Number(s[i])] let ans=new Set() for(let k=i+1;k<=j-1;k+=2) for(let a1 of dfs(i,k-1)) for(let a2 of dfs(k+1,j)) if(s[k]==='*') ans.add(Number(a1)*Number(a2)) else ans.add(Number(a1)+Number(a2)) return dp[i][j]=Array.from(ans).filter(d=>d<=1000) } dfs() dp[0][n-1]=new Set(dp[0][n-1]) return answers.reduce( (a,c)=> a+ (c===correct?5:(dp[0][n-1].has(c)?2:0)) ,0) };
The Score of Students Solving Math Expression
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix: 0 means the cell cannot be walked through. 1 represents an empty cell that can be walked through. A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height. In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off. You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell). Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1. Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off. &nbsp; Example 1: Input: forest = [[1,2,3],[0,0,4],[7,6,5]] Output: 6 Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps. Example 2: Input: forest = [[1,2,3],[0,0,0],[7,6,5]] Output: -1 Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked. Example 3: Input: forest = [[2,3,4],[0,0,5],[8,7,6]] Output: 6 Explanation: You can follow the same path as Example 1 to cut off all the trees. Note that you can cut off the first tree at (0, 0) before making any steps. &nbsp; Constraints: m == forest.length n == forest[i].length 1 &lt;= m, n &lt;= 50 0 &lt;= forest[i][j] &lt;= 109 Heights of all trees are distinct.
from collections import deque class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: a = [] n = len(forest) m = len(forest[0]) for i in range(n): for j in range(m): if forest[i][j] > 1: a.append(forest[i][j]) a.sort() s = 0 ux = 0 uy = 0 for h in a: dist = [[None] * m for i in range(n)] q = deque() q.append((ux, uy)) dist[ux][uy] = 0 while q: ux, uy = q.popleft() if forest[ux][uy] == h: break d = [(-1, 0), (0, 1), (1, 0), (0, -1)] for dx, dy in d: vx = ux + dx vy = uy + dy if vx < 0 or vx >= n or vy < 0 or vy >= m: continue if forest[vx][vy] == 0: continue if dist[vx][vy] is None: q.append((vx, vy)) dist[vx][vy] = dist[ux][uy] + 1 if forest[ux][uy] == h: s += dist[ux][uy] else: return -1 return s
class Solution { //approach: 1st store all the positions in the min heap acc. to their height //now start removing the elements from the heap and calculate their dis using bfs // if at any point we cann't reach at the next position return -1; // else keep on adding the distances and return; public int cutOffTree(List<List<Integer>> forest) { PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1]))); for(int i=0;i<forest.size();i++){ for(int j=0;j<forest.get(0).size();j++){ if(forest.get(i).get(j)>1) pq.add(new int[]{i,j}); } } int ans=0; int curr[]={0,0}; while(pq.size()>0){ int[] temp=pq.poll(); int dis=calcDis(forest,curr,temp); //System.out.println(dis+" "+temp.height); if(dis==-1) return -1; ans+=dis; curr=temp; } return ans; } int calcDis(List<List<Integer>> forest,int start[],int end[]){ int n=forest.size(),m=forest.get(0).size(); boolean vis[][]=new boolean[n][m]; Queue<int[]> queue=new LinkedList<>(); queue.add(start); vis[start[0]][start[1]]=true; int dis=0; while(queue.size()>0){ int len =queue.size(); while(len-->0){ int temp[]=queue.remove(); int r=temp[0],c=temp[1]; if(r==end[0] && c==end[1]) return dis; if(r+1<n && !vis[r+1][c] && forest.get(r+1).get(c)!=0){ queue.add(new int[]{r+1,c}); vis[r+1][c]=true; }if(r-1>=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){ queue.add(new int[]{r-1,c}); vis[r-1][c]=true; }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){ queue.add(new int[]{r,c-1}); vis[r][c-1]=true; }if(c+1<m && !vis[r][c+1] && forest.get(r).get(c+1)!=0){ queue.add(new int[]{r,c+1}); vis[r][c+1]=true; } } dis++; } return -1; } }
class Solution { public: #define vi vector<int> #define vvi vector<vi> vvi forests; vvi moves; int R; int C; bool isValid(int x,int y){ return x>=0&&x<R&&y>=0&&y<C; } int getShortestDistance(int sx,int sy,int ex,int ey){ vvi vis = vvi(R,vi(C,0)); queue<pair<int,int>>Q; Q.push({sx,sy}); vis[sx][sy] = 1; int level = 0; while(!Q.empty()){ queue<pair<int,int>>childQ; while(!Q.empty()){ auto x = Q.front().first; auto y = Q.front().second; Q.pop(); if(x==ex&&y==ey) return level; for(auto ele:moves){ int nextX = x+ele[0]; int nextY = y+ele[1]; if(isValid(nextX,nextY)&&!vis[nextX][nextY]&&forests[nextX][nextY]>0){ childQ.push({nextX,nextY}); vis[nextX][nextY]=1; } } } Q=childQ; level++; } return -1; } int cutOffTree(vector<vector<int>>& forest) { moves={ {0,1}, {1,0}, {0,-1}, {-1,0} }; forests = forest; R = forest.size(); C = forest[0].size(); if(forest[0][0]==0) return -1; vector<vector<int>>trees; int i=0; while(i<R){ int j=0; while(j<C){ if(forest[i][j]>1) trees.push_back({forest[i][j],i,j}); j++; } i++; } if(trees.empty()) return -1; sort(trees.begin(),trees.end()); int sx = 0; int sy = 0; int ans = 0; for(auto it:trees){ int dis = getShortestDistance(sx,sy,it[1],it[2]); if(dis==-1) return -1; ans+=dis; sx = it[1]; sy = it[2]; } return ans; } };
var cutOffTree = function(forest) { const trees = forest.flat().filter(x => x && x !== 1).sort((a, b) => b - a); let currPos = [0, 0], totalDist = 0; while(trees.length) { const grid = [...forest.map(row => [...row])]; const res = getDist(currPos, trees.pop(), grid); if(res == null) return -1; const [pos, dist] = res; currPos = pos; totalDist += dist; } return totalDist; function getDist(start, target, grid) { const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]]; let queue = [start], dist = 0; while(queue.length) { const next = []; for(let [r, c] of queue) { if(grid[r][c] === target) return [[r, c], dist]; if(!grid[r][c]) continue; for(let [x, y] of dir) { x += r; y += c; if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y]) next.push([x, y]) } grid[r][c] = 0; } dist++; queue = next; } return null; } };
Cut Off Trees for Golf Event
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. Given an array houses, an m x n matrix cost and an integer target where: houses[i]: is the color of the house i, and 0 if the house is not painted yet. cost[i][j]: is the cost of paint the house i with the color j + 1. Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1. &nbsp; Example 1: Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 9 Explanation: Paint houses of this way [1,2,2,1,1] This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. Example 2: Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 11 Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2] This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. Cost of paint the first and last house (10 + 1) = 11. Example 3: Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3 Output: -1 Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3. &nbsp; Constraints: m == houses.length == cost.length n == cost[i].length 1 &lt;= m &lt;= 100 1 &lt;= n &lt;= 20 1 &lt;= target &lt;= m 0 &lt;= houses[i] &lt;= n 1 &lt;= cost[i][j] &lt;= 104
class Solution: def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: @cache def dp(i, p, h): if (h > target) or (i == m and h != target): return inf if i == m: return 0 if houses[i] != 0: return dp(i + 1, houses[i], h + int(p != houses[i])) best = inf for j, c in enumerate(cost[i], 1): best = min(best, dp(i + 1, j, h + int(p != j)) + c) return best res = dp(0, 0, 0) return res if res != inf else -1
class Solution { public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp) { if(idx==houses.length || neigh>target) { if(neigh==target) return 0; return Integer.MAX_VALUE; } if(dp[idx][prevColor][neigh]!=null) return dp[idx][prevColor][neigh]; int minCost = Integer.MAX_VALUE; if(houses[idx]==0) { for(int j = 0;j<cost[idx].length;j++) { int minCostHere = Integer.MAX_VALUE; if(j+1==prevColor) // Painting the house with the same colour as that of the previous one. minCostHere = helper(idx+1,houses,cost,target,prevColor,neigh,dp); else // Painting the house with a different color and incrementing the neighbour count. minCostHere = helper(idx+1,houses,cost,target,j+1,neigh+1,dp); if(minCostHere!=Integer.MAX_VALUE) minCostHere+=cost[idx][j]; minCost = Math.min(minCostHere,minCost); } } else { if(houses[idx]==prevColor) minCost = helper(idx+1,houses,cost,target,prevColor,neigh,dp); else minCost = helper(idx+1,houses,cost,target,houses[idx],neigh+1,dp); } return dp[idx][prevColor][neigh] = minCost; } public int minCost(int[] houses, int[][] cost, int m, int n, int target) { Integer[][][] dp = new Integer[m][n+1][target+1]; int ans = helper(0,houses,cost,target,0,0,dp); return ans==Integer.MAX_VALUE?-1:ans; } }
class Solution { int dp[101][22][101]; vector<int> h;//m vector<vector<int>> c;//n int mm; int nn; int t; int dfs(int idx, int prev, int curt){ if(curt<1) return INT_MAX; if(idx==mm) return (curt==1)?0:INT_MAX; if(dp[idx][prev][curt]!=-1) return dp[idx][prev][curt]; int res=INT_MAX; int color=h[idx]; if(color==0){ for(int x=0;x<nn;x++){ color=x+1; int rres=dfs(idx+1,color,curt-(prev!=21 and prev!=color)); if(rres!=INT_MAX) res=min(c[idx][color-1]+rres,res); } }else{ return dp[idx][prev][curt]=dfs(idx+1,color,curt-(prev!=21 and prev!=color)); } return dp[idx][prev][curt]=res; } public: int minCost(vector<int>& houses, vector<vector<int>>& cost, int m, int n, int target) { h=houses,c=cost,mm=m,nn=n,t=target; memset(dp,-1,sizeof(dp)); int res=dfs(0,21,t); return res==INT_MAX?-1:res; } };
var minCost = function(houses, cost, m, n, target) { let map = new Map(); function dfs(idx = 0, prevColor = -1, neighborhoods = 0) { if (idx === m) return neighborhoods === target ? 0 : Infinity; let key = `${idx}-${prevColor}-${neighborhoods}`; if (map.has(key)) return map.get(key); let color = houses[idx]; // If the current house is already painted if (color > 0) { return color !== prevColor ? dfs(idx + 1, color, neighborhoods + 1) : dfs(idx + 1, color, neighborhoods); } let minCost = Infinity; for (let i = 1; i <= n; i++) { let potentialCost; // If color i is !== prevColor, increment the neighborhood count if (i !== prevColor) potentialCost = dfs(idx + 1, i, neighborhoods + 1); // Otherwise, the neighborhood simply expanded so the neighborhood count stays the same else potentialCost = dfs(idx + 1, i, neighborhoods); if (potentialCost === Infinity) continue; minCost = Math.min(minCost, cost[idx][i - 1] + potentialCost); } map.set(key, minCost); return minCost; } let minCost = dfs(); return minCost === Infinity ? -1 : minCost; };
Paint House III
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). &nbsp; Example 1: Input: s = "1 + 1" Output: 2 Example 2: Input: s = " 2-1 + 2 " Output: 3 Example 3: Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23 &nbsp; Constraints: 1 &lt;= s.length &lt;= 3 * 105 s consists of digits, '+', '-', '(', ')', and ' '. s represents a valid expression. '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid). '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid). There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer.
```class Solution: def calculate(self, s: str) -> int: curr,output,sign,stack = 0,0,1,[] for ch in s: if ch.isdigit(): curr = curr * 10 + int(ch) elif ch == '+': output += sign * curr sign = 1 curr = 0 elif ch == '-': output += sign * curr sign = -1 curr = 0 elif ch == '(': #push the result and then the sign stack.append(output) stack.append(sign) sign = 1 output = 0 elif ch == ')': output += sign * curr output *= stack.pop() output += stack.pop() curr = 0 return output + sign*curr``
class Solution { int idx; // this index traverse the string in one pass, between different level of recursion public int calculate(String s) { idx = 0; // Initialization should be here return helper(s); } private int helper(String s) { int res = 0, num = 0, preSign = 1, n = s.length(); while (idx < n) { char c = s.charAt(idx++); if (c == '(') num = helper(s); // Let recursion solve the sub-problem else if (c >= '0' && c <= '9') num = num * 10 + c - '0'; if (c == '+' || c == '-' || c == ')' || idx == n) { // we need one more calculation when idx == n res += preSign * num; if (c == ')') return res; // end of a sub-problem num = 0; preSign = c == '+' ? 1 : -1; } } return res; } }
class Solution { public: int calculate(string s) { stack<pair<int,int>> st; // pair(prev_calc_value , sign before next bracket () ) long long int sum = 0; int sign = +1; for(int i = 0 ; i < s.size() ; ++i) { char ch = s[i]; if(isdigit(ch)) { long long int num = 0; while(i < s.size() and isdigit(s[i])) { num = (num * 10) + s[i] - '0'; i++; } i--; // as for loop also increase i , so if we don't decrease i here a sign will be skipped sum += (num * sign); sign = +1; // reseting sign } else if(ch == '(') { // Saving current state of (sum , sign) in stack st.push(make_pair(sum , sign)); // Reseting sum and sign for inner bracket calculation sum = 0; sign = +1; } else if(ch == ')') { sum = st.top().first + (st.top().second * sum); st.pop(); } else if(ch == '-') { // toggle sign sign = (-1 * sign); } } return sum; } };
var calculate = function(s) { const numStack = [[]]; const opStack = []; const isNumber = char => !isNaN(char); function calculate(a, b, op){ if(op === '+') return a + b; if(op === '-') return a - b; } let number = ''; for (let i = 0; i < s.length; i++) { const char = s[i]; if (char === ' ') continue; if (isNumber(char)) { number += char; continue; } if(number) { // i.e. char is not a number so the number has ended if (numStack[numStack.length - 1].length === 0) { numStack[numStack.length - 1].push(+number); } else { const a = numStack[numStack.length - 1].pop(); const op = opStack.pop(); numStack[numStack.length - 1].push(calculate(a, +number, op)); } number = ''; } if (char === '(') { if (numStack[numStack.length - 1].length === 0) { numStack[numStack.length - 1].push(0); opStack.push('+'); } numStack.push([]); // Start a new stack for this parenthesis continue; } if (char === ')') { const b = numStack.pop().pop(); const a = numStack[numStack.length - 1].pop(); const op = opStack.pop(); numStack[numStack.length - 1].push(calculate(a, b, op)); continue; } if (char === '+' || char === '-') { if (numStack[numStack.length - 1].length === 0) { numStack[numStack.length - 1].push(0); } opStack.push(char); continue; } // We should never reach here throw new Error('Unexpected input: ' + char); } if(number){ if (numStack[numStack.length - 1].length === 0) return +number; const a = numStack[numStack.length - 1].pop(); const op = opStack.pop(); numStack[0].push(calculate(a, +number, op)); } return numStack.pop().pop(); };
Basic Calculator
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries. If a single answer cannot be determined, return -1.0. Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. &nbsp; Example 1: Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ] Example 2: Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] Output: [3.75000,0.40000,5.00000,0.20000] Example 3: Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]] Output: [0.50000,2.00000,-1.00000,-1.00000] &nbsp; Constraints: 1 &lt;= equations.length &lt;= 20 equations[i].length == 2 1 &lt;= Ai.length, Bi.length &lt;= 5 values.length == equations.length 0.0 &lt; values[i] &lt;= 20.0 1 &lt;= queries.length &lt;= 20 queries[i].length == 2 1 &lt;= Cj.length, Dj.length &lt;= 5 Ai, Bi, Cj, Dj consist of lower case English letters and digits.
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = dict() for (n, d), v in zip(equations, values): if n not in graph: graph[n] = [] if d not in graph: graph[d] = [] graph[n].append((d, v)) graph[d].append((n, 1/v)) def dfs(node, target, product, visited): if n not in graph or d not in graph: return -1 if node == target: return product visited.add(node) for neighbor, quotient in graph[node]: if neighbor not in visited: soln = dfs(neighbor, target, product * quotient, visited) if soln != -1: return soln return -1 solns = [] for n, d in queries: solns.append(dfs(n, d, 1, set())) return solns
class Solution { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { int len = equations.size(); Map<String, Integer> varMap = new HashMap<>(); int varCnt = 0; for (int i = 0; i < len; i++) { if (!varMap.containsKey(equations.get(i).get(0))) { varMap.put(equations.get(i).get(0), varCnt++); } if (!varMap.containsKey(equations.get(i).get(1))) { varMap.put(equations.get(i).get(1), varCnt++); } } List<Pair>[] edges = new List[varCnt]; for (int i = 0; i < varCnt; i++) { edges[i] = new ArrayList<>(); } for (int i = 0; i < len; i++) { int va = varMap.get(equations.get(i).get(0)); int vb = varMap.get(equations.get(i).get(1)); edges[va].add(new Pair(vb, values[i])); edges[vb].add(new Pair(va, 1.0 / values[i])); } int queriesCnt = queries.size(); double[] ans = new double[queriesCnt]; for (int i = 0; i < queriesCnt; i++) { List<String> query = queries.get(i); double result = -1.0; if (varMap.containsKey(query.get(0)) && varMap.containsKey(query.get(1))) { int idxA = varMap.get(query.get(0)); int idxB = varMap.get(query.get(1)); if (idxA == idxB) { result = 1.0; } else { Queue<Integer> points = new LinkedList<>(); points.offer(idxA); double[] ratios = new double[varCnt]; Arrays.fill(ratios, -1.0); ratios[idxA] = 1.0; while (!points.isEmpty() && ratios[idxB] < 0) { int cur = points.poll(); for (Pair pair : edges[cur]) { int y = pair.index; double value = pair.value; if (ratios[y] < 0) { ratios[y] = ratios[cur] * value; points.offer(y); } } } result = ratios[idxB]; } } ans[i] = result; } return ans; } class Pair { int index; double value; public Pair(int index, double value) { this.index = index; this.value = value; } } }
class Solution { public: vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { map<string, vector<pair<string, double>>> graph; map<string, double> dist; map<string, bool> visited; for(int i=0;i<equations.size();i++){ if(graph.count(equations[i][0])==0){ graph[equations[i][0]] = {}; visited[equations[i][0]] = false; dist[equations[i][0]] = DBL_MAX; } if(graph.count(equations[i][1])==0){ graph[equations[i][1]] = {}; dist[equations[i][0]] = DBL_MAX; } graph[equations[i][0]].push_back({equations[i][1], values[i]}); if(values[i]!=0) graph[equations[i][1]].push_back({equations[i][0], 1/values[i]}); else graph[equations[i][1]].push_back({equations[i][0], -1}); } vector<double> result; for(int i=0;i<queries.size();i++){ if(graph.count(queries[i][0])==0 || graph.count(queries[i][1])==0){ result.push_back(-1); continue; } if(queries[i][0] == queries[i][1]){ result.push_back(1); continue; } for(auto j: visited) visited[j.first] = false; priority_queue<pair<double, string>, vector<pair<double, string>>, greater<pair<double, string>>> pq; dist[queries[i][0]] = 1;; pq.push({1, queries[i][0]}); bool flag=false; while(!pq.empty()){ auto k = pq.top(); pq.pop(); visited[k.second] = true; if(k.second==queries[i][1]){ flag=true; result.push_back(dist[k.second]); break; } for(int j=0;j<graph[k.second].size();j++){ if(!visited[graph[k.second][j].first]) {dist[graph[k.second][j].first] = dist[k.second] * graph[k.second][j].second; pq.push({dist[graph[k.second][j].first], graph[k.second][j].first});} } } if(!flag) result.push_back(-1); } return result; } };
var calcEquation = function(equations, values, queries) { const res = [] for(let i = 0; i < queries.length; i++) { const currQuery = queries[i] const [currStart, currDestination] = currQuery const adj = {} const additionalEdges = [] const additionalValues = [] const visited = new Set() equations.forEach((el,idx) => { const [to, from] = el const val = values[idx] additionalEdges.push([from, to]) additionalValues.push(1/val) }) values = [...values, ...additionalValues] let idx = 0 for(const [from, to] of [...equations, ...additionalEdges]) { if(!(from in adj)) adj[from] = [] adj[from].push([to, values[idx]]) idx++ } if(!(currStart in adj) || !(currDestination in adj)) { res.push(-1) continue } if(currStart === currDestination) { res.push(1) continue } let currEvaluation = 1 let found = false const subResult = dfs(currStart) if(!found) res.push(-1) function dfs(node) { if(!node) return null if(node === currDestination) { return true } const children = adj[node] // [ [to, val] ] if(!children) return false for(const child of children) { if(visited.has(node)) continue visited.add(node) currEvaluation = currEvaluation*child[1] if(dfs(child[0]) === true) { !found && res.push(currEvaluation) found = true return } visited.delete(node) currEvaluation /= child[1] } } } return res };
Evaluate Division
Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: arr = [1,3,5] Output: 4 Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,8,5]. Odd sums are [1,9,3,5] so the answer is 4. Example 2: Input: arr = [2,4,6] Output: 0 Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]] All sub-arrays sum are [2,6,12,4,10,6]. All sub-arrays have even sum and the answer is 0. Example 3: Input: arr = [1,2,3,4,5,6,7] Output: 16 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 105 1 &lt;= arr[i] &lt;= 100
class Solution: def numOfSubarrays(self, arr: List[int]) -> int: ce, co = 0, 0 s = 0 for x in arr: if x % 2 == 0: ce += 1 else: old_co = co co = ce + 1 ce = old_co s += co return s % (10**9+7)
//odd-even=odd //even-odd=odd class Solution { public int numOfSubarrays(int[] arr) { long ans=0; int even=0; int odd=0; long sum=0; for(int i=0;i<arr.length;i++){ sum+=arr[i]; if(sum%2==0){ ans+=odd; even++; }else{ ans+=even+1; odd++; } } return (int)(ans%(1000000007)); } }
class Solution { public: int mod = 1e9 + 7; int solve(int ind, int n, vector<int> &arr, int req, vector<vector<int>> &dp) { if(ind == n) return 0; if(dp[ind][req] != -1) return dp[ind][req]; if(req == 1) { if(arr[ind] % 2 == 0) { return dp[ind][req] = solve(ind + 1, n, arr, req, dp); } else { return dp[ind][req] = (1 + solve(ind + 1, n, arr, !req, dp)) %mod; } } else { if(arr[ind] % 2 == 0) { return dp[ind][req] = (1 + solve(ind + 1, n, arr, req, dp)) %mod; } else { return dp[ind][req] = solve(ind + 1, n, arr, !req, dp); } } } int numOfSubarrays(vector<int>& arr) { int n = arr.size(); vector<vector<int>> dp(n, vector<int> (2, -1)); int count = 0; for(int i = 0; i < n; i++) { count = (count + solve(i, n, arr, 1, dp))% mod; } return count; } };
var numOfSubarrays = function(arr) { let mod=1e9+7,sum=0,odds=0,evens=0 //Notice that I do not need to keep track of the prefixSums, I just need the total count of odd and even PrefixSums for(let i=0;i<arr.length;i++){ sum+=arr[i] odds+=Number(sum%2==1) evens+=Number(sum%2==0) } return (odds*evens+odds)%mod };
Number of Sub-arrays With Odd Sum
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. &nbsp; Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11". After concatenating them, we have "11011", which corresponds to the decimal value 27. Example 3: Input: n = 12 Output: 505379714 Explanation: The concatenation results in "1101110010111011110001001101010111100". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. &nbsp; Constraints: 1 &lt;= n &lt;= 105
class Solution: def concatenatedBinary(self, n: int) -> int: modulo = 10 ** 9 + 7 shift = 0 # tracking power of 2 res = 0 for i in range(1, n+1): if i & (i - 1) == 0: # see if num reaches a greater power of 2 shift += 1 res = ((res << shift) + i) % modulo # do the simulation return res
class Solution { public int concatenatedBinary(int n) { long res = 0; for (int i = 1; i <= n; i++) { res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007; } return (int) res; } }
class Solution { public: int numberOfBits(int n) { return log2(n) + 1; } int concatenatedBinary(int n) { long ans = 0, MOD = 1e9 + 7; for (int i = 1; i <= n; ++i) { int len = numberOfBits(i); ans = ((ans << len) % MOD + i) % MOD; } return ans; } };
var concatenatedBinary = function(n) { let num = 0; for(let i = 1; i <= n; i++) { //OR num *= (1 << i.toString(2).length) num *= (2 ** i.toString(2).length) num += i; num %= (10 ** 9 + 7) } return num; };
Concatenation of Consecutive Binary Numbers
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. &nbsp; Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false &nbsp; Constraints: 1 &lt;= s.length &lt;= 104 s consists of parentheses only '()[]{}'.
class Solution: def isValid(self, string: str) -> bool: while True: if '()' in string: string = string.replace('()', '') elif '{}' in string: string = string.replace('{}', '') elif '[]' in string: string = string.replace('[]', '') else: return not string
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); // create an empty stack for (char c : s.toCharArray()) { // loop through each character in the string if (c == '(') // if the character is an opening parenthesis stack.push(')'); // push the corresponding closing parenthesis onto the stack else if (c == '{') // if the character is an opening brace stack.push('}'); // push the corresponding closing brace onto the stack else if (c == '[') // if the character is an opening bracket stack.push(']'); // push the corresponding closing bracket onto the stack else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack // does not match the closing bracket, the string is not valid, so return false return false; } // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, // so the string is valid, otherwise, there are unmatched opening brackets, so return false return stack.isEmpty(); } }
class Solution { public: // Ref: balanced parenthesis video from LUV bhaiya YT channel unordered_map<char,int>symbols={{'[',-1},{'{',-2},{'(',-3},{']',1},{'}',2},{')',3}}; stack<char>st; bool isValid(string s) { for(auto &i:s){ if(symbols[i]<0){ st.push(i); } else{ if(st.empty()) return false; char top=st.top(); st.pop(); if(symbols[i]+symbols[top]!=0) return false; } } if(st.empty()) return true; return false; } };
var isValid = function(s) { const stack = []; for (let i = 0 ; i < s.length ; i++) { let c = s.charAt(i); switch(c) { case '(': stack.push(')'); break; case '[': stack.push(']'); break; case '{': stack.push('}'); break; default: if (c !== stack.pop()) { return false; } } } return stack.length === 0; };
Valid Parentheses
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. &nbsp; Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -104 &lt;= nums[i] &lt;= 104 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique. &nbsp; Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: return [i[0] for i in Counter(nums).most_common(k)]
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.merge(num, 1, Integer::sum); } return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .map(Map.Entry::getKey) .mapToInt(x -> x) .limit(k) .toArray(); } }
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> map; for(int num : nums){ map[num]++; } vector<int> res; // pair<first, second>: first is frequency, second is number priority_queue<pair<int,int>> pq; for(auto it = map.begin(); it != map.end(); it++){ pq.push(make_pair(it->second, it->first)); if(pq.size() > (int)map.size() - k){ res.push_back(pq.top().second); pq.pop(); } } return res; } };
var topKFrequent = function(nums, k) { let store = {}; for(let i=0;i<nums.length;i++){ store[nums[i]] = store[nums[i]]+1||1 } //returns an array of keys in sorted order let keyArr = Object.keys(store).sort((a,b)=>store[a]-store[b]) let arrLength = keyArr.length; let slicedArr = keyArr.slice(arrLength-k,arrLength) return slicedArr };
Top K Frequent Elements
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1. &nbsp; Example 1: Input: n = 4, connections = [[0,1],[0,2],[1,2]] Output: 1 Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3. Example 2: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Example 3: Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] Output: -1 Explanation: There are not enough cables. &nbsp; Constraints: 1 &lt;= n &lt;= 105 1 &lt;= connections.length &lt;= min(n * (n - 1) / 2, 105) connections[i].length == 2 0 &lt;= ai, bi &lt; n ai != bi There are no repeated connections. No two computers are connected by more than one cable.
class Solution(object): def __init__(self): self.parents = [] self.count = [] def makeConnected(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: int """ if len(connections) < n-1: return -1 self.parents = [i for i in range(n)] self.count = [1 for _ in range(n)] for connection in connections: a, b = connection[0], connection[1] self.union(a, b) return len({self.find(i) for i in range(n)}) - 1 def find(self, node): """ :type node: int :rtype: int """ while(node != self.parents[node]): node = self.parents[node]; return node def union(self, a, b): """ :type a: int :type b: int :rtype: None """ a_parent, b_parent = self.find(a), self.find(b) a_size, b_size = self.count[a_parent], self.count[b_parent] if a_parent != b_parent: if a_size < b_size: self.parents[a_parent] = b_parent self.count[b_parent] += a_size else: self.parents[b_parent] = a_parent self.count[a_parent] += b_size
class Solution { public int makeConnected(int n, int[][] connections) { int m = connections.length; if(m < n - 1) return -1; UnionFind uf = new UnionFind(n); for(int[] connection: connections){ uf.union(connection[0], connection[1]); } return uf.getIsolated(); } } class UnionFind{ int[] root; int[] rank; int isolated; public UnionFind(int n){ root = new int[n]; rank = new int[n]; for(int i = 0; i < n; i++){ root[i] = i; rank[i] = 1; } isolated = 0; } public int find(int x){ if(root[x] != x) root[x] = find(root[x]); return root[x]; } public void union(int x, int y){ int rootx = find(x); int rooty = find(y); if(rootx == rooty) return; if(rank[rootx] > rank[rooty]){ root[rooty] = rootx; }else if(rank[rootx] < rank[rooty]){ root[rootx] = rooty; }else{ root[rootx] = rooty; rank[rooty] += 1; } } public int getIsolated(){ for(int i = 0; i < root.length; i ++){ if(root[i] == i) isolated++; } return isolated - 1; } }
class Solution { public: // Union Find Approach vector<int> root; int find(int node){ if(root[node] != node){ return find(root[node]); } return node; } int makeConnected(int n, vector<vector<int>>& connections) { int m = connections.size(); if(m < n-1){ return -1; } for(int i=0 ; i<n ; i++){ root.push_back(i); } for(int i=0 ; i<m ; i++){ int v1 = connections[i][0]; int v2 = connections[i][1]; int r1 = find(v1); int r2 = find(v2); if(r1 != r2){ root[r1] = r2; } } int ans = 0; for(int i=0 ; i<n ; i++){ if(root[i] == i){ ans++; } } return ans - 1; } };
/** * @param {number} n * @param {number[][]} connections * @return {number} */ class UnionFind { constructor(n) { this.root = new Array(n).fill().map((_, index)=>index); this.components = n; } find(x) { if(x == this.root[x]) return x; return this.root[x] = this.find(this.root[x]); } union(x, y) { const rootX = this.find(x); const rootY = this.find(y); if(rootX != rootY) { this.root[rootY] = rootX; this.components--; } } } var makeConnected = function(n, connections) { // We need at least n - 1 cables to connect all nodes (like a tree). if(connections.length < n-1) return -1; const uf = new UnionFind(n); for(const [a, b] of connections) { uf.union(a, b); } return uf.components - 1; };
Number of Operations to Make Network Connected
Given two strings&nbsp;s&nbsp;and&nbsp;t, your goal is to convert&nbsp;s&nbsp;into&nbsp;t&nbsp;in&nbsp;k&nbsp;moves or less. During the&nbsp;ith&nbsp;(1 &lt;= i &lt;= k)&nbsp;move you can: Choose any index&nbsp;j&nbsp;(1-indexed) from&nbsp;s, such that&nbsp;1 &lt;= j &lt;= s.length&nbsp;and j&nbsp;has not been chosen in any previous move,&nbsp;and shift the character at that index&nbsp;i&nbsp;times. Do nothing. Shifting a character means replacing it by the next letter in the alphabet&nbsp;(wrapping around so that&nbsp;'z'&nbsp;becomes&nbsp;'a'). Shifting a character by&nbsp;i&nbsp;means applying the shift operations&nbsp;i&nbsp;times. Remember that any index&nbsp;j&nbsp;can be picked at most once. Return&nbsp;true&nbsp;if it's possible to convert&nbsp;s&nbsp;into&nbsp;t&nbsp;in no more than&nbsp;k&nbsp;moves, otherwise return&nbsp;false. &nbsp; Example 1: Input: s = "input", t = "ouput", k = 9 Output: true Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'. Example 2: Input: s = "abc", t = "bcd", k = 10 Output: false Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s. Example 3: Input: s = "aab", t = "bbb", k = 27 Output: true Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'. &nbsp; Constraints: 1 &lt;= s.length, t.length &lt;= 10^5 0 &lt;= k &lt;= 10^9 s, t contain&nbsp;only lowercase English letters.
class Solution: def canConvertString(self, s: str, t: str, k: int) -> bool: if len(s) != len(t): return False cycles, extra = divmod(k, 26) shifts = [cycles + (shift <= extra) for shift in range(26)] for cs, ct in zip(s, t): shift = (ord(ct) - ord(cs)) % 26 if shift == 0: continue if not shifts[shift]: return False shifts[shift] -= 1 return True
class Solution { public boolean canConvertString(String s, String t, int k) { //if strings lengths not equal return false if(s.length()!=t.length())return false; //array to count number of times a difference can repeat int b[]=new int[26]; int h=k/26; int h1=k%26; //count of each number from 1 to 26 from 1 to k for(int i=0;i<26;i++){ b[i]+=h; if(i<=h1)b[i]++; } int i=0; while(i<s.length()){ //if both characters equal increment i if(s.charAt(i)==t.charAt(i)){ i++; }else{ //else now find difference //+26 because we dont know it can be negative also and again mod with 26 int diff=((t.charAt(i)-s.charAt(i))+26)%26; //decrement count after usage of one value of b[diff] b[diff]--; //if b[diff]<0 means over usage than given so return false if(b[diff]<0) return false; //else finally increment else i++; } } return true; } }
class Solution { public: bool canConvertString(string s, string t, int k) { int m = s.length(), n = t.length(), count = 0; if (m != n) return false; unordered_map<int, int> mp; for (int i = 0; i < m; i++) { if (t[i] == s[i]) continue; int diff = t[i] - s[i] < 0 ? 26 + t[i] - s[i] : t[i] - s[i]; if (mp.find(diff) == mp.end()) { count = max(count, diff); } else { count = max(count, (mp[diff] * 26) + diff); } mp[diff]++; if (count > k) return false; } return count <= k; } };
/** * @param {string} s * @param {string} t * @param {number} k * @return {boolean} */ var canConvertString = function(s, t, k) { let res = true; if(s.length === t.length){ let tmp = []; let countMap = new Map(); for(let i=0; i<s.length; i++){ let n1 = s[i].charCodeAt(); let n2 = t[i].charCodeAt(); let r = n2 - n1; if(r < 0){ r += 26; } // exclude special case 0 if(r > 0){ // Considering repeated letters, the unrepeated move should change to r + 26*n (n>=0) // use hash table to count the same letter if(!countMap.has(r)){ // first time to move countMap.set(r, 1); tmp.push(r); }else{ // n time to move, n means the count of the same letter let c = countMap.get(r); tmp.push(r + c * 26); // update count countMap.set(r, c+1); } } } // check all possible move in range for(let i=0; i<tmp.length; i++){ let t = tmp[i]; if(t > k){ res = false; break; } } }else{ res = false; } return res; };
Can Convert String in K Moves
You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied. &nbsp; Example 1: Input: s = "abc", shifts = [3,5,9] Output: "rpl" Explanation: We start with "abc". After shifting the first 1 letters of s by 3, we have "dbc". After shifting the first 2 letters of s by 5, we have "igc". After shifting the first 3 letters of s by 9, we have "rpl", the answer. Example 2: Input: s = "aaa", shifts = [1,2,3] Output: "gfd" &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s consists of lowercase English letters. shifts.length == s.length 0 &lt;= shifts[i] &lt;= 109
class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: n = len(s) nums = [] sums = 0 for i in shifts[::-1]: sums = (sums+i)%26 nums.append(sums) nums = nums[::-1] res = '' for i, ch in enumerate(s): val = ord(s[i]) + nums[i] while val > 122: val -= 26 res += chr(val) return res
class Solution { public String shiftingLetters(String s, int[] shifts) { char[] arr = s.toCharArray(); int[] arr1 = new int[shifts.length]; arr1[arr1.length-1] = (shifts[shifts.length-1])%26; for(int i =shifts.length -2 ;i>=0 ;i--){ arr1[i] = (shifts[i] + arr1[i+1])%26; } for(int i =0; i<arr.length ; i++ ){ int c = (int)(arr[i]); int n = c+arr1[i]; if(n>122){ int m = arr1[i] -(122-c); n = m+96; } char ch = (char)n; arr[i] = ch; } String string = new String(arr); return string; } }
class Solution { void shift(string& s, int times, int amt) { const int clampL = 97; const int clampR = 123; for (int i = 0; i <= times; i++) { int op = (s[i] + amt) % clampR; if (op < clampL) op += clampL; s[i] = op; } } public: string shiftingLetters(string s, vector<int>& shifts) { for (int i = 0; i < shifts.size(); i++) shift(s,i,shifts[i]); return s; } };
// 848. Shifting Letters var shiftingLetters = function(s, shifts) { let res = '', i = shifts.length; shifts.push(0); while (--i >= 0) { shifts[i] += shifts[i+1]; res = String.fromCharCode((s.charCodeAt(i) - 97 + shifts[i]) % 26 + 97) + res; } return res; };
Shifting Letters
Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr. int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right]. A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive). &nbsp; Example 1: Input ["RangeFreqQuery", "query", "query"] [[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]] Output [null, 1, 2] Explanation RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]); rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4] rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 105 1 &lt;= arr[i], value &lt;= 104 0 &lt;= left &lt;= right &lt; arr.length At most 105 calls will be made to query
class RangeFreqQuery: def __init__(self, arr: List[int]): self.l = [[] for _ in range(10001)] for i, v in enumerate(arr): self.l[v].append(i) def query(self, left: int, right: int, v: int) -> int: return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)
class RangeFreqQuery { //Use map's key to store arr's value, map's value to keep <value's location, cummulative arr's value count> HashMap<Integer, TreeMap<Integer, Integer>> map; public RangeFreqQuery(int[] arr) { //O(nlog(n)) map = new HashMap<>(); for(int i = 0; i < arr.length; i++){ map.putIfAbsent(arr[i], new TreeMap<>()); TreeMap<Integer, Integer> tree = map.get(arr[i]); //i = value's location //tree.size() = cummulative arr's value count - 1 tree.put(i, tree.size()); } } public int query(int left, int right, int value) { //O(log(n)) //check if value exist in map if(!map.containsKey(value)){ return 0; } TreeMap<Integer, Integer> tree = map.get(value); //check if there exist position >= left and position <= right //if not, return 0 if(tree.ceilingKey(left) == null || tree.floorKey(right) == null){ return 0; } //get leftMost position's cummulative count int leftMost = tree.get(tree.ceilingKey(left)); //get rightMost position's cummulative count int rightMost = tree.get(tree.floorKey(right)); return rightMost - leftMost + 1; } } /** * Your RangeFreqQuery object will be instantiated and called as such: * RangeFreqQuery obj = new RangeFreqQuery(arr); * int param_1 = obj.query(left,right,value); */
class RangeFreqQuery { private: int size; unordered_map< int, vector<int> > mp; public: RangeFreqQuery(vector<int>& arr) { size=arr.size(); for (int i=0; i<size;i++){ mp[arr[i]].push_back(i); } } int query(int left, int right, int value) { int first = lower_bound(mp[value].begin(),mp[value].end(),left)- mp[value].begin(); int second = upper_bound(mp[value].begin(),mp[value].end(),right)- mp[value].begin(); return second-first; } };
var RangeFreqQuery = function(arr) { this.array = arr; this.subRangeSize = Math.sqrt(this.array.length) >> 0; this.subRangeFreqs = []; let freq = {}; for(let i = 0; i < arr.length; i++) { const num = arr[i]; if(i >= this.subRangeSize && i % this.subRangeSize === 0) { this.subRangeFreqs.push({...freq}); freq = {}; } freq[num] = (freq[num] || 0) + 1; } this.subRangeFreqs.push(freq); }; RangeFreqQuery.prototype.query = function(left, right, value) { let fr = 0; const leftIdx = left / this.subRangeSize >> 0, rightIdx = right / this.subRangeSize >> 0; for(let i = leftIdx; i <= rightIdx; i++) { fr += this.subRangeFreqs[i][value] || 0; } for(let i = leftIdx * this.subRangeSize; i < left; i++) { fr -= this.array[i] === value ? 1 : 0; } for(let i = right + 1; i < Math.min((rightIdx + 1) * this.subRangeSize, this.array.length); i++) { fr -= this.array[i] === value ? 1 : 0; } return fr; };
Range Frequency Queries
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. &nbsp; Example 1: Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -&gt; Right -&gt; Down -&gt; Down 2. Down -&gt; Down -&gt; Right -&gt; Right Example 2: Input: obstacleGrid = [[0,1],[0,0]] Output: 1 &nbsp; Constraints: m == obstacleGrid.length n == obstacleGrid[i].length 1 &lt;= m, n &lt;= 100 obstacleGrid[i][j] is 0 or 1.
class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: def valid(r,c,matrix): return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0]) dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))] dp[0][0] = 1 ^ obstacleGrid[0][0] for r in range(len(obstacleGrid)): for c in range(len(obstacleGrid[0])): if obstacleGrid[r][c] != 1: if valid(r-1, c, dp) and obstacleGrid[r-1][c] != 1: dp[r][c] += dp[r-1][c] if valid(r, c-1, dp) and obstacleGrid[r][c-1] != 1: dp[r][c] += dp[r][c-1] return dp[-1][-1]
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] path = new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ //if there is an obstacle at the current block then you cannot get there if(obstacleGrid[i][j]!=1){ if(i==0 && j==0) path[i][j] = 1; if(i>0) path[i][j] += path[i-1][j]; if(j>0) path[i][j] += path[i][j-1]; } } } return path[--m][--n]; } }
class Solution { public: int dp[101][101]; int paths(int i,int j,int &m, int &n,vector<vector<int>> &grid){ if(i>=m || j>=n) return 0; if(grid[i][j] == 1) return 0; if(i== m-1 && j== n-1) return 1; if(dp[i][j] != -1) return dp[i][j]; int v = paths(i,j+1,m,n,grid); int h = paths(i+1,j,m,n,grid); return dp[i][j] = v + h; } int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); memset(dp,-1,sizeof(dp)); return paths(0,0,m,n,obstacleGrid); } };
var uniquePathsWithObstacles = function(grid) { let m=grid.length, n=grid[0].length; const dp = [...Array(m+1)].map((e) => Array(n+1).fill(0)); dp[0][1]=1; for(let i=1;i<m+1;i++){ for(let j=1;j<n+1;j++){ dp[i][j]=grid[i-1][j-1]==1 ? 0:dp[i][j-1]+dp[i-1][j]; } } return dp[m][n]; };
Unique Paths II
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. &nbsp; Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", magazine = "ab" Output: false Example 3: Input: ransomNote = "aa", magazine = "aab" Output: true &nbsp; Constraints: 1 &lt;= ransomNote.length, magazine.length &lt;= 105 ransomNote and magazine consist of lowercase English letters.
from collections import Counter class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: ransomNote_count = dict(Counter(ransomNote)) magazine_count = dict(Counter(magazine)) for key , value in ransomNote_count.items(): if key in magazine_count: if value <= magazine_count[key]: continue else: return False return False return True
class Solution { public boolean canConstruct(String ransomNote, String magazine) { char[] rs = ransomNote.toCharArray(); char[] ms = magazine.toCharArray(); HashMap<Character, Integer> rm = new HashMap<>(); HashMap<Character, Integer> mz = new HashMap<>(); for (char c : rs) { if (rm.containsKey(c)) { rm.put(c, rm.get(c) + 1); } else { rm.put(c, 1); } } for (char c : ms) { if (mz.containsKey(c)) { mz.put(c, mz.get(c) + 1); } else { mz.put(c, 1); } } for (char c : rm.keySet()) { if (!mz.containsKey(c) || mz.get(c) < rm.get(c)) { return false; } } return true; } }
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int cnt[26] = {0}; for(char x: magazine) cnt[x-'a']++; for(char x: ransomNote) { if(cnt[x-'a'] == 0) return false; cnt[x-'a']--; } return true; } };
var canConstruct = function(ransomNote, magazine) { map = {}; for(let i of magazine){ map[i] = (map[i] || 0) + 1; } for(let i of ransomNote){ if(!map[i]){ return false } map[i]--; } return true };
Ransom Note
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise. &nbsp; Example 1: Input: words = ["abc","aabc","bc"] Output: true Explanation: Move the first 'a' in words[1] to the front of words[2], to make words[1] = "abc" and words[2] = "abc". All the strings are now equal to "abc", so return true. Example 2: Input: words = ["ab","a"] Output: false Explanation: It is impossible to make all the strings equal using the operation. &nbsp; Constraints: 1 &lt;= words.length &lt;= 100 1 &lt;= words[i].length &lt;= 100 words[i] consists of lowercase English letters.
class Solution: def makeEqual(self, words: List[str]) -> bool: map_ = {} for word in words: for i in word: if i not in map_: map_[i] = 1 else: map_[i] += 1 n = len(words) for k,v in map_.items(): if (v%n) != 0: return False return True
class Solution { public boolean makeEqual(String[] words) { HashMap<Character, Integer> map = new HashMap<>(); for(String str : words){ for(int i=0; i<str.length(); i++){ char ch = str.charAt(i); map.put(ch, map.getOrDefault(ch, 0) + 1); } } for(Character key : map.keySet()){ int freq = map.get(key); if(freq % words.length!=0){ return false; } } return true; } }
class Solution { public: bool makeEqual(vector<string>& words) { int mp[26] = {0}; for(auto &word: words){ for(auto &c: word){ mp[c - 'a']++; } } for(int i = 0;i<26;i++){ if(mp[i] % words.size() != 0) return false; } return true; } };
/** * @param {string[]} words * @return {boolean} */ var makeEqual = function(words) { let length = words.length let map = {} for( let word of words ) { for( let ch of word ) { map[ch] = ( map[ch] || 0 ) + 1 } } for( let key of Object.keys(map)) { if( map[key] % length !=0 ) return false } return true };
Redistribute Characters to Make All Strings Equal
You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951". Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345". Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'. &nbsp; Example 1: Input: s = "5525", a = 9, b = 2 Output: "2050" Explanation: We can apply the following operations: Start: "5525" Rotate: "2555" Add: "2454" Add: "2353" Rotate: "5323" Add: "5222" Add: "5121" Rotate: "2151" ​​​​​​​Add: "2050"​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050". Example 2: Input: s = "74", a = 5, b = 1 Output: "24" Explanation: We can apply the following operations: Start: "74" Rotate: "47" ​​​​​​​Add: "42" ​​​​​​​Rotate: "24"​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24". Example 3: Input: s = "0011", a = 4, b = 2 Output: "0011" Explanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011". &nbsp; Constraints: 2 &lt;= s.length &lt;= 100 s.length is even. s consists of digits from 0 to 9 only. 1 &lt;= a &lt;= 9 1 &lt;= b &lt;= s.length - 1
''' w: BFS h: for each possible number (node), we have two possible operations (add, rotate) it seems to be a 2^100 possible number, however, note: 1) add a to number of odd index, we will get to the same number after 10 rounds of add 2) s has even length, if b is odd, we can get the same number after n round 3) for each shift, we would get different number at even index in 10 rounds so we would have 10 * n * 10 number at most, then we can use BFS + memo ''' import collections class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: seen = set() deque = collections.deque([s]) while deque: #print(deque) curr = deque.popleft() seen.add(curr) #1.add ad = self.add_(curr, a) if ad not in seen: deque.append(ad) seen.add(ad) #2. rotate: ro = self.rotate_(curr, b) if ro not in seen: deque.append(ro) seen.add(ro) return min(seen) def add_(self,s,a): res = '' for idx, i in enumerate(s): if idx % 2 == 1: num = (int(i) + a) % 10 res += str(num) else: res += i return res def rotate_(self, s, b): idx = len(s)-b res = s[idx:] + s[0:idx] return res
class Solution { private String result; public String findLexSmallestString(String s, int a, int b) { result = "z"; HashSet<String> set = new HashSet<>(); dfs(s, a, b, set); return result; } private void dfs(String s, int a, int b, HashSet<String> set) { if(set.contains(s)) return; set.add(s); String s1, s2; s1 = addA(s, a); s2 = rotateB(s, b); dfs(s1, a , b, set); dfs(s2, a , b, set); } private String addA(String s, int a) { char c[] = s.toCharArray(); int i, temp; for(i=1;i<s.length();i+=2) { temp = c[i] - '0'; temp += a; temp = temp % 10; c[i] = (char)(temp + '0'); } s = new String(c); if(result.compareTo(s) > 0) result = s; return s; } private String rotateB(String s, int b) { if(b < 0) b += s.length(); b = b % s.length(); b = s.length() - b; s = s.substring(b) + s.substring(0, b); if(result.compareTo(s) > 0) result = s; return s; } }
class Solution { public: void dfs(string &s, string &small, int a, int b, unordered_map<string, string> &memo) { if (memo.count(s)) return; string res = s, str = res; memo[s] = res; rotate(str.begin(), str.begin() + b, str.end()); // rotate current string dfs(str, small, a, b, memo); if (memo[str] < res) res = memo[str]; for (int i = 0; i < 9; i++) { // or add it for (int j = 1; j < s.length(); j+=2) s[j] = '0' + ((s[j] - '0') + a) % 10; if (s < res) res = s; dfs(s, small, a, b, memo); } if (small > res) small = res; memo[s] = res; } string findLexSmallestString(string s, int a, int b) { unordered_map<string, string> memo; string res = s; dfs(s, res, a, b, memo); return res; } };
var findLexSmallestString = function(s, a, b) { const n = s.length; const visited = new Set(); const queue = []; visited.add(s); queue.push(s); let minNum = s; while (queue.length > 0) { const currNum = queue.shift(); if (currNum < minNum) minNum = currNum; const justRotate = rotate(currNum); const justAdd = add(currNum); if (!visited.has(justRotate)) { visited.add(justRotate); queue.push(justRotate); } if (!visited.has(justAdd)) { visited.add(justAdd); queue.push(justAdd); } } return minNum; function rotate(num) { let rotatedNum = ""; const start = n - b; for (let i = 0; i < b; i++) { rotatedNum += num.charAt(start + i); } const restDigs = num.substring(0, n - b); rotatedNum += restDigs; return rotatedNum; } function add(num) { let nextNum = ""; for (let i = 0; i < n; i++) { let currDig = num.charAt(i); if (i % 2 == 0) { nextNum += currDig; } else { let newDig = (parseInt(currDig) + a) % 10; nextNum += newDig; } } return nextNum; } };
Lexicographically Smallest String After Applying Operations
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 &lt;= i &lt; nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. &nbsp; Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. &nbsp; Constraints: 1 &lt;= nums1.length &lt;= nums2.length &lt;= 1000 0 &lt;= nums1[i], nums2[i] &lt;= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. &nbsp; Follow up: Could you find an O(nums1.length + nums2.length) solution?
class Solution: def nextGreaterElement(self, nums1, nums2): dic, stack = {}, [] for num in nums2[::-1]: while stack and num > stack[-1]: stack.pop() if stack: dic[num] = stack[-1] stack.append(num) return [dic.get(num, -1) for num in nums1]
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>(); Stack<Integer> stack = new Stack<>(); int[] ans = new int[nums1.length]; for(int i = 0; i < nums2.length; i++){ while(!stack.isEmpty() && nums2[i] > stack.peek()){ int temp = stack.pop(); map.put(temp, nums2[i]); } stack.push(nums2[i]); } for(int i = 0; i < nums1.length; i++){ ans[i] = map.getOrDefault(nums1[i], -1); } return ans; } }
class Solution { public: vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) { vector<int>vc; int len1=nums1.size(); int len2=nums2.size(); unordered_map<int,int>ump; int e,f; for(e=0;e<len2;e++) { for(f=e+1;f<len2;f++) { if(nums2[f]>nums2[e]) { ump[nums2[e]]=nums2[f]; break; } } if(f==len2) ump[nums2[e]]=-1; } unordered_map<int,int>::iterator it; for(int e=0;e<len1;e++) { it=ump.find(nums1[e]); if(it!=ump.end()) { vc.push_back(it->second); } } return vc; } };
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var nextGreaterElement = function(nums1, nums2) { // [Value, Index] of all numbers in nums2 const indexMap = new Map() for(let i = 0; i < nums2.length; i++){ indexMap.set(nums2[i], i) } // Stores the next greatest elements let result = [] // Iterate through all the numbers of interest. Remember that all numbers in nums1 are present in nums2. for(let num of nums1){ // Check to see those numbers were present in the nums2 indexMap if(indexMap.has(num)){ // If they were, we must find the next greatest element. // Set it to -1 by default in case we cannot find it. let nextGreatest = -1 // Iterate through all numbers in nums2 to the right of the index of the target number. (index of the target + 1) for(let i = indexMap.get(num) + 1; i < nums2.length; i++){ // Check to see if the current number is greater than the target. if(nums2[i] > num){ // If it is, this is the next greatest element. nextGreatest = nums2[i] // Break the loop. break; } } // Add the next greatest element (if found). Otherwise, add -1 (default) result.push(nextGreatest) } } // Return the array of next greatest elements. return result };
Next Greater Element I
Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. &nbsp; Example 1: Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4] Example 2: Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8] &nbsp; Constraints: The number of nodes in each tree is in the range [0, 5000]. -105 &lt;= Node.val &lt;= 105
# 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: l1,l2=[],[] def preorder(root,l): if root is None: return preorder(root.left,l) l.append(root.val) preorder(root.right,l) preorder(root1,l1) preorder(root2,l2) return sorted(l1+l2)
class Solution { public List<Integer> getAllElements(TreeNode root1, TreeNode root2) { Stack<TreeNode> st1 = new Stack<>(); Stack<TreeNode> st2 = new Stack<>(); List<Integer> res = new ArrayList<>(); while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){ while(root1 != null){ st1.push(root1); root1 = root1.left; } while(root2 != null){ st2.push(root2); root2 = root2.left; } if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){ root1 = st1.pop(); res.add(root1.val); root1 = root1.right; } else{ root2 = st2.pop(); res.add(root2.val); root2 = root2.right; } } return res; } }
class Solution { public: vector<int> v; void Temp(TreeNode* root) { if(root!=NULL){ Temp(root->left); v.push_back(root->val); Temp(root->right); } } vector<int> getAllElements(TreeNode* root1, TreeNode* root2) { Temp(root1); Temp(root2); sort(v.begin(), v.end()); return v; } };
var getAllElements = function(root1, root2) { const ans = []; const traverse = (r) => { if(!r) return; traverse(r.left); ans.push(r.val); traverse(r.right); } traverse(root1); traverse(root2); return ans.sort((a, b) => a - b); };
All Elements in Two Binary Search Trees
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); &nbsp; Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consists of English letters (lower-case and upper-case), ',' and '.'. 1 &lt;= numRows &lt;= 1000
class Solution: def convert(self, s: str, numRows: int) -> str: # safety check to not process single row if numRows == 1: return s # safety check to not process strings shorter/equal than numRows if len(s) <= numRows: return s # safety check to not process double rows if numRows == 2: # slice every other character return s[0::2] + s[1::2] # list that stores the lines # add lines with initial letters lines: list[str] = [letter for letter in s[:numRows]] # positive direction goes down # lines are created, so it's going up direction: int = -1 # track the position at which the letter will be added # position after bouncing off, after adding initial lines line_index: int = numRows - 2 # edge indexes # 0 can only be reached by going up # numRows only by going down edges: set[int] = {0, numRows} for letter in s[numRows:]: # add letter at tracked index position lines[line_index] += letter # prepare index before next loop iteration line_index += direction # reaching one of the edges if line_index in edges: # change direction direction = -direction # bounce off if bottom edge if line_index == numRows: line_index += direction * 2 return "".join(lines)
class Solution { public String convert(String s, int numRows) { if (numRows==1)return s; StringBuilder builder = new StringBuilder(); for (int i=1;i<=numRows;i++){ int ind = i-1; boolean up = true; while (ind < s.length()){ builder.append(s.charAt(ind)); if (i==1){ ind += 2*(numRows-i); } else if (i==numRows){ ind += 2*(i-1); } else { ind += up ? 2*(numRows-i) : 2*(i-1); up=!up; } } } return builder.toString(); } }
class Solution { public: string convert(string s, int numRows) { vector<vector<char>> v(numRows); int j=0,t=1; if(numRows ==1) return s; for(int i=0;i<s.size();i++) { v[j].push_back((char)s[i]); if(j==numRows-1 ) t=0; else if(j==0) t=1; if(t) j++; else j--; } string x=""; for(int i=0;i<numRows;i++) { for(int j=0;j<v[i].size();j++) x.push_back(v[i][j]); } return x; } };
var convert = function(s, numRows) { let result = []; let row = 0; let goingUp = false; for (let i = 0; i < s.length; i++) { result[row] = (result[row] || '') + s[i]; // append letter to active row if (goingUp) { row--; if (row === 0) goingUp = false; // reverse direction if goingUp and reaching top } else { row++; if (row === numRows - 1) goingUp = true; // reverse direction after reaching bottom } } return result.join(''); };
Zigzag Conversion
You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. &nbsp; Example 1: Input: nums = [5,-7,3,5], goal = 6 Output: 0 Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0. Example 2: Input: nums = [7,-9,15,-2], goal = -5 Output: 1 Explanation: Choose the subsequence [7,-9,-2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. Example 3: Input: nums = [1,2,3], goal = -7 Output: 7 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 40 -107 &lt;= nums[i] &lt;= 107 -109 &lt;= goal &lt;= 109
class Solution: def minAbsDifference(self, nums: List[int], goal: int) -> int: # When goal 0 we can just choose no elements if goal == 0: return 0 n = len(nums) mid = n // 2 # Split the list in 2 parts and then find all possible subset sums # T = O(2^n/2) to build all subset sums leftList = nums[:mid] leftSums = [] rightList = nums[mid:] rightSums = [] # T = O(2^n/2) to build all subset sums (we only consider half list) def buildSubsetSums(usedNums, numsToChooseFrom, ind, storeIn): if ind == len(numsToChooseFrom): # We also keep elements with sum 0 to deal with cases like this where we don't select nums # List: [1,2,3], Target: -7 (choosing no elements will give a sum close to goal) # We can also have cases where we want to take only 1 element from the list # so sum 0 for left and right list needs to be an option storeIn.append(sum(usedNums)) return usedNums.append(numsToChooseFrom[ind]) buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn) usedNums.pop() buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn) buildSubsetSums([], leftList, 0, leftSums) buildSubsetSums([], rightList, 0, rightSums) # 2^n/2 log(2^n/2) = n/2 * 2^n/2 time to sort rightSums.sort() diff = float('inf') # Loop runs 2^n/2 times and inside binary search tale n/2 time # So total time is n/2 * 2^n/2 for leftSum in leftSums: complement = goal - leftSum # Bisect left takes log(2^n/2) = n/2 search time idx = bisect.bisect_left(rightSums, complement) for i in [idx - 1, idx, idx + 1]: if 0 <= i < len(rightSums): finalSum = leftSum + rightSums[i] diff = min(diff, abs(goal - finalSum)) # Over all time complexity is - n/2 * 2^n/2 # 1. Making subset sums will take - 2^n/2 # 2. Sorting right list takes - 2^n/2 * n/2 # 3. Iterating one list and finding closest complement in other # takes n/2 * 2^n/2 # Space will be O(n/2) for the list and call stack for building subset return diff
class Solution { int[] arr; public int minAbsDifference(int[] nums, int goal) { arr = nums; int n = nums.length; List<Integer> first = new ArrayList<>(); List<Integer> second = new ArrayList<>(); generate(0,n/2,0, first); //generate all possible subset sums from half the array generate(n/2, n , 0, second);//generate all possible subset sums from the second half of the array Collections.sort(first); int ans = Integer.MAX_VALUE; for(int secondSetSum : second ) { int left = goal - secondSetSum; // How far off are we from the desired goal? if(first.get(0) > left) { // all subset sums from first half are too big => Choose the smallest ans = (int)(Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal))); continue; } if(first.get(first.size() - 1) < left) { // all subset sums from first half are too small => Choose the largest ans = (int)(Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal))); continue; } int pos = Collections.binarySearch(first, left); if(pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal return 0; else // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1) pos = -1 * (pos + 1); int low = pos - 1; ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(low) - goal)); // Checking for the floor value (largest sum < goal) ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(pos) - goal)); //Checking for the ceiling value (smallest sum > goal) } return ans; } /** * Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick */ void generate(int i, int end, int sum, List<Integer> listOfSubsetSums) { if (i == end) { listOfSubsetSums.add(sum); //add return; } generate(i + 1, end, sum + arr[i], set); generate(i + 1, end, sum, set); } }
class Solution { public: void find(vector<int>&v, int i, int e, int sum, vector<int>&sumv){ if(i==e){ sumv.push_back(sum); return; } find(v,i+1,e,sum+v[i],sumv); find(v,i+1,e,sum,sumv); } int minAbsDifference(vector<int>& nums, int goal) { int n=nums.size(); //Step 1: Divide nums into 2 subarrays of size n/2 and n-n/2 vector<int>A,B; for(int i=0;i<n/2;i++) A.push_back(nums[i]); for(int i=n/2;i<n;i++) B.push_back(nums[i]); //Step 2: Find all possible subset sums of A and B vector<int>sumA,sumB; find(A,0,A.size(),0,sumA); find(B,0,B.size(),0,sumB); sort(sumA.begin(),sumA.end()); sort(sumB.begin(),sumB.end()); //Step 3: Find combinations from sumA & sumB such that abs(sum-goal) is minimized int ans=INT_MAX; for(int i=0;i<sumA.size();i++){ int s=sumA[i]; int l=0; int r=sumB.size()-1; while(l<=r){ int mid=l+(r-l)/2; int sum=s+sumB[mid]; if(sum==goal) return 0; ans=min(ans,abs(sum-goal)); if(sum>goal){ r=mid-1; } else{ l=mid+1; } } } return ans; } };
var minAbsDifference = function(nums, goal) { let mid = Math.floor(nums.length / 2); let part1 = nums.slice(0, mid), part2 = nums.slice(mid); function findSubsetSums(arr, set, idx = 0, sum = 0) { if (idx === arr.length) return set.add(sum); findSubsetSums(arr, set, idx + 1, sum); findSubsetSums(arr, set, idx + 1, sum + arr[idx]); } let sum1 = new Set(), sum2 = new Set(); findSubsetSums(part1, sum1); findSubsetSums(part2, sum2); sum1 = [...sum1.values()]; sum2 = [...sum2.values()]; sum2.sort((a, b) => a - b); let min = Infinity; for (let num1 of sum1) { let l = 0, r = sum2.length - 1; while (l <= r) { let mid = l + Math.floor((r - l) / 2); let num2 = sum2[mid]; min = Math.min(min, Math.abs(num1 + num2 - goal)); if (num1 + num2 < goal) l = mid + 1; else r = mid - 1; } } return min; };
Closest Subsequence Sum
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. &nbsp; Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. &nbsp; Constraints: 1 &lt;= words.length &lt;= 1000 1 &lt;= words[i].length, chars.length &lt;= 100 words[i] and chars consist of lowercase English letters.
class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ b = set(chars) anwser = 0 for i in words: a = set(i) if a.issubset(b): test = [o for o in a if chars.count(o) < i.count(o)] if len(test) == 0: anwser += len(i) return anwser
class Solution { public int countCharacters(String[] words, String chars) { int[] freq = new int[26]; for (int i = 0; i < chars.length(); i++) { // char - char is a kind of clever way to get the position of // the character in the alphabet. 'a' - 'a' would give you 0. // 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on. freq[chars.charAt(i) - 'a'] ++; } int result = 0; for (String word : words) { int[] copy = Arrays.copyOf(freq, freq.length); boolean pass = true; for (int j = 0; j < word.length(); j++) { // decrement the frequency of this char in array for using // if there are less than 1 chance for using this character, invalid, // move to next word in words if (-- copy[word.charAt(j) - 'a'] < 0) { pass = false; break; } } if (pass) { result += word.length(); } } return result; } }
class Solution { public: int countCharacters(vector<string>& words, string chars) { vector<int> dp(26,0); vector<int> dp2(26,0); for(int i=0;i<chars.size();i++){ dp[chars[i]-'a']++; } dp2 = dp; bool flg = false; int cnt=0; for(int i=0;i<words.size();i++){ string a = words[i]; for(int j=0;j<a.size();j++){ if(dp[a[j]-'a']>0){ dp[a[j]-'a']--; } else{ flg = true; dp = dp2; break; } } if(!flg){ cnt += a.size(); } dp = dp2; flg = false; } return cnt; } };
var countCharacters = function(words, chars) { let arr = []; loop1: for(word of words){ let characters = chars; loop2: for( char of word ){ if(characters.indexOf(char) === -1){ continue loop1; } characters = characters.replace(char,''); } arr.push(word); } return arr.join('').length; };
Find Words That Can Be Formed by Characters
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. &nbsp; Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 -1000 &lt;= nums[i] &lt;= 1000 -107 &lt;= k &lt;= 107
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: ans=0 prefsum=0 d={0:1} for num in nums: prefsum = prefsum + num if prefsum-k in d: ans = ans + d[prefsum-k] if prefsum not in d: d[prefsum] = 1 else: d[prefsum] = d[prefsum]+1 return ans
/* */ class Solution { public int subarraySum(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); map.put(0,1); int count = 0; int sum = 0; for(int i=0; i<nums.length; i++){ sum += nums[i]; if(map.containsKey(sum - k)){ count += map.get(sum-k); } map.put(sum, map.getOrDefault(sum,0)+1); } return count; } }
/********************************* Solution Using HashMap / Prefix ********************/ class Solution { public: int subarraySum(vector<int>& nums, int k) { unordered_map<int, int> prefixSum {{0, 1}}; int sum = 0; int numOfSubArr = 0; int size = nums.size(); for (int index = 0; index < size; index++){ sum += nums[index]; if (prefixSum.find(sum-k) != prefixSum.end()) numOfSubArr += prefixSum[sum-k]; prefixSum[sum]++; } return numOfSubArr; } };
var subarraySum = function(nums, k) { const obj = {}; let res = 0; let sum = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (sum == k) res++; if (obj[sum - k]) res += obj[sum - k]; obj[sum] ? obj[sum] += 1 : obj[sum] = 1; } return res; };
Subarray Sum Equals K
You have k lists of sorted integers in non-decreasing&nbsp;order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a &lt; d - c or a &lt; c if b - a == d - c. &nbsp; Example 1: Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] Output: [20,24] Explanation: List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24]. Example 2: Input: nums = [[1,2,3],[1,2,3],[1,2,3]] Output: [1,1] &nbsp; Constraints: nums.length == k 1 &lt;= k &lt;= 3500 1 &lt;= nums[i].length &lt;= 50 -105 &lt;= nums[i][j] &lt;= 105 nums[i]&nbsp;is sorted in non-decreasing order.
from queue import PriorityQueue class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: q = PriorityQueue() maxi = -10**7 mini = 10**7 for i in range(len(nums)): maxi = max(maxi,nums[i][0]) mini = min(mini,nums[i][0]) q.put((nums[i][0],i,0)) s, e = mini, maxi while not q.empty() : mini, i, j = q.get() if maxi - mini < e-s: s,e = mini, maxi if j+1 < len(nums[i]): maxi = max(maxi,nums[i][j+1]) q.put((nums[i][j+1],i,j+1)) else: break return [s,e]
class Solution { class Pair implements Comparable<Pair> { int val; int li; int di; public Pair(int val, int li, int di) { this.val = val; this.li = li; this.di = di; } public int compareTo(Pair other) { return this.val - other.val; } } public int[] smallestRange(List<List<Integer>> nums) { PriorityQueue<Pair> pq = new PriorityQueue<>(); int max = Integer.MIN_VALUE; for(int i=0; i<nums.size(); i++) { pq.add(new Pair(nums.get(i).get(0), i, 0)); max = Math.max(max, nums.get(i).get(0)); } int rbeg = 0; int rend = 0; int rsize = Integer.MAX_VALUE; while(pq.size() == nums.size()) { Pair rem = pq.remove(); int crsize = max - rem.val; if(crsize < rsize) { rsize = crsize; rbeg = rem.val; rend = max; } if(rem.di < nums.get(rem.li).size() - 1) { pq.add(new Pair(nums.get(rem.li).get(rem.di + 1), rem.li, rem.di + 1)); max = Math.max(max, nums.get(rem.li).get(rem.di + 1)); } } return new int[]{rbeg, rend}; } }
#include <vector> #include <queue> #include <limits> using namespace std; struct Item { int val; int r; int c; Item(int val, int r, int c): val(val), r(r), c(c) { } }; struct Comp { bool operator() (const Item& it1, const Item& it2) { return it2.val < it1.val; } }; class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { priority_queue<Item, vector<Item>, Comp> pq; int high = numeric_limits<int>::min(); int n = nums.size(); for (int i = 0; i < n; ++i) { pq.push(Item(nums[i][0], i, 0)); high = max(high , nums[i][0]); } int low = pq.top().val; vector<int> res{low, high}; while (pq.size() == (size_t)n) { auto it = pq.top(); pq.pop(); if ((size_t)it.c + 1 < nums[it.r].size()) { pq.push(Item(nums[it.r][it.c + 1], it.r, it.c + 1)); high = max(high, nums[it.r][it.c + 1]); low = pq.top().val; if (high - low < res[1] - res[0]) { res[0] = low; res[1] = high; } } } return res; } };
var smallestRange = function(nums) { let minHeap = new MinPriorityQueue({ compare: (a,b) => a[0] - b[0] }); let start = 0, end = Infinity; let maxSoFar = -Infinity; for (let num of nums) { minHeap.enqueue([num[0], 0, num]); maxSoFar = Math.max(maxSoFar, num[0]); } while (minHeap.size() == nums.length) { let [num, i, list] = minHeap.dequeue(); if (end - start > maxSoFar - num) { start = num; end = maxSoFar; } if (list.length > i + 1) { minHeap.enqueue([list[i + 1], i + 1, list]); maxSoFar = Math.max(maxSoFar, list[i + 1]); } } return [start, end]; };
Smallest Range Covering Elements from K Lists
Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: s = "0110111" Output: 9 Explanation: There are 9 substring in total with only 1's characters. "1" -&gt; 5 times. "11" -&gt; 3 times. "111" -&gt; 1 time. Example 2: Input: s = "101" Output: 2 Explanation: Substring "1" is shown 2 times in s. Example 3: Input: s = "111111" Output: 21 Explanation: Each substring contains only 1's characters. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s[i] is either '0' or '1'.
class Solution(object): def numSub(self, s): res, currsum = 0,0 for digit in s: if digit == '0': currsum = 0 else: currsum += 1 res+=currsum return res % (10**9+7)
class Solution { public int numSub(String s) { char[] ch = s.toCharArray(); long count =0; long result =0; for(int i=0; i<ch.length; i++){ if(ch[i] == '1'){ count++; result += count; } else{ count = 0; } } return (int)(result%1000000007); } }
class Solution { /* To calculate the substring the formula is (n*n+1)/2 so just find the range and calculate the substrings. */ int mod=1e9+7; long calculateNumbeOfSubstrings(string &s,int &l,int &r){ long range=r-l; long ans=range*(range+1)/2; return ans; } public: int numSub(string s) { int ans=0; int len=s.size(); int r=0,l=0; while(r<len){ while(r<len && s[l]!='1'){ l++; r++; } while(r<len && s[r]!='0'){ r++; } ans=(ans+calculateNumbeOfSubstrings(s,l,r))%mod; l=r; } return ans; } };
var numSub = function(s) { const mod = Math.pow(10, 9)+7; let r = 0, tot = 0; while (r<s.length) { if (s[r]==='1') { let tmp = r; while (tmp < s.length && s[tmp] === '1') { tot += tmp - r + 1; tot%=mod; tmp++; } r = tmp; } r++; } return tot; };
Number of Substrings With Only 1s
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. &nbsp; Example 1: Input: s = "hello" Output: "holle" Example 2: Input: s = "leetcode" Output: "leotcede" &nbsp; Constraints: 1 &lt;= s.length &lt;= 3 * 105 s consist of printable ASCII characters.
class Solution: def reverseVowels(self, s: str) -> str: s=list(s) vow=[] for i,val in enumerate(s): if val in ('a','e','i','o','u','A','E','I','O','U'): vow.append(val) s[i]='_' vow=vow[::-1] c=0 print(vow) for i,val in enumerate(s): if val =='_': s[i]=vow[c] c+=1 return "".join(s)
class Solution { public String reverseVowels(String s) { Set<Character> set = new HashSet<>(); set.add('a'); set.add('e'); set.add('i'); set.add('o'); set.add('u'); set.add('A'); set.add('E'); set.add('I'); set.add('O'); set.add('U'); StringBuilder str = new StringBuilder(s); int left = 0, right = str.length() - 1; while (left < right) { if (!set.contains(str.charAt(left))) { left++; } if (!set.contains(str.charAt(right))) { right--; } if (set.contains(str.charAt(left)) && set.contains(s.charAt(right))) { char temp = str.charAt(left); str.setCharAt(left++, str.charAt(right)); str.setCharAt(right--, temp); } } return str.toString(); } }
class Solution { public: bool isVowel(char s) { if(s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u' or s == 'A' or s == 'E' or s == 'I' or s == 'O' or s == 'U') return true; return false; } string reverseVowels(string s) { if(s.size() == 0) return ""; int left = 0, right = s.size() - 1; while(left < right) { if(isVowel(s[left]) and isVowel(s[right])) { swap(s[left], s[right]); left++; right--; } else if(isVowel(s[left])) right--; else if(isVowel(s[right])) left++; else { left++; right--; } } return s; } };
var reverseVowels = function(s) { const VOWELS = { 'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1 }; const arr = s.split(''); let i = 0, j = arr.length - 1; while (i < j) { if (VOWELS[arr[i]] && VOWELS[arr[j]]) { [arr[i], arr[j]] = [arr[j], arr[i]]; i++; j--; } else if (VOWELS[arr[i]]) { j--; } else { i++; } } return arr.join(''); };
Reverse Vowels of a String
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. &nbsp; Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a" Output: 0 Example 3: Input: s = "ab" Output: 1 &nbsp; Constraints: 1 &lt;= s.length &lt;= 2000 s consists of lowercase English letters only.
class Solution: def isPallindrom(self, s: str, l, r) -> bool: st = s[l: r+1] rev = st[::-1] return st == rev def minCut(self, s: str) -> int: N = len(s) if not s: return 0 if self.isPallindrom(s, 0, N-1): return 0 dp = [sys.maxsize] * (N+1) dp[-1] = 0 for i in range(N-1, -1, -1): for j in range(i, N): if self.isPallindrom(s, i, j): dp[i] = min(dp[i], 1 + dp[j+1]) return dp[0]-1
class Solution { int dp[]; public boolean pali(int i,int j,String s){ // int j=s.length()-1,i=0; while(i<=j){ if(s.charAt(i)!=s.charAt(j))return false; i++;j--; } return true; } public int cut(String s,int i,int n,int dp[]){ if(i==n)return 0; if(dp[i]!=-1)return dp[i]; int min=Integer.MAX_VALUE; for(int j=i;j<n;j++){ if(pali(i,j,s)){ int cost=1+cut(s,j+1,n,dp); min=Math.min(min,cost); } } return dp[i]=min; public int minCut(String s) { int n=s.length(); dp=new int[n]; Arrays.fill(dp,-1); return cut(s,0,n,dp)-1; }
class Solution { public: // function to precompute if every substring of s is a palindrome or not vector<vector<bool>> isPalindrome(string& s){ int n = s.size(); vector<vector<bool>> dp(n, vector<bool>(n, false)); for(int i=0; i<n; i++){ dp[i][i] = true; } for(int i=0; i<n-1; i++){ if(s[i] == s[i+1]){ dp[i][i+1] = true; } } int k = 2; while(k < n){ int i=0; int j=k; while(j<n){ if(s[i] == s[j] and dp[i+1][j-1]){ dp[i][j] = true; } i++; j++; } k++; } return dp; } // function to find the minimum palindromic substrings in s int solve(string& s, int n, int i, vector<vector<bool>>& palin, vector<int>& memo){ if(i==n){ return 0; } if(memo[i] != -1){ return memo[i]; } int result = INT_MAX; for(int j=i+1; j<=n; j++){ if(palin[i][j-1]){ result = min(result, 1+solve(s, n, j, palin, memo)); } } return memo[i] = result; } int minCut(string s) { int n = s.size(); vector<int> memo(n, -1); vector<vector<bool>> palin = isPalindrome(s); return solve(s, n, 0, palin, memo)-1; } };
var minCut = function(s) { function isPal(l, r) { while (l < r) { if (s[l] === s[r]) l++, r--; else return false; } return true; } let map = new Map(); function dfs(idx = 0) { if (idx === s.length) return 0; if (map.has(idx)) return map.get(idx); let min = Infinity; for (let i = idx; i < s.length; i++) { if (isPal(idx, i)) min = Math.min(min, 1 + dfs(i + 1)); } map.set(idx, min); return min; } return dfs() - 1; };
Palindrome Partitioning II
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123&nbsp; 34 8&nbsp; 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34". Return the number of different integers after performing the replacement operations on word. Two integers are considered different if their decimal representations without any leading zeros are different. &nbsp; Example 1: Input: word = "a123bc34d8ef34" Output: 3 Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once. Example 2: Input: word = "leet1234code234" Output: 2 Example 3: Input: word = "a1b01c001" Output: 1 Explanation: The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values. &nbsp; Constraints: 1 &lt;= word.length &lt;= 1000 word consists of digits and lowercase English letters.
class Solution: def numDifferentIntegers(self, word: str) -> int: word = re.findall('(\d+)', word) numbers = [int(i) for i in word] return len(set(numbers))
class Solution { public int numDifferentIntegers(String word) { String[] arr = word.replaceAll("[a-zA-Z]", " ").split("\\s+"); Set<String> set = new HashSet<String>(); for (String str : arr) { if (!str.isEmpty()) set.add(String.valueOf(str.replaceAll("^0*",""))); } return set.size(); } }
class Solution { public: int numDifferentIntegers(string word) { unordered_map<string, int> hmap; for (int i = 0; i < word.size(); i++) { if (isdigit(word[i])) { string str; while (word[i] == '0') i++; while (isdigit(word[i])) str += word[i++]; hmap[str]++; } } return hmap.size(); } };
const CC0 = '0'.charCodeAt(0); var numDifferentIntegers = function(word) { const numStrSet = new Set(); // get numbers as strings const numStrs = word.split(/[^0-9]+/); // drop leading zeros for (const numStr of numStrs) { if (numStr.length > 0) { let i = 0; while (numStr.charCodeAt(i) === CC0) i++; // make sure that we preserve last 0 if string is composed of zeros only numStrSet.add(numStr.slice(i) || '0'); } } return numStrSet.size; };
Number of Different Integers in a String
Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: MyHashMap() initializes the object with an empty map. void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. void remove(key) removes the key and its corresponding value if the map contains the mapping for the key. &nbsp; Example 1: Input ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] Output [null, null, null, 1, -1, null, 1, null, -1] Explanation MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now [[1,1]] myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] &nbsp; Constraints: 0 &lt;= key, value &lt;= 106 At most 104 calls will be made to put, get, and remove.
class MyHashMap: def __init__(self): self.data = [None] * 1000001 def put(self, key: int, val: int) -> None: self.data[key] = val def get(self, key: int) -> int: val = self.data[key] return val if val != None else -1 def remove(self, key: int) -> None: self.data[key] = None
class MyHashMap { /** Initialize your data structure here. */ LinkedList<Entry>[] map; public static int SIZE = 769; public MyHashMap() { map = new LinkedList[SIZE]; } /** value will always be non-negative. */ public void put(int key, int value) { int bucket = key % SIZE; if(map[bucket] == null) { map[bucket] = new LinkedList<Entry>(); map[bucket].add(new Entry(key, value)); } else { for(Entry entry : map[bucket]){ if(entry.key == key){ entry.val = value; return; } } map[bucket].add(new Entry(key, value)); } } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ public int get(int key) { int bucket = key % SIZE; LinkedList<Entry> entries = map[bucket]; if(entries == null) return -1; for(Entry entry : entries) { if(entry.key == key) return entry.val; } return -1; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ public void remove(int key) { int bucket = key % SIZE; Entry toRemove = null; if(map[bucket] == null) return; else { for(Entry entry : map[bucket]){ if(entry.key == key) { toRemove = entry; } } if(toRemove == null) return; map[bucket].remove(toRemove); } } } class Entry { public int key; public int val; public Entry(int key, int val){ this.key = key; this.val = val; } }
class MyHashMap { vector<vector<pair<int, int>>> map; const int size = 10000; public: /** Initialize your data structure here. */ MyHashMap() { map.resize(size); } /** value will always be non-negative. */ void put(int key, int value) { int index = key % size; vector<pair<int, int>> &row = map[index]; for(auto iter = row.begin(); iter != row.end(); iter++) { if(iter->first == key) { iter->second = value; return; } } row.push_back(make_pair(key, value)); } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ int get(int key) { int index = key % size; vector<pair<int, int>> &row = map[index]; for (auto iter = row.begin(); iter != row.end(); iter++) { if (iter->first == key) { return iter->second; } } return -1; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { int index = key % size; vector<pair<int, int>> &row = map[index]; for (auto iter = row.begin(); iter != row.end(); iter++) { if (iter->first == key) { row.erase(iter); return; } } } }; /** * Your MyHashMap object will be instantiated and called as such: * MyHashMap* obj = new MyHashMap(); * obj->put(key,value); * int param_2 = obj->get(key); * obj->remove(key); */
var MyHashMap = function() { this.hashMap = []; }; /** * @param {number} key * @param {number} value * @return {void} */ MyHashMap.prototype.put = function(key, value) { this.hashMap[key] = [key, value]; }; /** * @param {number} key * @return {number} */ MyHashMap.prototype.get = function(key) { return this.hashMap[key] ? this.hashMap[key][1] : -1; }; /** * @param {number} key * @return {void} */ MyHashMap.prototype.remove = function(key) { delete this.hashMap[key]; }; /** * Your MyHashMap object will be instantiated and called as such: * var obj = new MyHashMap() * obj.put(key,value) * var param_2 = obj.get(key) * obj.remove(key) */
Design HashMap
Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: arr = [1,4,2,5,3] Output: 58 Explanation: The odd-length subarrays of arr and their sums are: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4,2] = 7 [4,2,5] = 11 [2,5,3] = 10 [1,4,2,5,3] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 Example 2: Input: arr = [1,2] Output: 3 Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. Example 3: Input: arr = [10,11,12] Output: 66 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 100 1 &lt;= arr[i] &lt;= 1000 &nbsp; Follow up: Could you solve this problem in O(n) time complexity?
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: n = len(arr) ans = 0 for i in range(n): total = (i+1) * (n-1-i+1) ans = ans + (total//2 + total%2) * arr[i] return ans
class Solution { public int sumOddLengthSubarrays(int[] arr) { // Using two loops in this question... int sum = 0; for(int i=0 ; i<arr.length ; i++){ int prevSum = 0; for(int j=i ; j<arr.length ; j++){ prevSum+=arr[j]; if((j-i+1)%2==1){ sum+=prevSum; } } } // Time Complexity : O(n-square) // Space Complexity : O(1) return sum; } }
class Solution { public: int sumOddLengthSubarrays(vector<int>& arr) { int sum=0; int sum1=0; for(int i=0;i<arr.size();i++) { int count=0; sum+=arr[i]; for(int j=i;j<arr.size();j++) { sum1+=arr[j]; count++; if(count%2!=0 and count!=1) sum+=sum1; } sum1=0; } return sum; } };
/* Suppose N is the length of given array. Number of subarrays including element arr[i] is i * (N-i) + (N-i) because there are N-i subarrays with arr[i] as first element and i * (N-i) subarrays with arr[i] as a not-first element. arr[i] appears in (N-i) subarrays for each preceding element and therefore we have i*(N-i). Suppose i * (N-i) + (N-i) is `total`. Ceil(total / 2) is the number of odd-length subarrays and Floor(total / 2) is the number of even-length subarrays. When total is odd, there is one more odd-length subarray because of a single-element subarray. For each number, we multiply its value with the total number of subarrays it appears and add it to a sum. */ var sumOddLengthSubarrays = function(arr) { let sum = 0, N = arr.length; for (let i = 0; i < arr.length; i++) { let total = i * (N-i) + (N-i); sum += Math.ceil(total / 2) * arr[i]; } return sum; // T.C: O(N) // S.C: O(1) };
Sum of All Odd Length Subarrays
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: Replace keyi and the bracket pair with the key's corresponding valuei. If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks). Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs. &nbsp; Example 1: Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] Output: "bobistwoyearsold" Explanation: The key "name" has a value of "bob", so replace "(name)" with "bob". The key "age" has a value of "two", so replace "(age)" with "two". Example 2: Input: s = "hi(name)", knowledge = [["a","b"]] Output: "hi?" Explanation: As you do not know the value of the key "name", replace "(name)" with "?". Example 3: Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] Output: "yesyesyesaaa" Explanation: The same key can appear multiple times. The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". Notice that the "a"s not in a bracket pair are not evaluated. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 0 &lt;= knowledge.length &lt;= 105 knowledge[i].length == 2 1 &lt;= keyi.length, valuei.length &lt;= 10 s consists of lowercase English letters and round brackets '(' and ')'. Every open bracket '(' in s will have a corresponding close bracket ')'. The key in each bracket pair of s will be non-empty. There will not be any nested bracket pairs in s. keyi and valuei consist of lowercase English letters. Each keyi in knowledge is unique.
class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: knowledge = dict(knowledge) answer, start = [], None for i, char in enumerate(s): if char == '(': start = i + 1 elif char == ')': answer.append(knowledge.get(s[start:i], '?')) start = None elif start is None: answer.append(char) return ''.join(answer)
class Solution { public String evaluate(String s, List<List<String>> knowledge) { Map<String, String> map = new HashMap<>(); for(List<String> ele : knowledge) { map.put(ele.get(0), ele.get(1)); } StringBuilder sb = new StringBuilder(); int b_start = -1; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(') { b_start = i; } else if(s.charAt(i) == ')') { String key = s.substring(b_start + 1, i); sb.append(map.getOrDefault(key, "?")); b_start = -1; } else { if(b_start == -1) { sb.append(s.charAt(i)); } } } return sb.toString(); } }
class Solution { public: string evaluate(string s, vector<vector<string>>& knowledge) { string ans; // resultant string int n = s.size(); if(n < 2) return s; // because () will come in pair so, size should be more than 2 int sz = knowledge.size(); for(int i=0; i<sz; ++i){ mp.insert({knowledge[i][0], knowledge[i][1]}); // Inserting {key, value} pair } for(int i=0; i<n; i++){ if(s[i] == '('){ string key; i++; while(s[i] != ')'){ // getting key till we get ')' key += s[i++]; } string value; if(mp.find(key) != mp.end()){ // If {key, value} pair is present then replace (key) by it's value value = mp[key]; ans += value; } else {// otherwise replace (key) by ? ans += "?"; } } else ans += s[i]; } return ans; } }; **Please do upvote**
var evaluate = function(s, knowledge) { // key => value hash map can be directly constructed using the Map constructor const map = new Map(knowledge); // since bracket pairs can't be nested we can use a RegExp to capture keys and replace using a map constructed in the line above return s.replace(/\(([a-z]+)\)/g, (_, p1) => map.get(p1) ?? "?"); };
Evaluate the Bracket Pairs of a String
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. &nbsp; Example 1: Input: n = 2, batteries = [3,3,3] Output: 4 Explanation: Initially, insert battery 0 into the first computer and battery 1 into the second computer. After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute. At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead. By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running. We can run the two computers simultaneously for at most 4 minutes, so we return 4. Example 2: Input: n = 2, batteries = [1,1,1,1] Output: 2 Explanation: Initially, insert battery 0 into the first computer and battery 2 into the second computer. After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running. We can run the two computers simultaneously for at most 2 minutes, so we return 2. &nbsp; Constraints: 1 &lt;= n &lt;= batteries.length &lt;= 105 1 &lt;= batteries[i] &lt;= 109
class Solution: def maxRunTime(self, n: int, batteries: List[int]) -> int: batteries.sort() total=sum(batteries) while batteries[-1]>total//n: n-=1 total-=batteries.pop() return total//n
class Solution { private boolean canFit(int n, long k, int[] batteries) { long currBatSum = 0; long target = n * k; for (int bat : batteries) { if (bat < k) { currBatSum += bat; } else { currBatSum += k; } if (currBatSum >= target) { return true; } } return currBatSum >= target; } public long maxRunTime(int n, int[] batteries) { long batSum = 0; for (int bat : batteries) { batSum += bat; } long lower = 0; long upper = batSum / n; long res = -1; // binary search while (lower <= upper) { long mid = lower + (upper - lower) / 2; if (canFit(n, mid, batteries)) { res = mid; lower = mid + 1; } else { upper = mid - 1; } } return res; } }
class Solution { public: bool canFit(int n,long timeSpan,vector<int>batteries) { long currBatSum=0; long targetBatSum=n*timeSpan; for(auto it:batteries) { if(it<timeSpan) currBatSum+=it; else currBatSum+=timeSpan; if(currBatSum>=targetBatSum) return true; } return false; } long long maxRunTime(int n, vector<int>& batteries) { long totalSum=0; long low=*min_element(batteries.begin(),batteries.end()); for(auto it:batteries) { totalSum+=it; } long high = totalSum/n; long ans=-1; while(low<=high) { long mid = low+(high-low)/2; if(canFit(n,mid,batteries)) { ans=mid; low=mid+1; } else { high=mid-1; } } return ans; }
var maxRunTime = function(n, batteries) { let total = batteries.reduce((acc,x)=>acc+x,0) let batts = batteries.sort((a,b)=>b-a) let i = 0 while(1){ let average_truncated = parseInt(total / n) let cur = batts[i] if(cur > average_truncated){ total -= cur // remove all of that batteries charge from the equation n -- // remove the computer from the equation i++ } else { return average_truncated } } };
Maximum Running Time of N Computers
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 &lt;= i &lt;= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautiful arrangements that you can construct. &nbsp; Example 1: Input: n = 2 Output: 2 Explanation: The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 Example 2: Input: n = 1 Output: 1 &nbsp; Constraints: 1 &lt;= n &lt;= 15
class Solution: def countArrangement(self, n: int) -> int: self.count = 0 self.backtrack(n, 1, []) return self.count def backtrack(self, N, idx, temp): if len(temp) == N: self.count += 1 return for i in range(1, N+1): if i not in temp and (i % idx == 0 or idx % i == 0): temp.append(i) self.backtrack(N, idx+1, temp) temp.pop()
class Solution { int N; Integer[][] memo; public int countArrangement(int n) { this.N = n; memo = new Integer[n+1][1<<N]; return permute(1, 0); } private int permute(int index, int mask) { if (mask == (1<<N)-1) return 1; if (memo[index][mask] != null) return memo[index][mask]; int res = 0; for (int i = 1; i <= N; i++) { if ((mask & (1<<(i-1))) == 0 && (index % i == 0 || i % index == 0)) { mask |= (1<<(i-1)); res += permute(index+1, mask); mask ^= (1<<(i-1)); } } return memo[index][mask]=res; } }
class Solution { public: int ans = 0; bool isBeautiful(vector<int> &v) { int i = v.size() - 1; if (v[i] % (i + 1) == 0 || (i + 1) % v[i] == 0) return true; return false; } void solve(int n, vector<int> &p, vector<bool> &seen) { if (p.size() == n) { ans++; return; } for (int i = 1; i <= n; i++) { if (seen[i]) continue; p.push_back(i); if (isBeautiful(p)) { seen[i] = true; solve(n, p, seen); seen[i] = false; } p.pop_back(); } } int countArrangement(int n) { vector<int> p; vector<bool> seen(n + 1, false); solve(n, p, seen); return ans; } };
var countArrangement = function(n) { let result = 0; const visited = Array(n + 1).fill(false); const dfs = (next = n) => { if (next === 0) { result += 1; return; } for (let index = 1; index <= n; index++) { if (visited[index] || index % next && next % index) continue; visited[index] = true; dfs(next - 1); visited[index] = false; } }; dfs(); return result; };
Beautiful Arrangement
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. Return true if you can get such expression that evaluates to 24, and false otherwise. &nbsp; Example 1: Input: cards = [4,1,8,7] Output: true Explanation: (8-4) * (7-1) = 24 Example 2: Input: cards = [1,2,1,2] Output: false &nbsp; Constraints: cards.length == 4 1 &lt;= cards[i] &lt;= 9
class Solution: def judgePoint24(self, cards: List[int]) -> bool: return self.allComputeWays(cards, 4, 24) def allComputeWays(self, nums, l, target): if l == 1: if abs(nums[0] - target) <= 1e-6: return True return False for first in range(l): for second in range(first + 1, l): tmp1, tmp2 = nums[first], nums[second] nums[second] = nums[l - 1] nums[first] = tmp1 + tmp2 if self.allComputeWays(nums, l - 1, target): return True nums[first] = tmp1 - tmp2 if self.allComputeWays(nums, l - 1, target): return True nums[first] = tmp2 - tmp1 if self.allComputeWays(nums, l - 1, target): return True nums[first] = tmp1 * tmp2 if self.allComputeWays(nums, l - 1, target): return True if tmp2: nums[first] = tmp1 / tmp2 if self.allComputeWays(nums, l - 1, target): return True if tmp1: nums[first] = tmp2 / tmp1 if self.allComputeWays(nums, l - 1, target): return True nums[first], nums[second] = tmp1, tmp2 return False
// 0 ms. 100% class Solution { private static final double EPS = 1e-6; private boolean backtrack(double[] A, int n) { if(n == 1) return Math.abs(A[0] - 24) < EPS; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { double a = A[i], b = A[j]; A[j] = A[n-1]; A[i] = a + b; if(backtrack(A, n - 1)) return true; A[i] = a - b; if(backtrack(A, n - 1)) return true; A[i] = b - a; if(backtrack(A, n - 1)) return true; A[i] = a * b; if(backtrack(A, n - 1)) return true; if(Math.abs(b) > EPS) { A[i] = a / b; if(backtrack(A, n - 1)) return true; } if(Math.abs(a) > EPS) { A[i] = b / a; if(backtrack(A, n - 1)) return true; } A[i] = a; A[j] = b; } } return false; } public boolean judgePoint24(int[] nums) { double[] A = new double[nums.length]; for(int i = 0; i < nums.length; i++) A[i] = nums[i]; return backtrack(A, A.length); } }
class Solution { public: double cor=0.001; void dfs(vector<double> &cards,bool &res){ if(res==true) return; if(cards.size()==1){ if(abs(cards[0]-24)<cor) res=true; return; } for(int i=0;i<cards.size();i++){ for(int j=0;j<i;j++){ double p=cards[i],q=cards[j]; vector<double> t{p+q,q-p,p-q,p*q}; if(p>cor) t.push_back(q/p); if(q>cor) t.push_back(p/q); cards.erase(cards.begin()+i); cards.erase(cards.begin()+j); for(double d:t){ cards.push_back(d); dfs(cards,res); cards.pop_back(); } cards.insert(cards.begin()+j,q); cards.insert(cards.begin()+i,p); } } } bool judgePoint24(vector<int>& cards) { bool res=false; vector<double> card (cards.begin(),cards.end()); dfs(card,res); return res; } };
/** * @param {number[]} cards * @return {boolean} 1487 7-1 8-4 */ var judgePoint24 = function(cards) { let minV = 0.00000001; let numL = []; cards.forEach(card=>numL.push(card)); function judge(nums){ if(nums.length === 1) return Math.abs(nums[0]-24)<=minV; else{ for(let i = 0 ;i<nums.length;i++){ for(let j = 0 ;j<i;j++){ let a = nums[i] ,b = nums[j]; let val =[a + b, a - b, b - a, a * b, a / b, b / a]; let copy =[...nums]; copy.splice(i,1); copy.splice(j,1); for(let v of val){ copy.push(v); if (judge(copy)) { return true; } copy.pop(); } } } return false; } } return judge(numL); };
24 Game
A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid. &nbsp; Example 1: Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]] Output: 3 Explanation: The largest magic square has a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 12. - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums: 5+4+3 = 6+4+2 = 12 Example 2: Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]] Output: 2 &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 50 1 &lt;= grid[i][j] &lt;= 106
class Solution: def largestMagicSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # dimensions rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row cols = [[0]*n for _ in range(m+1)] # prefix sum along column for i in range(m): for j in range(n): rows[i][j+1] = grid[i][j] + rows[i][j] cols[i+1][j] = grid[i][j] + cols[i][j] ans = 1 for i in range(m): for j in range(n): diag = grid[i][j] for k in range(min(i, j)): ii, jj = i-k-1, j-k-1 diag += grid[ii][jj] ss = {diag} for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj]) for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c]) ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal if len(ss) == 1: ans = max(ans, k+2) return ans
class Solution { public int largestMagicSquare(int[][] grid) { int m = grid.length; int n = grid[0].length; // every row prefix sum int[][] rowPrefix = new int[m][n]; for (int i = 0; i < m; i++) { rowPrefix[i][0] = grid[i][0]; for (int j = 1; j < n; j++) { rowPrefix[i][j] = rowPrefix[i][j - 1] + grid[i][j]; } } // every column prefix sum int[][] columnPrefix = new int[m][n]; for (int i = 0; i < n; i++) { columnPrefix[0][i] = grid[0][i]; for (int j = 1; j < m; j++) { columnPrefix[j][i] = columnPrefix[j - 1][i] + grid[j][i]; } } int result = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // length of square int l = Math.min(m - i, n - j); // only check square's length is better than previous result for (int k = l; k > result; k--) { if (magic(i, j, k, grid, rowPrefix, columnPrefix)) { result = k; break; } } } } return result; } private boolean magic( int i, int j, int l, int[][] grid, int[][] rowPrefix, int[][] columnPrefix) { // check every row int target = rowPrefix[i][j + l - 1] - rowPrefix[i][j] + grid[i][j]; for (int k = 0; k < l; k++) { if (rowPrefix[i + k][j + l - 1] - rowPrefix[i + k][j] + grid[i + k][j] != target) { return false; } } // check every column for (int k = 0; k < l; k++) { if (columnPrefix[i + l - 1][j + k] - columnPrefix[i][j + k] + grid[i][j + k] != target) { return false; } } // check both diagonal int diagonal = 0; // \ // \ for (int k = 0; k < l; k++) { diagonal += grid[i + k][j + k]; } if (diagonal != target) { return false; } // / // / for (int k = 0; k < l; k++) { diagonal -= grid[i + l - 1 - k][j + k]; } return diagonal == 0; } }
class Solution { public: bool isValid(int r1, int r2, int c1, int c2, vector<vector<int>>& grid, vector<vector<int>>& rg, vector<vector<int>>& cg,int checkSum){ //Checking all row sums between top and bottom row for(int i = r1 + 1; i<r2; i++){ int sum = rg[i][c2]; if(c1>0)sum-=rg[i][c1-1]; if(sum!=checkSum)return false; } //Checking all columns between left and right column for(int j = c1 + 1; j<c2; j++){ int sum = cg[r2][j]; if(r1>0)sum-=cg[r1-1][j]; if(sum!=checkSum)return false; } int sum = 0; //right diagonal for(int i = r1, j = c1; i<=r2&&j<=c2; i++, j++){ sum+=grid[i][j]; } if(sum!=checkSum)return false; sum = 0; //left diagonal for(int i = r1, j = c2; i<=r2&&j>=c1; i++, j--){ sum+=grid[i][j]; } if(sum!=checkSum)return false; return true; } int largestMagicSquare(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>>rg, cg; rg = grid; cg = grid; //Generating row prefix sum matrix for(int i = 0; i<m; i++){ for(int j = 1; j<n; j++){ rg[i][j] += rg[i][j-1]; } } //Generating column prefix sum matrix for(int j = 0; j<n; j++){ for(int i = 1; i<m; i++){ cg[i][j] += cg[i-1][j]; } } int ans = 1; //For each cell in the loop, we find the larget magic square with cell {i,j} at the top left corner. for(int i = 0; i<m; i++){ for(int j = 0; j<n; j++){ if(m-i<=ans)return ans;//The largest square with it's top row as i will have at max a dimension = m-i, and in case are answer is already >= this dimension, we can simply return our answer //Pruning step --> //We only need to consider squares whose sizes our greater than our current answer, so we prune our search by starting from squares having side-lengths greater than ans. int r = i + ans; int c = j + ans; while(r<m&&c<n){ //For a square having it's 4 corners defined by {i,j,r,c}, we calculate the sum of all these 4 sides, and call our isValid function in case these sums are equal int rsum1 = j>0 ? rg[i][c] - rg[i][j-1] : rg[i][c];//top row sum int csum1 = i>0 ? cg[r][j] - cg[i-1][j] : cg[r][j];//left column sum int rsum2 = j>0 ? rg[r][c] - rg[r][j-1] : rg[r][c];//bottom row sum int csum2 = i>0 ? cg[r][c] - cg[i-1][c] : cg[r][c];//right column sum if(rsum1==csum2&&rsum2==csum2&&isValid(i,r,j,c,grid, rg, cg, rsum1)){ ans = max(ans, r-i+1); } r++; c++; } } } return ans; } };
var largestMagicSquare = function(grid) { const row = grid.length; const col = grid[0].length; const startSize = row <= col ? row : col; for(let s = startSize; s > 1; s--){ for(let r = 0; r < grid.length - s + 1; r++){ for(let c = 0; c < grid[0].length - s + 1; c++){ if(isMagic(grid, r, c, s)){ return s; } } } } return 1; }; const isMagic = (grid, i, j, size) => { let targetSum = 0; for(let c = j; c < j + size; c++){ targetSum += grid[i][c]; } //check rows for(let r = i; r < i + size; r++){ let sum = 0; for(let c = j; c < j + size; c++){ sum += grid[r][c]; } if(targetSum !== sum){ return false; } } //check cols for(let c = j; c < j + size; c++){ let sum = 0; for(let r = i; r < i + size; r++){ sum += grid[r][c]; } if(targetSum !== sum){ return false; } } //check diagonals let diagSum = 0, antiDiagSum = 0; for(let c = 0; c < size; c++){ diagSum += grid[i + c][j+c]; antiDiagSum += grid[i + c][j + size - 1 - c]; } if(diagSum !== antiDiagSum || diagSum !== targetSum){ return false } return true; }
Largest Magic Square
Given a string s, find the length of the longest substring without repeating characters. &nbsp; Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. &nbsp; Constraints: 0 &lt;= s.length &lt;= 5 * 104 s consists of English letters, digits, symbols and spaces.
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest_s = '' curr_s = '' for i in s: if i not in curr_s: curr_s += i if len(curr_s) >= len(longest_s): longest_s = curr_s else: curr_s = curr_s[curr_s.index(i)+1:]+i return len(longest_s)
class Solution { public int lengthOfLongestSubstring(String s) { Map<Character, Integer> hash = new HashMap<>(); int count = 0; int ans = 0; for(int i=0; i < s.length(); i++){ if(hash.containsKey(s.charAt(i))){ i = hash.get(s.charAt(i)) + 1; hash.clear(); count = 0; } if(!hash.containsKey(s.charAt(i))){ hash.put(s.charAt(i), i); count++; ans = Math.max(ans, count); } } return ans; } }
class Solution { public: int lengthOfLongestSubstring(string s) { map<char, int> mp; int ans = 1; for(auto ch : s) { if(mp.find(ch) != mp.end()) { while(mp.find(ch) != mp.end()) mp.erase(mp.begin()); } mp.insert({ch, 1}); if(mp.size() > ans) ans = mp.size(); } return ans; } };
var lengthOfLongestSubstring = function(s) { // keeps track of the most recent index of each letter. const seen = new Map(); // keeps track of the starting index of the current substring. let start = 0; // keeps track of the maximum substring length. let maxLen = 0; for(let i = 0; i < s.length; i++) { // if the current char was seen, move the start to (1 + the last index of this char) // max prevents moving backward, 'start' can only move forward if(seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start) seen.set(s[i], i); // maximum of the current substring length and maxLen maxLen = Math.max(i - start + 1, maxLen); } return maxLen; };
Longest Substring Without Repeating Characters
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. &nbsp; Example 1: Input: nums = [1,3], n = 6 Output: 1 Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: Input: nums = [1,5,10], n = 20 Output: 2 Explanation: The two patches can be [2, 4]. Example 3: Input: nums = [1,2,2], n = 5 Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 1 &lt;= nums[i] &lt;= 104 nums is sorted in ascending order. 1 &lt;= n &lt;= 231 - 1
class Solution: def minPatches(self, nums: List[int], n: int) -> int: #pre-process for convenience nums.append(n+1) t=1 sum=1 rs=0 if nums[0]!=1: nums=[1]+nums rs+=1 # the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go form left to right to cover upto n while sum<n: if sum<nums[t]-1: sum+=(sum+1) rs+=1 else: sum+=nums[t] t+=1 return rs
class Solution { public int minPatches(int[] nums, int n) { long sum = 0; int count = 0; for (int x : nums) { if (sum >= n) break; while (sum+1 < x && sum < n) { ++count; sum += sum+1; } sum += x; } while (sum < n) { sum += sum+1; ++count; } return count; } }
class Solution { public: int minPatches(vector<int>& nums, int n) { nums.push_back(0); sort(nums.begin(), nums.end()); long sum = 0; int ans = 0; for(int i = 1; i < nums.size(); i++){ while((long)nums[i] > (long)(sum + 1)){ ans++; sum += (long)(sum + 1); if(sum >= (long)n) return ans; } sum += nums[i]; if(sum >= (long)n) return ans; } while(sum < (long)n){ ans++; sum += (long)(sum + 1); } return ans; } };
// time complexity: // while loop is - o(n) beacuse we can potentially get to n with nums array full of ones and we will pass on each of them // in some cases it will hit o(logn) if the nums array is pretty empty var minPatches = function(nums, n) { // nums is sorted so we don't have to sort it let index = 0; let sumCanCreate = 0; let patchCount = 0; while(sumCanCreate < n) { // if we can't create nums[index] or we at the end of nums and can't create n. // we can create nums[index] only if it is lower or equal to sumCanCreate+1. if(sumCanCreate+1 < nums[index] || (index >= nums.length && sumCanCreate+1 < n)) { patchCount++; // because we "patch" the next number in the sequence. sumCanCreate += (sumCanCreate+1); // if we can create nums[index]. } else { // we can create anything from current sumCanCreate to (sumCanCreate + nums[index]). sumCanCreate += nums[index]; index++; } } return patchCount; };
Patching Array
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i]. Execute all the valid transactions. A transaction is valid if: The given account number(s) are between 1 and n, and The amount of money withdrawn or transferred from is less than or equal to the balance of the account. Implement the Bank class: Bank(long[] balance) Initializes the object with the 0-indexed integer array balance. boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise. boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise. boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise. &nbsp; Example 1: Input ["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"] [[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]] Output [null, true, true, true, false, false] Explanation Bank bank = new Bank([10, 100, 20, 50, 30]); bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10. // Account 3 has $20 - $10 = $10. bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20. // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30. bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5. // Account 5 has $10 + $20 = $30. bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10, // so it is invalid to transfer $15 from it. bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist. &nbsp; Constraints: n == balance.length 1 &lt;= n, account, account1, account2 &lt;= 105 0 &lt;= balance[i], money &lt;= 1012 At most 104 calls will be made to each function transfer, deposit, withdraw.
class Bank: def __init__(self, bal: List[int]): self.store = bal # storage list def transfer(self, a1: int, a2: int, money: int) -> bool: try: # checking if both accounts exist. and if the transaction would be valid if self.store[a1 - 1] >= money and self.store[a2 - 1] >= 0: # performing the transaction self.store[a1 - 1] -= money self.store[a2 - 1] += money return True else: # retrning false on invalid transaction return False except: # returning false when accounts don't exist return False def deposit(self, ac: int, mn: int) -> bool: try: # if account exists performing transaction self.store[ac - 1] += mn return True except: # returning false when account doesn't exist return False def withdraw(self, ac: int, mn: int) -> bool: try: # checking if transaction is valid if self.store[ac - 1] >= mn: # performing the transaction self.store[ac - 1] -= mn return True else: # returning false in case on invalid transaction return False except: # returning false when account doesn't exist return False
class Bank { int N; long[] balance; public Bank(long[] balance) { this.N = balance.length; this.balance = balance; } public boolean transfer(int account1, int account2, long money) { if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < money) return false; balance[account1 - 1] -= money; balance[account2 - 1] += money; return true; } public boolean deposit(int account, long money) { if(account < 1 || account > N) return false; balance[account - 1] += money; return true; } public boolean withdraw(int account, long money) { if(account < 1 || account > N || balance[account - 1] < money) return false; balance[account - 1] -= money; return true; } }
class Bank { public: vector<long long> temp; int n; Bank(vector<long long>& balance) { temp=balance; n=balance.size(); } bool transfer(int account1, int account2, long long money) { if(account1<=n && account2<=n && account1>0 && account2>0 && temp[account1-1]>=money){ temp[account1-1]-=money; temp[account2-1]+=money; return true; } return false; } bool deposit(int account, long long money) { if(account>n || account<0)return false; temp[account-1]+=money; return true; } bool withdraw(int account, long long money) { if(account<=n && account>0 && temp[account-1]>=money){ temp[account-1]-=money; return true; } return false; } };
/** * @param {number[]} balance */ var Bank = function(balance) { this.arr = balance; }; /** * @param {number} account1 * @param {number} account2 * @param {number} money * @return {boolean} */ Bank.prototype.transfer = function(account1, account2, money) { if (this.arr[account1-1] >= money && this.arr.length >= account1 && this.arr.length >= account2) { this.arr[account1-1] -= money; this.arr[account2-1] += money; return true; } return false; }; /** * @param {number} account * @param {number} money * @return {boolean} */ Bank.prototype.deposit = function(account, money) { if (this.arr.length >= account) { this.arr[account-1] += money; return true; } return false; }; /** * @param {number} account * @param {number} money * @return {boolean} */ Bank.prototype.withdraw = function(account, money) { if (this.arr.length >= account && this.arr[account-1] >= money) { this.arr[account-1] -= money return true; } return false; }; /** * Your Bank object will be instantiated and called as such: * var obj = new Bank(balance) * var param_1 = obj.transfer(account1,account2,money) * var param_2 = obj.deposit(account,money) * var param_3 = obj.withdraw(account,money) */
Simple Bank System
You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray, return -1. A subarray is a contiguous non-empty sequence of elements within an array. &nbsp; Example 1: Input: nums = [1,3,4,3,1], threshold = 6 Output: 3 Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2. Note that this is the only valid subarray. Example 2: Input: nums = [6,5,6,5,8], threshold = 7 Output: 1 Explanation: The subarray [8] has a size of 1, and 8 &gt; 7 / 1 = 7. So 1 is returned. Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions. Therefore, 2, 3, 4, or 5 may also be returned. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i], threshold &lt;= 109
class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: nums = [0] + nums + [0] stack = [0] for i in range(1,len(nums)): while nums[i] < nums[stack[-1]]: tmp = nums[stack.pop()] if tmp > threshold / (i - stack[-1] - 1): return i - stack[-1] - 1 stack.append(i) return -1
class Solution { public int validSubarraySize(int[] nums, int threshold) { int n = nums.length; int[] next_small = new int[n]; int[] prev_small = new int[n]; Stack<Integer> stack = new Stack<>(); stack.push(0); Arrays.fill(next_small, n); Arrays.fill(prev_small, -1); for(int i=1;i<n;i++){ while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){ stack.pop(); } if(stack.size()!=0){ prev_small[i] = stack.peek(); } stack.push(i); } stack = new Stack<>(); stack.push(n-1); for(int i=n-2;i>=0;i--){ while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){ stack.pop(); } if(stack.size()!=0){ next_small[i] = stack.peek(); } stack.push(i); } for(int i=0;i<n;i++){ int len = next_small[i] - prev_small[i] - 1; if(threshold/(double)len < nums[i]){ return len; } } return -1; } }
class Solution { public: int validSubarraySize(vector<int>& nums, int threshold) { int n = nums.size(); vector<long long> lr(n, n), rl(n, -1); vector<int> s; for(int i = 0; i < n; ++i) { while(!s.empty() and nums[i] < nums[s.back()]) { lr[s.back()] = i; s.pop_back(); } s.push_back(i); } s.clear(); for(int i = n - 1; ~i; --i) { while(!s.empty() and nums[i] < nums[s.back()]) { rl[s.back()] = i; s.pop_back(); } s.push_back(i); } for(int i = 0; i < n; ++i) { long long length = lr[i] - rl[i] - 1; if(1LL * nums[i] * length > threshold) return length; } return -1; } }; // please upvote if you like
/** * @param {number[]} nums * @param {number} threshold * @return {number} */ var validSubarraySize = function(nums, threshold) { /* Approach: Use monotonous increasing array */ let stack=[]; for(let i=0;i<nums.length;i++){ let start = i; while(stack.length>0 && stack[stack.length-1][0]>nums[i]){ let popped = stack.pop(); let min = popped[0]; let len = i-popped[1]; if(min>threshold/len){ return len; } start = popped[1]; } stack.push([nums[i],start]); } let end = nums.length-1; for(let i=0;i<stack.length;i++){ let len = end - stack[i][1] +1; let min = stack[i][0]; if(min>threshold/len){ return len; } } return -1; };
Subarray With Elements Greater Than Varying Threshold
Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order. The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. &nbsp; Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 15 -100 &lt;= nums[i] &lt;= 100
class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: def backtracking(nums,path): # to ensure that the base array has at least 2 elements if len(path)>=2: res.add(tuple(path)) for i in range(len(nums)): # to ensure that every element to be added is equal or larger than the former if not path or path[-1] <= nums[i]: backtracking(nums[i+1:],path+[nums[i]]) res=set() backtracking(nums,[]) return res
class Solution { HashSet<List<Integer>> set; public List<List<Integer>> findSubsequences(int[] nums) { set=new HashSet<>(); dfs(nums,0,new ArrayList<>()); List<List<Integer>> ans=new ArrayList<>(); if(set.size()>0){ ans.addAll(set); } return ans; } private void dfs(int nums[], int start, List<Integer> temp){ if(start==nums.length) return; for(int i=start;i<nums.length;i++){ if(temp.size()==0 || temp.get(temp.size()-1)<=nums[i]){ temp.add(nums[i]); if(temp.size()>=2) set.add(new ArrayList<>(temp)); dfs(nums,i+1,temp); temp.remove(temp.size()-1); } } } }
class Solution { public: set<vector<int>>ans; void solve(int start, int n, vector<int>&nums, vector<int>&result){ if(result.size()>1)ans.insert(result); if(start==n){ return; } for(int i=start; i<n; i++){ if(result.empty() || result.back()<=nums[i]){ result.push_back(nums[i]); solve(i+1, n, nums, result); result.pop_back(); } } } vector<vector<int>> findSubsequences(vector<int>& nums) { int n = nums.size(); vector<int>result; solve(0, n, nums, result); return vector<vector<int>>(ans.begin(), ans.end()); } };
var findSubsequences = function(nums) { const result = []; const set = new Set(); function bt(index=0,ar=[]){ if(!set.has(ar.join("_")) && ar.length >=2){ set.add(ar.join("_")); result.push(ar); } for(let i =index; i<nums.length; i++){ if(nums[i] >= ar[ar.length-1] || ar.length===0){ bt(i+1, [...ar, nums[i]]); } } } bt(); return result; };
Increasing Subsequences
You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively. Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. Return the string formed after mapping. The test cases are generated so that a unique mapping will always exist. &nbsp; Example 1: Input: s = "10#11#12" Output: "jkab" Explanation: "j" -&gt; "10#" , "k" -&gt; "11#" , "a" -&gt; "1" , "b" -&gt; "2". Example 2: Input: s = "1326#" Output: "acz" &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consists of digits and the '#' letter. s will be a valid string such that mapping is always possible.
class Solution: def freqAlphabets(self, s: str) -> str: for i in range(26,0,-1): s = s.replace(str(i)+"#"*(i>9),chr(96+i)) return s
class Solution { public String freqAlphabets(String str) { HashMap<String, Character> map = new HashMap<>(); int k = 1; for (char ch = 'a'; ch <= 'z'; ch++) { if (ch < 'j') map.put(String.valueOf(k++), ch); else map.put(String.valueOf(k++)+"#", ch); } StringBuilder sb = new StringBuilder(); int i = str.length() - 1; while (i >= 0) { if (str.charAt(i) == '#') { sb.append(map.get(str.substring(i - 2, i+1))); i -= 3; } else { sb.append(map.get(str.substring(i, i + 1))); i--; } } return sb.reverse().toString(); } }
class Solution { public: string freqAlphabets(string s) { int n=s.size(); string ans=""; for(int i=0;i<n;){ if(i+2<n && s[i+2]=='#'){ ans+= (s[i]-'0')*10 + (s[i+1]-'0') +96; i+=3; } else{ ans+=(s[i]-'0') + 96; i++; } } return ans; } };
var freqAlphabets = function(s) { const ans = [] for (let i = 0, len = s.length; i < len; ++i) { const c = s.charAt(i) if (c === '#') { ans.length = ans.length - 2 ans.push(String.fromCharCode(parseInt(`${s.charAt(i - 2)}${s.charAt(i - 1)}`, 10) + 96)) continue } ans.push(String.fromCharCode(+c + 96)) } return ans.join('') };
Decrypt String from Alphabet to Integer Mapping
Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: &lt;IntegerPart&gt;, &lt;NonRepeatingPart&gt;, and a &lt;RepeatingPart&gt;. The number will be represented in one of the following three ways: &lt;IntegerPart&gt; For example, 12, 0, and 123. &lt;IntegerPart&gt;&lt;.&gt;&lt;NonRepeatingPart&gt; For example, 0.5, 1., 2.12, and 123.0001. &lt;IntegerPart&gt;&lt;.&gt;&lt;NonRepeatingPart&gt;&lt;(&gt;&lt;RepeatingPart&gt;&lt;)&gt; For example, 0.1(6), 1.(9), 123.00(1212). The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66). &nbsp; Example 1: Input: s = "0.(52)", t = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number. Example 2: Input: s = "0.1666(6)", t = "0.166(66)" Output: true Example 3: Input: s = "0.9(9)", t = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "". &nbsp; Constraints: Each part consists only of digits. The &lt;IntegerPart&gt; does not have leading zeros (except for the zero itself). 1 &lt;= &lt;IntegerPart&gt;.length &lt;= 4 0 &lt;= &lt;NonRepeatingPart&gt;.length &lt;= 4 1 &lt;= &lt;RepeatingPart&gt;.length &lt;= 4
class Solution: # inspired from: # https://coolconversion.com/math/recurring-decimals-as-a-fraction/ # to which we wouldn't have access during interview. import typing def isRationalEqual(self, s: str, t: str) -> bool: # intuition: # write each numbes as fraction: num / den # then compare the two fractions. num1, den1 = self.toFraction(s) num2, den2 = self.toFraction(t) return den1 * num2 == den2 * num1 def toFraction(self, s: str) -> typing.Tuple[int, int]: if "." not in s: return int(s), 1 intp, frac = s.split(".") # decimal dot, but no repeating part: # xyz.abc = xyzabc / 1000 if "(" not in frac: ifrac = int(frac) if len(frac) > 0 else 0 num = int(intp) * (10 ** len(frac)) + ifrac den = 10 ** len(frac) return num, den # this is for cases like a.b(c) # let n = a.b(c) # then, 10^(len(b+c)) * n = abc.(c) # and 10^(len(b)) * n = ab.(c) # subtract the two, and solve for n: # n = (abc - ab) / (10^len(b + c) - 10^len(b)) frac, repfrac = frac.split("(") repfrac = repfrac[:-1] iintp = int(intp) ifrac = int(frac) if len(frac) > 0 else 0 irep = int(repfrac) return ( (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac), (10** len(frac+repfrac) - 10 **len(frac)) ) ```
class Solution { private List<Double> ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999); public boolean isRationalEqual(String S, String T) { return Math.abs(computeValue(S) - computeValue(T)) < 1e-9; } private double computeValue(String s) { if (!s.contains("(")) { return Double.valueOf(s); } else { double intNonRepeatingValue = Double.valueOf(s.substring(0, s.indexOf('('))); int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1; int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1; int repeatingValue = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')'))); return intNonRepeatingValue + repeatingValue * Math.pow(0.1, nonRepeatingLength) * ratios.get(repeatingLength); } } }
class Solution { public: double toDouble(string s){ // Strings for each integral, fractional, and repeating part string in="", fn="", rn=""; int i=0; // Integral while(i<s.size() && s[i]!='.'){ in+=s[i]; i++; } // Fractional i++; while(i<s.size() && s[i]!='('){ fn+=s[i]; i++; } // Repeating i++; while(i<s.size() && s[i]!=')'){ rn+=s[i]; i++; } // Number double a = 0; // Adding integral part if(!in.empty()) a=stoi(in); i=0; // Adding fractional part while(i<fn.size()){ a = a*10 + fn[i] - '0'; i++; } // Adding repeating part if(i < 8){ // If repeatig part isn't there then just add 0s if(rn.size() == 0){ while(i <= 8){ a*=10;i++; } } else { int j=0; while(i <= 8){ a = a*10 + rn[j%rn.size()] - '0'; j++; i++; } } } // Return number/10^8 return a/10e8; } bool isRationalEqual(string s, string t) { // Find absolute differance till 8 digits after decimal and compar if its lesser double ans = abs(toDouble(s) - toDouble(t)); return ans < 0.000000002; } };
var isRationalEqual = function(s, t) { return calculate(s) === calculate(t); function calculate(v) { let start = v.split('(')[0] || v; let newer = v.split('(')[1] && v.split('(')[1].split(')')[0] || '0'; start = start.includes('.') ? start : start + '.'; newer = newer.padEnd(100, newer); return parseFloat(start + newer); } };
Equal Rational Numbers
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of "first second third". &nbsp; Example 1: Input: text = "alice is a good girl she is a good student", first = "a", second = "good" Output: ["girl","student"] Example 2: Input: text = "we will we will rock you", first = "we", second = "will" Output: ["we","rock"] &nbsp; Constraints: 1 &lt;= text.length &lt;= 1000 text consists of lowercase English letters and spaces. All the words in text a separated by a single space. 1 &lt;= first.length, second.length &lt;= 10 first and second consist of lowercase English letters.
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: pattern = r"(?<=\b" + first +" " + second + r" )[a-z]*" txt = re.findall(pattern,text) return txt
class Solution { public String[] findOcurrences(String text, String first, String second) { List<String> list = new ArrayList<>(); String[] arr = text.split(" "); for(int i = 0; i < arr.length - 2; i++) { if(arr[i].equals(first) && arr[i + 1].equals(second)) { list.add(arr[i + 2]); } } String[] result = list.toArray(new String[0]); return result; } }
class Solution { public: vector<string> findOcurrences(string text, string first, string second) { vector<string>ans; int i=0; while(i<text.length()) { string word = ""; string secondWord=""; while(i<text.length() && text[i]!=' ') { word = word+text[i]; i++; } if(word == first) { int k = i+1; while(k<text.length() && text[k]!=' ') { secondWord = secondWord+text[k]; k++; } k++; if(k<text.length() && secondWord==second) { string tmp=""; int j=k; while(j<text.length() && text[j]!=' ') { tmp = tmp+text[j]; j++; } ans.push_back(tmp); } } i++; } return ans; } };
var findOcurrences = function(text, first, second) { let result = []; let txt = text.split(' '); for(let i = 0; i<txt.length - 2; i++) { if(txt[i] === first && txt[i+1] === second) result.push(txt[i+2]); } return result; };
Occurrences After Bigram
Given an integer&nbsp;k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n &gt; 2. It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k. &nbsp; Example 1: Input: k = 7 Output: 2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. Example 2: Input: k = 10 Output: 2 Explanation: For k = 10 we can use 2 + 8 = 10. Example 3: Input: k = 19 Output: 3 Explanation: For k = 19 we can use 1 + 5 + 13 = 19. &nbsp; Constraints: 1 &lt;= k &lt;= 109
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib_sq = [1, 1] while fib_sq[-1] + fib_sq[-2] <= k: fib_sq.append(fib_sq[-1]+fib_sq[-2]) counter = 0 for i in range(len(fib_sq)-1, -1, -1): if fib_sq[i] <= k: counter += 1 k -= fib_sq[i] return counter
class Solution { public int findMinFibonacciNumbers(int k) { int ans = 0; while (k > 0) { // Run until solution is reached int fib2prev = 1; int fib1prev = 1; while (fib1prev <= k) { // Generate Fib values, stop when fib1prev is > k, we have the fib number we want stored in fib2prev int temp = fib2prev + fib1prev; fib2prev = fib1prev; fib1prev = temp; } k -= fib2prev; ans += 1; } return ans; } }
class Solution { public: int findMinFibonacciNumbers(int k) { vector<int> fibb; int a = 1; int b = 1; fibb.push_back(a); fibb.push_back(b); int next = a + b; while (next <= k) { fibb.push_back(next); a = b; b = next; next = a + b; } int res = 0; int j = fibb.size() - 1; while (j >= 0 and k > 0) { if (fibb[j] <= k) { k -= fibb[j]; res++; } j--; } return res; } };
var findMinFibonacciNumbers = function(k) { let sequence = [1, 1], sum = sequence[0] + sequence[1]; let i = 2; while (sum <= k) { sequence.push(sum); i++; sum = sequence[i-1]+sequence[i-2]; } let j = sequence.length-1, res = 0; while (k) { if (k >= sequence[j]) k -= sequence[j], res++; j--; } return res; // Time Complexity: O(n) // Space Complexity: O(n) };
Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
Given the head of a linked&nbsp;list, rotate the list to the right by k places. &nbsp; Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1] &nbsp; Constraints: The number of nodes in the list is in the range [0, 500]. -100 &lt;= Node.val &lt;= 100 0 &lt;= k &lt;= 2 * 109
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if k==0 or head is None or head.next is None: return head cur=head n=0 while cur is not None: cur=cur.next n+=1 k=n-k%n if k==n: return head cur=head prev=None while k>0 and cur is not None: prev=cur cur=cur.next k-=1 prev.next=None prev=cur while cur.next is not None: cur=cur.next cur.next=head return prev
class Solution { public ListNode rotateRight(ListNode head, int k) { if(k<=0 || head==null || head.next==null){ return head; } int length=1; ListNode first=head; ListNode curr=head; ListNode node=head; while(node.next!=null){ length++; node=node.next; } if(k==length){ return head; } int n=length-(k%length); for(int i=0; i<n-1;i++){ curr=curr.next; } node.next=head; //5-->1 head=curr.next; curr.next=null; return head; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: // like if it is useful to you ListNode* rotateRight(ListNode* head, int k) { if(head == NULL){ return head; } vector<int> nums; ListNode *temp = head; while(temp != NULL){ nums.push_back(temp->val); temp = temp->next; } // if k greater than size; k = k%nums.size(); // rotating vector reverse(nums.begin(),nums.end()); reverse(nums.begin(),nums.begin()+k); reverse(nums.begin()+k,nums.end()); // replace value of list temp = head; for(int i = 0; i<nums.size();i++){ temp->val = nums[i]; temp = temp->next; } return head; } };
var rotateRight = function(head, k) { if(k === 0 || !head) return head; let n = 0; let end = null; let iterator = head; while(iterator) { n += 1; end = iterator; iterator = iterator.next; } const nodesToRotate = k % n; if(nodesToRotate === 0) return head; let breakAt = n - nodesToRotate; iterator = head; while(breakAt - 1 > 0) { iterator = iterator.next; breakAt -= 1; } const newHead = iterator.next; iterator.next = null; end.next = head; return newHead; };
Rotate List
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false. int next() Moves the pointer to the right, then returns the number at the pointer. Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. &nbsp; Example 1: Input ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] Output [null, 3, 7, true, 9, true, 15, true, 20, false] Explanation BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False &nbsp; Constraints: The number of nodes in the tree is in the range [1, 105]. 0 &lt;= Node.val &lt;= 106 At most 105 calls will be made to hasNext, and next. &nbsp; Follow up: Could you implement next() and hasNext() to run in average O(1) time and use&nbsp;O(h) memory, where h is the height of the 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 BSTIterator: def __init__(self, root: Optional[TreeNode]): self.root=root self.tree=[]#list to store the inorder traversal def inorder(node): if not node: return inorder(node.left) self.tree.append(node.val) inorder(node.right) return inorder(self.root) self.i=0 def next(self) -> int: self.i+=1 return self.tree[self.i-1] def hasNext(self) -> bool: return self.i-1<len(self.tree)-1 # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
class BSTIterator { TreeNode root; TreeNode current; Stack<TreeNode> st = new Stack<>(); public BSTIterator(TreeNode root) { this.root = root; //init(root); current = findLeft(root); //System.out.println("Init: stack is: "+st); } public int next() { int val = -1; if(current != null) val = current.val; else return -1; if(current.right != null) current = findLeft(current.right); else if(!st.isEmpty()) current = st.pop(); else current = null; // System.out.println("next: stack is: "+st); return val; } public TreeNode findLeft(TreeNode node) { if(node == null) return null; if(node.left != null){ TreeNode next = node.left; st.push(node); return findLeft(next); } else return node; } public boolean hasNext() { return current != null; } }
//TC O(1) and O(H) Space //MIMIC inorder class BSTIterator { public: stack<TreeNode*> stk; BSTIterator(TreeNode* root) { pushAll(root); // left is done } int next() { //root handled TreeNode* node = stk.top(); int ans = node->val; stk.pop(); //right handled pushAll(node->right); return ans; } bool hasNext() { return stk.size() != 0; // stk is empty then no next to show simple } void pushAll(TreeNode* root){ //left part - as inorder is like Left left left, once a root is done then check right while(root!= NULL){ stk.push(root); root = root->left; } } };
/** * 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 */ var BSTIterator = function(root) { this.stack = []; this.node = root; }; /** * @return {number} */ BSTIterator.prototype.next = function() { while (this.node) { this.stack.push(this.node); this.node = this.node.left; } const node = this.stack.pop(); this.node = node.right; return node.val; }; /** * @return {boolean} */ BSTIterator.prototype.hasNext = function() { return this.node || this.stack.length > 0; }; /** * Your BSTIterator object will be instantiated and called as such: * var obj = new BSTIterator(root) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
Binary Search Tree Iterator
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. For example, when num = "5489355142": The 1st smallest wonderful integer is "5489355214". The 2nd smallest wonderful integer is "5489355241". The 3rd smallest wonderful integer is "5489355412". The 4th smallest wonderful integer is "5489355421". Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth&nbsp;smallest wonderful integer exists. &nbsp; Example 1: Input: num = "5489355142", k = 4 Output: 2 Explanation: The 4th smallest wonderful number is "5489355421". To get this number: - Swap index 7 with index 8: "5489355142" -&gt; "5489355412" - Swap index 8 with index 9: "5489355412" -&gt; "5489355421" Example 2: Input: num = "11112", k = 4 Output: 4 Explanation: The 4th smallest wonderful number is "21111". To get this number: - Swap index 3 with index 4: "11112" -&gt; "11121" - Swap index 2 with index 3: "11121" -&gt; "11211" - Swap index 1 with index 2: "11211" -&gt; "12111" - Swap index 0 with index 1: "12111" -&gt; "21111" Example 3: Input: num = "00123", k = 1 Output: 1 Explanation: The 1st smallest wonderful number is "00132". To get this number: - Swap index 3 with index 4: "00123" -&gt; "00132" &nbsp; Constraints: 2 &lt;= num.length &lt;= 1000 1 &lt;= k &lt;= 1000 num only consists of digits.
class Solution: def getMinSwaps(self, num: str, k: int) -> int: num = list(num) orig = num.copy() for _ in range(k): for i in reversed(range(len(num)-1)): if num[i] < num[i+1]: ii = i+1 while ii < len(num) and num[i] < num[ii]: ii += 1 num[i], num[ii-1] = num[ii-1], num[i] lo, hi = i+1, len(num)-1 while lo < hi: num[lo], num[hi] = num[hi], num[lo] lo += 1 hi -= 1 break ans = 0 for i in range(len(num)): ii = i while orig[i] != num[i]: ans += 1 ii += 1 num[i], num[ii] = num[ii], num[i] return ans
class Solution { public int getMinSwaps(String num, int k) { int[] nums=new int[num.length()]; int[] org=new int[num.length()]; for(int i=0;i<num.length();i++){ int e=Character.getNumericValue(num.charAt(i)); nums[i]=e; org[i]=e; } while(k!=0){ nextPermutation(nums); k--; } int ans=0; for(int i=0;i<nums.length;i++){ if(nums[i]!=org[i]){ int j=0; for(j=i+1;j<nums.length;j++) if(org[j]==nums[i]) break; while(j>0 && j!=i){ swap(org,j,j-1); ans++; j--; } } } return ans; } public void nextPermutation(int[] nums) { if(nums.length<=1) return; int j=nums.length-2; while(j>=0 && nums[j]>=nums[j+1]) j--; if(j>=0){ int k=nums.length-1; while(nums[j]>=nums[k]) k--; swap(nums,j,k); } reverse(nums,j+1,nums.length-1); } public void swap(int[] nums,int j,int k){ int temp=nums[j]; nums[j]=nums[k]; nums[k]=temp; } public void reverse(int[] nums,int i,int j){ while(i<=j){ swap(nums,i,j); i++; j--; } } }
class Solution { public: // GREEDY APPROACH // min steps to make strings equal int minSteps(string s1, string s2) { int size = s1.length(); int i = 0, j = 0; int result = 0; while (i < size) { j = i; while (s1[j] != s2[i]) j++; while (i < j) { swap(s1[j], s1[j-1]); j--; result++; } i++; } return result; } int getMinSwaps(string num, int k) { string original = num; while(k--) { next_permutation(num.begin(), num.end()); } return minSteps(original, num); } };
var getMinSwaps = function(num, k) { const digits = [...num] const len = digits.length; // helper function to swap elements in digits in place const swap = (i, j) => [digits[i], digits[j]] = [digits[j], digits[i]] // helper function to reverse elements in digits from i to the end of digits const reverse = (i) => { for (let j = len - 1; i < j; ++i && --j) { swap(i, j); } } // helper to get the next smallest permutation for digits const nextPermutation = () => { // from right to left, find the first decreasing index // in digits and store it as i let i = len - 2; while (digits[i] >= digits[i + 1]) { i--; } // from right to left, find the first index in digits // that is greater than element at i let j = len - 1; while (digits[j] <= digits[i]) { j--; } // swap the 2 elements at i and j swap(i, j); // reverse all elements after i because we know that // all elements after i are in ascending order // from right to left reverse(i + 1); } // find the next permutation k times for (let i = 0; i < k; i++) { nextPermutation(); } // find out how many swaps it will take to get to the // kth permutation by finding out how many swaps // it takes to put digits back to its original state let numSwaps = 0; for (let i = 0; i < len; i++) { let j = i; // find the first element in digits to matches // num[i] and hold its place at j while (num[i] !== digits[j]) { j++; } // move the element at j to i while counting the // number of swaps while (i < j) { swap(j, j - 1); numSwaps++; j--; } } return numSwaps; };
Minimum Adjacent Swaps to Reach the Kth Smallest Number
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. &nbsp; Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: heights: [1,1,4,2,1,3] expected: [1,1,1,2,3,4] Indices 2, 4, and 5 do not match. Example 2: Input: heights = [5,1,2,3,4] Output: 5 Explanation: heights: [5,1,2,3,4] expected: [1,2,3,4,5] All indices do not match. Example 3: Input: heights = [1,2,3,4,5] Output: 0 Explanation: heights: [1,2,3,4,5] expected: [1,2,3,4,5] All indices match. &nbsp; Constraints: 1 &lt;= heights.length &lt;= 100 1 &lt;= heights[i] &lt;= 100
class Solution: def heightChecker(self, heights: List[int]) -> int: heightssort = sorted(heights) import numpy as np diff = list(np.array(heightssort) - np.array(heights)) return (len(diff) - diff.count(0))
class Solution { public int heightChecker(int[] heights) { int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length); Arrays.sort(dupheights); int count = 0; for(int i=0 ; i< heights.length ; i++){ if(heights[i] != dupheights[i]){ count++; } } return count; } }
class Solution { public: int heightChecker(vector<int>& heights) { vector<int> expected=heights; int count=0; sort(expected.begin(),expected.end()); for(int i=0;i<heights.size();i++){ if(heights[i]!=expected[i]) count++; } return count; } };
var heightChecker = function(heights) { let count = 0; const orderedHeights = [...heights].sort((a, b) => a-b) for (let i = 0; i < heights.length; i++) { heights[i] !== orderedHeights[i] ? count++ : null } return count };
Height Checker
An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. &nbsp; Example 1: Input: "112358" Output: true Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 Example 2: Input: "199100199" Output: true Explanation: The additive sequence is: 1, 99, 100, 199.&nbsp; 1 + 99 = 100, 99 + 100 = 199 &nbsp; Constraints: 1 &lt;= num.length &lt;= 35 num consists only of digits. &nbsp; Follow up: How would you handle overflow for very large input integers?
class Solution: def isAdditiveNumber(self, num: str) -> bool: def isadditive(num1,num2,st): if len(st) == 0: return True num3 = str(num1+num2) l = len(num3) return num3 == st[:l] and isadditive(num2,int(num3),st[l:]) for i in range(1,len(num)-1): for j in range(i+1,len(num)): if num [0] == "0" and i != 1: break if num[i] == "0" and i+1 != j: break if isadditive(int(num[:i]),int(num[i:j]),num[j:]): return True return False
class Solution { public boolean isAdditiveNumber(String num) { return backtrack(num, 0, 0, 0, 0); } public boolean backtrack(String num, int idx, long sum, long prev, int length){ if(idx == num.length()){ return length >= 3; } long currLong = 0; for(int i = idx; i < num.length(); i++){ //make sure it won't start with 0 if(i > idx && num.charAt(idx) == '0') break; currLong = currLong * 10 + num.charAt(i) - '0'; if(length >= 2){ if(sum < currLong){ //currLong is greater than sum of previous 2 numbers break; }else if(sum > currLong){ //currLong is smaller than sum of previous 2 numbers continue; } } //currLong == sum of previous 2 numbers if(backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true){ return true; } } return false; } }
class Solution { public: bool isAdditiveNumber(string num) { vector<string> adds; return backtrack(num, 0, adds); } private: bool backtrack(string num, int start, vector<string> &adds) { if (start >= num.size() && adds.size() >= 3) return true; int maxSize = num[start] == '0' ? 1 : num.size() - start; for (int i = 1; i <= maxSize; i++) { string current = num.substr(start, i); if (adds.size() >= 2) { string num1 = adds[adds.size() - 1], num2 = adds[adds.size() - 2]; string sum = add(num1, num2); if (sum != current) continue; } adds.push_back(current); if (backtrack(num, start + i, adds)) return true; adds.pop_back(); } return false; } string add(string num1, string num2) { string sum; int i1 = num1.size() - 1, i2 = num2.size() - 1, carry = 0; while (i1 >= 0 || i2 >= 0) { int current = carry + (i1 >= 0 ? (num1[i1--] - '0') : 0) + (i2 >= 0 ? (num2[i2--] - '0') : 0); carry = current / 10; sum.push_back(current % 10 + '0'); } if (carry) sum.push_back(carry + '0'); reverse(begin(sum), end(sum)); return sum; } };
const getNum = (str, i, j) => { str = str.slice(i, j); if(str[0] == '0' && str.length > 1) return -1000 return Number(str); } var isAdditiveNumber = function(num) { // i = 3 say and make theory and proof that const len = num.length; for(let b = 2; b < len; b++) { for(let i = 0; i < b - 1; i++) { for(let j = i + 1; j < b; j++) { let v1 = getNum(num,0, i + 1); let v2 = getNum(num,i + 1, j + 1); let v3 = getNum(num,j + 1, b + 1); if(v1 + v2 == v3) { // test hypothesis; // from b start checking if string persist behaviour let p = num.slice(0, b + 1); while(p.length <= len) { let sum = v2 + v3; p += sum; v2 = v3; v3 = sum; } if(p.slice(0, len) == num) { return true; } } } } } return false; };
Additive Number
Given an&nbsp;integer n, return a string with n&nbsp;characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. &nbsp; &nbsp; Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". Example 2: Input: n = 2 Output: "xy" Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". Example 3: Input: n = 7 Output: "holasss" &nbsp; Constraints: 1 &lt;= n &lt;= 500
class Solution: def generateTheString(self, n: int) -> str: alpha = "abcdefghijklmnopqrstuvwxyz" res="" while n>0: curr, alpha = alpha[0], alpha[1:] if n%2: res += curr*n n-=n else: res += curr*(n-1) n-=n-1 return res
class Solution { public String generateTheString(int n) { String s = ""; String string ="a"; for (int i = 0; i < n-1; i++) s += string; if(n%2==0) return s+"b"; return s+"a"; } }
class Solution { public: string generateTheString(int n) { string s=""; if(n%2!=0){ for(int i=0;i<n;i++) s+="a"; } else{ for(int i=0;i<n-1;i++) s+="a"; s+="b"; } return s; } };
// C++ Code class Solution { public: string generateTheString(int n) { string res = ""; if (n%2 == 0) { res += 'a'; n -= 1; } for (int i=0;i < n;i++) res += 'k'; return res; } }; // JavaScript Code var generateTheString = function(n) { let ans = []; let state = n % 2 === 0 ? true : false; if(!state){ for(let i=0;i<n;i++){ ans.push('a'); } }else{ for(let i=0;i<n-1;i++){ ans.push('a'); } ans.push('k'); } return ans.join(''); };
Generate a String With Characters That Have Odd Counts
A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any&nbsp;two distinct critical points and maxDistance is the maximum distance between any&nbsp;two distinct critical points. If there are fewer than two critical points, return [-1, -1]. &nbsp; Example 1: Input: head = [3,1] Output: [-1,-1] Explanation: There are no critical points in [3,1]. Example 2: Input: head = [5,3,1,2,5,1,2] Output: [1,3] Explanation: There are three critical points: - [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. - [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. - [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. Example 3: Input: head = [1,3,2,2,3,2,2,2,7] Output: [3,3] Explanation: There are two critical points: - [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. - [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. Both the minimum and maximum distances are between the second and the fifth node. Thus, minDistance and maxDistance is 5 - 2 = 3. Note that the last node is not considered a local maxima because it does not have a next node. &nbsp; Constraints: The number of nodes in the list is in the range [2, 105]. 1 &lt;= Node.val &lt;= 105
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: idx, i = [], 1 prev, cur = head, head.next while cur and cur.next: if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val: idx.append(i) prev = cur cur = cur.next i += 1 if len(idx) < 2: return [-1, -1] minDist = min(j - i for i, j in pairwise(idx)) maxDist = idx[-1] - idx[0] return [minDist, maxDist]
class Solution { public int[] nodesBetweenCriticalPoints(ListNode head) { int res[]=new int[]{-1,-1}; if(head==null||head.next==null||head.next.next==null) return res; int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1; ListNode prev=head,ptr=head.next; int idx=1,minD=Integer.MAX_VALUE; while(ptr!=null&&ptr.next!=null){ if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val<prev.val&&ptr.val<ptr.next.val)){ if(idx<minidx) minidx=idx; lastidx=curridx; curridx=idx; if(lastidx!=-1&&curridx-lastidx<minD) minD=curridx-lastidx; } prev=ptr; ptr=ptr.next; idx++; } if(lastidx==-1) return res; else{ res[0]=minD; res[1]=curridx-minidx; } return res; } }
class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { if(!head or !head->next or !head->next->next) return {-1,-1}; int mini = 1e9; int prevInd = -1e9; int currInd = 0; int start = -1e9; int prev = head->val; head = head->next; while(head->next){ if(prev<head->val and head->next->val<head->val){ mini = min(mini,currInd-prevInd); prevInd = currInd; if(start==-1e9) start = currInd; } if(prev>head->val and head->next->val>head->val){ mini = min(mini,currInd-prevInd); prevInd = currInd; if(start==-1e9) start = currInd; } prev = head->val; head = head->next; currInd++; } if(start!=prevInd) return {mini,prevInd-start}; return {-1,-1}; } };
var nodesBetweenCriticalPoints = function(head) { const MAX = Number.MAX_SAFE_INTEGER; const MIN = Number.MIN_SAFE_INTEGER; let currNode = head.next; let prevVal = head.val; let minIdx = MAX; let maxIdx = MIN; let minDist = MAX; let maxDist = MIN; for (let i = 1; currNode.next != null; ++i) { const currVal = currNode.val; const nextNode = currNode.next; const nextVal = nextNode.val; // Triggers when we have either a maxima or a minima if ((prevVal < currVal && currVal > nextVal) || (prevVal > currVal && currVal < nextVal)) { if (maxIdx != MIN) minDist = Math.min(minDist, i - maxIdx); if (minIdx != MAX) maxDist = Math.max(maxDist, i - minIdx); if (minIdx == MAX) minIdx = i; maxIdx = i; } prevVal = currVal; currNode = nextNode; } const minRes = minDist === MAX ? -1 : minDist; const maxRes = maxDist === MIN ? -1 : maxDist; return [minRes, maxRes]; };
Find the Minimum and Maximum Number of Nodes Between Critical Points
Given a string s, return the longest palindromic substring in s. &nbsp; Example 1: Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consist of only digits and English letters.
class Solution: def longestPalindrome(self, s: str) -> str: res = "" for i in range(len(s)): left, right = i - 1, i + 1 while (right < len(s) and s[right] == s[i]): right += 1 while (0 <= left < right < len(s) and s[left] == s[right]): left, right = left - 1, right + 1 res = s[left+1:right] if right - left-1 > len(res) else res return res
class Solution { String max = ""; private void checkPalindrome(String s, int l, int r) { while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { if (r - l >= max.length()) { max = s.substring(l, r + 1); } l--; r++; } } public String longestPalindrome(String s) { for (int i = 0; i < s.length(); i++) { checkPalindrome(s, i, i); checkPalindrome(s, i, i + 1); } return max; } }
class Solution { public: string longestPalindrome(string s) { if(s.size() <= 1) return s; string longest = ""; for (int i = 0; i < s.size(); i++) { string sub1 = expand(s, i, i+1); string sub2 = expand(s, i, i); string sub3 = sub1.size() > sub2.size() ? sub1 : sub2; if(sub3.size() > longest.size()) { longest = sub3; } } return longest; } string expand(string s, int i, int j) { while(j < s.size() && i >= 0 && s[i] == s[j]) { i--; j++; } // Add 1 to i and subtract 1 from j because the range is expanded by 1 on each side before it ends return s.substr(i+1, j-i-1); } };
I solve the problem distinguishing two different cases. First I consider the case when the length of the palindrome to be found is odd (there is a center). I then expand the search to left and right from the possible found center. Then I consider the case when the length of the palindrome to be found is pair (there is no center/middle). I then expand the search to left and right from the possible palindrome having the form "xx". ```/** * @param {string} s * @return {string} */ var longestPalindrome = function(s) { let longestP = s[0]; let palindrome = ""; if(s.length === 1 ) return s; //the length of the palindrome is odd for(let index = 1; index < s.length-1; index++){ if(s[index - 1] === s[index + 1]){ palindrome = s[index - 1] + s[index] + s[index + 1]; for(let k = 1; index - 1 - k > -1 && index + 1 + k < s.length; k++){ if(s[index - 1 - k] === s[index + 1 + k]){ palindrome = s[index - 1 - k] + palindrome + s[index + 1 + k]; } else{ break; } } } if (palindrome.length > longestP.length){ longestP = palindrome; } palindrome = ""; } //the length of the palindrome is pair for(let index = 0; index < s.length-1; index++){ if(s[index] === s[index + 1]){ palindrome = s[index] + s[index + 1]; for(let k = 1; (index - k > -1) && (index + 1 + k < s.length); k++){ if(s[index - k] === s[index + 1 + k]){ palindrome = s[index - k] + palindrome + s[index + 1 + k]; } else{ break; } } } if (palindrome.length > longestP.length){ longestP = palindrome; } palindrome = ""; } return longestP; };`
Longest Palindromic Substring
Given an array of string words. Return all strings in words which is substring of another word in any order.&nbsp; String words[i] is substring of words[j],&nbsp;if&nbsp;can be obtained removing some characters to left and/or right side of words[j]. &nbsp; Example 1: Input: words = ["mass","as","hero","superhero"] Output: ["as","hero"] Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". ["hero","as"] is also a valid answer. Example 2: Input: words = ["leetcode","et","code"] Output: ["et","code"] Explanation: "et", "code" are substring of "leetcode". Example 3: Input: words = ["blue","green","bu"] Output: [] &nbsp; Constraints: 1 &lt;= words.length &lt;= 100 1 &lt;= words[i].length &lt;= 30 words[i] contains only lowercase English letters. It's guaranteed&nbsp;that words[i]&nbsp;will be unique.
class Solution: def stringMatching(self, words: List[str]) -> List[str]: ans=set() l=len(words) for i in range(l): for j in range(l): if (words[i] in words[j]) & (i!=j): ans.add(words[i]) return ans
class Solution { public List<String> stringMatching(String[] words) { List<String>ans = new ArrayList<>(); for(int i=0; i<words.length; i++){ String s = words[i]; for(int j=0; j<words.length; j++){ if(i == j){ continue; } if(words[j].indexOf(s) >= 0){ ans.add(s); break; } } } return ans; } }
class Solution { public: vector<string> stringMatching(vector<string>& words) { vector<string> res; //output for(int i = 0 ; i < words.size(); i++) { for(int j = 0; j < words.size(); j++) { if(i != j && words[j].find(words[i]) != -1) { if(!count(res.begin(),res.end(), words[i])) //if vector result does not include this string, push it to vector res.push_back(words[i]); else continue; //if vector result includes this string, ignore } } } return res; } };
var stringMatching = function(words) { let res = []; for (let i = 0; i < words.length; i++) { for (let j = 0; j < words.length; j++) { if (j === i) continue; if (words[j].includes(words[i])) { res.push(words[i]); break; } } } return res; };
String Matching in an Array
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: nums1[i] == nums2[j], and the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way. &nbsp; Example 1: Input: nums1 = [1,4,2], nums2 = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2. Example 2: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] Output: 3 Example 3: Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] Output: 2 &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 500 1 &lt;= nums1[i], nums2[j] &lt;= 2000
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: @lru_cache(None) def dp(a,b): if a>=len(nums1) or b>=len(nums2): return 0 if nums1[a]==nums2[b]: return 1+dp(a+1,b+1) else: return max(dp(a+1,b),dp(a,b+1)) return dp(0,0)
class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int[][] dp = new int[m + 1][n + 1]; for(int i = 1; i <= m; i ++){ for(int j = 1; j <= n; j ++){ if(nums1[i - 1] == nums2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } }
class Solution { public: int solve(int n1,int n2,vector<int>& nums1, vector<int>& nums2,vector<vector<int>> &dp) { if(n1<0 || n2<0) return 0; if(dp[n1][n2]!=-1) return dp[n1][n2]; if(nums1[n1]==nums2[n2]) return dp[n1][n2]=1+solve(n1-1,n2-1,nums1,nums2,dp); return dp[n1][n2]=max(solve(n1-1,n2,nums1,nums2,dp),solve(n1,n2-1,nums1,nums2,dp)); } int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) { int n1=nums1.size(),n2=nums2.size(); vector<vector<int>> dp(n1+1,vector<int>(n2+1,-1)); return solve(n1-1,n2-1,nums1,nums2,dp); } };
/** https://leetcode.com/problems/uncrossed-lines/ * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var maxUncrossedLines = function(nums1, nums2) { // Array to hold the combination of connected numbers let dp = []; // We look up the connected numbers with matrix for (let i=0;i< nums1.length;i++){ for (let j=0;j< nums2.length;j++){ if (nums1[i]===nums2[j]){ dp.push([i,j]); } } } // Only 0 or 1 connected numbers found, return if(dp.length <=1){ return dp.length; } // Array to count how many connected numbers in the matrix without crossing let count=Array(dp.length).fill(1); let out = count[0]; // Count from the last connected numbers, for each connected number, count how many other connected numbers in front of it that will not crossed with current for (let i=dp.length-2;i>=0;i--){ for (let j=i+1;j<dp.length;j++){ if (dp[i][0] < dp[j][0]&& dp[i][1] < dp[j][1]){ count[i] = Math.max(count[i],count[j]+1); out = Math.max(out, count[i]); } } } return out; };
Uncrossed Lines
You are given an integer array nums. In one move, you can pick an index i where 0 &lt;= i &lt; nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: nums = [1,2,2] Output: 1 Explanation: After 1 move, the array could be [1, 2, 3]. Example 2: Input: nums = [3,2,1,2,1,7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 105
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() c=0 i=1 num=[] while i<len(nums): if nums[i]<=nums[i-1]: a=nums[i-1]+1 c+=(a-nums[i]) nums[i]=a i+=1 return c
class Solution { public int minIncrementForUnique(int[] nums) { //Approach - 1 : Using a Count array // TC : O(N) // SC : O(N) int max = 0; for(int i : nums) max = Math.max(max, i); int count[] = new int[nums.length + max]; for(int c : nums) count[c]++; int answer = 0, choosen = 0; int len = count.length; for(int i = 0; i< len; i++) { if(count[i] >= 2) { choosen += count[i] - 1; answer -= i * (count[i] - 1); } else if(choosen > 0 && count[i] == 0) { answer += i; choosen--; } } return answer; //Approach - 2: // TC : O(nlogn) // SC : O(1) Arrays.sort(nums); int answer = 0; for(int i=1; i<nums.length; i++) { if(nums[i-1] >= nums[i]){ answer += nums[i-1]- nums[i] +1; nums[i] = nums[i-1] + 1; } } return answer; } }
class Solution { public: int minIncrementForUnique(vector<int>& nums) { int minElePossible=0,ans=0; sort(nums.begin(),nums.end()); for(int i=0;i<nums.size();i++){ if(nums[i]<minElePossible){ ans+=minElePossible-nums[i]; nums[i]+=minElePossible-nums[i]; } minElePossible=nums[i]+1; } return ans; } };
var minIncrementForUnique = function(nums) { let ans = 0, arr = nums.sort((a, b) => a - b); for (let i = 0; i < arr.length; i++) { if (arr[i] === arr[i + 1]) { arr[i + 1]++; ans++; } else if (arr[i] > arr[i + 1]) { if(arr[i] - arr[i - 1] === 1){ ans += arr[i] - arr[i + 1] + 1 arr[i + 1] += arr[i] - arr[i + 1] + 1; } } } return ans; };
Minimum Increment to Make Array Unique
An array arr a mountain if the following properties hold: arr.length &gt;= 3 There exists some i with 0 &lt; i &lt; arr.length - 1 such that: arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1] Given a mountain array arr, return the index i such that arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]. You must solve it in O(log(arr.length)) time complexity. &nbsp; Example 1: Input: arr = [0,1,0] Output: 1 Example 2: Input: arr = [0,2,1,0] Output: 1 Example 3: Input: arr = [0,10,5,2] Output: 1 &nbsp; Constraints: 3 &lt;= arr.length &lt;= 105 0 &lt;= arr[i] &lt;= 106 arr is guaranteed to be a mountain array.
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: beg = 0 end = len(arr)-1 while beg <= end: mid = (beg+end)//2 if arr[mid] < arr[mid+1]: beg = mid +1 elif arr[mid] > arr[mid+1]: end = mid -1 return beg
class Solution { public int peakIndexInMountainArray(int[] arr) { int start = 0; int end = arr.length - 1; while( start < end){ int mid = start + (end - start)/2; // if mid < mid next if(arr[mid] < arr[mid + 1]){ start = mid + 1; } // otherwise it can either peak element or greater element else{ end = mid; } } return start; // or we can return end also, bcz both will be on same value at the time, that's why loop breaks here. } }
class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { return max_element(arr.begin(), arr.end()) - arr.begin(); } };
var peakIndexInMountainArray = function(arr) { //lets assume we have peak it divides array in two parts // first part is increasing order , second part is decreasing // when we find the middle we'll compare arr[middle] > arr[middle+1], it means //we can only find max in first part of arr (increasing part) else second part. //there will be point where start === end that is our peak let start = 0; let end = arr.length -1; while(start < end){ let mid = parseInt(start + (end - start)/2) if( arr[mid] > arr[mid + 1]){ end = mid; }else { start = mid +1; } } return start; };
Peak Index in a Mountain Array
You are given a list of&nbsp;preferences&nbsp;for&nbsp;n&nbsp;friends, where n is always even. For each person i,&nbsp;preferences[i]&nbsp;contains&nbsp;a list of friends&nbsp;sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list.&nbsp;Friends in&nbsp;each list are&nbsp;denoted by integers from 0 to n-1. All the friends are divided into pairs.&nbsp;The pairings are&nbsp;given in a list&nbsp;pairs,&nbsp;where pairs[i] = [xi, yi] denotes xi&nbsp;is paired with yi and yi is paired with xi. However, this pairing may cause some of the friends to be unhappy.&nbsp;A friend x&nbsp;is unhappy if x&nbsp;is paired with y&nbsp;and there exists a friend u&nbsp;who&nbsp;is paired with v&nbsp;but: x&nbsp;prefers u&nbsp;over y,&nbsp;and u&nbsp;prefers x&nbsp;over v. Return the number of unhappy friends. &nbsp; Example 1: Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]] Output: 2 Explanation: Friend 1 is unhappy because: - 1 is paired with 0 but prefers 3 over 0, and - 3 prefers 1 over 2. Friend 3 is unhappy because: - 3 is paired with 2 but prefers 1 over 2, and - 1 prefers 3 over 0. Friends 0 and 2 are happy. Example 2: Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]] Output: 0 Explanation: Both friends 0 and 1 are happy. Example 3: Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]] Output: 4 &nbsp; Constraints: 2 &lt;= n &lt;= 500 n&nbsp;is even. preferences.length&nbsp;== n preferences[i].length&nbsp;== n - 1 0 &lt;= preferences[i][j] &lt;= n - 1 preferences[i]&nbsp;does not contain i. All values in&nbsp;preferences[i]&nbsp;are unique. pairs.length&nbsp;== n/2 pairs[i].length&nbsp;== 2 xi != yi 0 &lt;= xi, yi&nbsp;&lt;= n - 1 Each person is contained in exactly one pair.
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: dd = {} for i,x in pairs: dd[i] = preferences[i][:preferences[i].index(x)] dd[x] = preferences[x][:preferences[x].index(i)] ans = 0 for i in dd: for x in dd[i]: if i in dd[x]: ans += 1 break return ans
class Solution { public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { int[][] rankings = new int[n][n]; // smaller the value, higher the preference int[] pairedWith = new int[n]; for (int i = 0; i < n; i++) { for (int rank = 0; rank < n - 1; rank++) { int j = preferences[i][rank]; rankings[i][j] = rank; // person "i" views person "j" with rank } } int unhappy = 0; for (int[] pair : pairs) { int a = pair[0], b = pair[1]; pairedWith[a] = b; pairedWith[b] = a; } for (int a = 0; a < n; a++) { // "a" prefers someone else if (rankings[a][pairedWith[a]] != 0) { for (int b = 0; b < n; b++) { // "b" prefers to be with "a" over their current partner // "a" prefers to be with "b" over their current partner if (b != a && rankings[b][a] < rankings[b][pairedWith[b]] && rankings[a][b] < rankings[a][pairedWith[a]]) { unhappy++; break; } } } } return unhappy; } }
class Solution { public: bool check(int x , int y , int u , int v ,int n , vector<vector<int>>& pref){ int id_x = 0 , id_y = 0 , id_u = 0 , id_v = 0 ; //check indices of (y and u) in pref[x] ; for(int i = 0 ; i < n - 1; ++i ){ if(pref[x][i] == y) id_y = i ; if(pref[x][i] == u) id_u = i ; } //check indices of (v and x) in pref[u] ; for(int i = 0 ; i < n - 1 ; ++i ){ if(pref[u][i] == v) id_v = i ; if(pref[u][i] == x) id_x = i ; } return (id_x < id_v and id_u < id_y) ; } int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) { unordered_set<int> unhappy ; for(int i = 0 ; i < pairs.size() ; ++i ){ for(int j = i + 1; j < pairs.size() ; ++j){ int x = pairs[i][0] , y = pairs[i][1] , u = pairs[j][0] , v = pairs[j][1] ; // x prefers u over y and u preferes x over v if(check(x,y,u,v,n,preferences)) unhappy.insert(x), unhappy.insert(u) ; // x prefers v over y and v prefers x over u if(check(x,y,v,u,n,preferences)) unhappy.insert(x) , unhappy.insert(v) ; // y prefers u over x and u prefers y over v if(check(y,x,u,v,n,preferences)) unhappy.insert(y) , unhappy.insert(u) ; // y prefers v over x and v prefers y over u if(check(y,x,v,u,n,preferences)) unhappy.insert(y) , unhappy.insert(v) ; } } return unhappy.size() ; } };
var unhappyFriends = function(n, preferences, pairs) { let happyMap = new Array(n); for (let [i, j] of pairs) { happyMap[i] = preferences[i].indexOf(j); happyMap[j] = preferences[j].indexOf(i); } let unhappy = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < happyMap[i]; j++) { let partner = preferences[i][j]; if (preferences[partner].indexOf(i) < happyMap[partner]) { unhappy++; break; } } } return unhappy; };
Count Unhappy Friends
You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates. Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously. You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape. Return true if it is possible to escape regardless of how the ghosts move, otherwise return false. &nbsp; Example 1: Input: ghosts = [[1,0],[0,3]], target = [0,1] Output: true Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you. Example 2: Input: ghosts = [[1,0]], target = [2,0] Output: false Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination. Example 3: Input: ghosts = [[2,0]], target = [1,0] Output: false Explanation: The ghost can reach the target at the same time as you. &nbsp; Constraints: 1 &lt;= ghosts.length &lt;= 100 ghosts[i].length == 2 -104 &lt;= xi, yi &lt;= 104 There can be multiple ghosts in the same location. target.length == 2 -104 &lt;= xtarget, ytarget &lt;= 104
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: t = float('inf') tx, ty = target for i, j in ghosts: t = min(t, abs(tx - i) + abs(ty - j)) return t > abs(tx) + abs(ty)
// Escape The Ghosts // Leetcode: https://leetcode.com/problems/escape-the-ghosts/ class Solution { public boolean escapeGhosts(int[][] ghosts, int[] target) { int dist = Math.abs(target[0]) + Math.abs(target[1]); for (int[] ghost : ghosts) { if (Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]) <= dist) { return false; } } return true; } }
class Solution { public: bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) { int minimumstepsreqbyplayer = abs(target[0]) + abs(target[1]); int minimumstepsreqbyanyghost = INT_MAX; for(auto x: ghosts){ minimumstepsreqbyanyghost = min(minimumstepsreqbyanyghost, abs(x[0]-target[0]) + abs(x[1]-target[1])); } return minimumstepsreqbyplayer<minimumstepsreqbyanyghost; } };
var escapeGhosts = function(ghosts, target) { const getDistance = (target, source = [0, 0]) => { return ( Math.abs(target[0] - source[0]) + Math.abs(target[1] - source[1]) ); } const timeTakenByMe = getDistance(target); let timeTakenByGhosts = Infinity; for(let ghost of ghosts) { timeTakenByGhosts = Math.min(timeTakenByGhosts, getDistance(target, ghost)); } return timeTakenByGhosts > timeTakenByMe; };
Escape The Ghosts
Given an array nums of integers, return how many of them contain an even number of digits. &nbsp; Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits).&nbsp; 345 contains 3 digits (odd number of digits).&nbsp; 2 contains 1 digit (odd number of digits).&nbsp; 6 contains 1 digit (odd number of digits).&nbsp; 7896 contains 4 digits (even number of digits).&nbsp; Therefore only 12 and 7896 contain an even number of digits. Example 2: Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 500 1 &lt;= nums[i] &lt;= 105
class Solution: def findNumbers(self, nums: List[int]) -> int: even_count = 0 for elem in nums: if(len(str(elem))%2 == 0): even_count += 1 return even_count
class Solution { public int findNumbers(int[] nums) { int count = 0; for(int val : nums) { if((val>9 && val<100) || (val>999 && val<10000) || val==100000 ) count++; } return count; } }
class Solution { public: int findNumbers(vector<int>& nums) { int count = 0; for(auto it:nums) { int amount = 0; while(it>0) { amount++; it /= 10; } if (amount % 2 == 0) { count++; } } return count; } };
var findNumbers = function(nums) { let count = 0; for(let num of nums){ if(String(num).length % 2 === 0) count++ } return count; };
Find Numbers with Even Number of Digits
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Each element of nums is in exactly one pair, and The maximum pair sum is minimized. Return the minimized maximum pair sum after optimally pairing up the elements. &nbsp; Example 1: Input: nums = [3,5,2,3] Output: 7 Explanation: The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. Example 2: Input: nums = [3,5,4,2,4,6] Output: 8 Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. &nbsp; Constraints: n == nums.length 2 &lt;= n &lt;= 105 n is even. 1 &lt;= nums[i] &lt;= 105
class Solution: def minPairSum(self, nums: List[int]) -> int: pair_sum = [] nums.sort() for i in range(len(nums)//2): pair_sum.append(nums[i]+nums[len(nums)-i-1]) return max(pair_sum)
class Solution { public int minPairSum(int[] nums) { Arrays.sort(nums); int output = Integer.MIN_VALUE; //This is greedy, so n/2 pairs must be from start and end and move inwards for(int i=0, j=nums.length - 1; i<nums.length/2; i++, j--) { output = Math.max(output, nums[i] + nums[j]); } return output; } }
class Solution { public: int minPairSum(vector<int>& nums){ //sort the array sort(nums.begin(),nums.end()); int start=0,end=nums.size()-1,min_max_pair_sum=0; //Observe the pattern of taking the first and last element, second and second last element... and soo onn.. //would help you to minimize the maximum sum. while(start<end){ min_max_pair_sum=max(min_max_pair_sum,nums[start++]+nums[end--]); } return min_max_pair_sum; } };
/** * @param {number[]} nums * @return {number} */ var minPairSum = function(nums) { nums.sort((a,b) => a-b); let max = 0; for(let i=0; i<nums.length/2; i++){ max = Math.max(max , nums[i] + nums[nums.length-1-i]); } return max; };
Minimize Maximum Pair Sum in Array
You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts. For example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30. You are given two strings loginTime and logoutTime where: loginTime is the time you will login to the game, and logoutTime is the time you will logout from the game. If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime. Return the number of full chess rounds you have played in the tournament. Note:&nbsp;All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45. &nbsp; Example 1: Input: loginTime = "09:31", logoutTime = "10:14" Output: 1 Explanation: You played one full round from 09:45 to 10:00. You did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began. You did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended. Example 2: Input: loginTime = "21:30", logoutTime = "03:00" Output: 22 Explanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00. 10 + 12 = 22. &nbsp; Constraints: loginTime and logoutTime are in the format hh:mm. 00 &lt;= hh &lt;= 23 00 &lt;= mm &lt;= 59 loginTime and logoutTime are not equal.
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: hs, ms = (int(x) for x in startTime.split(":")) ts = 60 * hs + ms hf, mf = (int(x) for x in finishTime.split(":")) tf = 60 * hf + mf if 0 <= tf - ts < 15: return 0 # edge case return tf//15 - (ts+14)//15 + (ts>tf)*96
class Solution { public int numberOfRounds(String loginTime, String logoutTime) { String[] arr1 = loginTime.split(":"); String[] arr2 = logoutTime.split(":"); int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]); int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]); if(time1 > time2) time2 = time2 + 24*60; if(time1%15 != 0) time1 = time1 + 15-time1%15; return (time2 - time1)/15; } }
class Solution { public: int solve(string s) { int hour=stoi(s.substr(0,2)); int min=stoi(s.substr(3,5)); return hour*60+min; } int numberOfRounds(string loginTime, string logoutTime) { int st=solve(loginTime); int et=solve(logoutTime); int ans=0; if(st>et) et=et+1440; if(st%15!=0) st=st+(15-st%15); ans=(et-st)/15; return ans; } };
var numberOfRounds = function(loginTime, logoutTime) { const start = toMins(loginTime); const end = toMins(logoutTime); let roundStart = Math.ceil(start / 15); let roundEnd = Math.floor(end / 15); if (start < end) { return Math.max(0, roundEnd - roundStart); } else { roundEnd += 96; return roundEnd - roundStart; } function toMins(timeStr) { const [hh, mm] = timeStr.split(":"); let totMins = 0; totMins += parseInt(hh) * 60; totMins += parseInt(mm); return totMins; } };
The Number of Full Rounds You Have Played
Given a 2D&nbsp;grid consists of 0s (land)&nbsp;and 1s (water).&nbsp; An island is a maximal 4-directionally connected group of 0s and a closed island&nbsp;is an island totally&nbsp;(all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. &nbsp; Example 1: Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] Output: 1 Example 3: Input: grid = [[1,1,1,1,1,1,1], &nbsp; [1,0,0,0,0,0,1], &nbsp; [1,0,1,1,1,0,1], &nbsp; [1,0,1,0,1,0,1], &nbsp; [1,0,1,1,1,0,1], &nbsp; [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] Output: 2 &nbsp; Constraints: 1 &lt;= grid.length, grid[0].length &lt;= 100 0 &lt;= grid[i][j] &lt;=1
class Solution: '''主函数:计算封闭岛屿的数量''' def closedIsland(self, grid: List[List[int]]) -> int: result = 0 m, n = len(grid), len(grid[0]) self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]] # 遍历 grid,处理边缘陆地 for j in range(n): self.dfs(grid, 0, j) self.dfs(grid, m - 1, j) for i in range(m): self.dfs(grid, i, 0) self.dfs(grid, i, n - 1) # 剩下都是封闭岛屿,遍历找结果 for i in range(m): for j in range(n): if grid[i][j] == 0: result += 1 self.dfs(grid, i, j) return result '''从 (i, j) 开始,将与之相邻的陆地都变成海水''' def dfs(self, grid, i, j): m, n = len(grid), len(grid[0]) # 超出索引边界 if i < 0 or j < 0 or i >= m or j >= n: return # 已经是海水了 if grid[i][j] == 1: return # 变成海水 grid[i][j] = 1 for d in self.direction: x = i + d[0] y = j + d[1] self.dfs(grid, x, y)
class Solution { boolean isClosed = true; public int closedIsland(int[][] grid) { int m = grid.length; int n = grid[0].length; int count = 0; for(int i=1; i<m-1; i++){ for(int j=1; j<n-1; j++){ isClosed = true; if(grid[i][j] == 0){ dfs(grid, i, j); if(isClosed){ count++; } } } } return count; } public void dfs(int[][] grid, int i, int j){ if(i<0 || j<0 || i> grid.length-1 || j> grid[0].length-1 || grid[i][j] != 0) return; grid[i][j] = 1; // to mark as visited if(i == 0 || j == 0 || i == grid.length -1 || j == grid[0].length - 1) isClosed = false; dfs(grid, i, j+1); dfs(grid, i, j-1); dfs(grid, i+1, j); dfs(grid, i-1, j); } }
class Solution { public: bool isValid(int i,int j,vector<vector<int>>&grid) { if(i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 0) { return true; } return false; } void DFS(int i,int j,vector<vector<int>>&grid) { grid[i][j] = 1; if(isValid(i + 1,j,grid)) { DFS(i + 1,j,grid); } if(isValid(i - 1,j,grid)) { DFS(i - 1,j,grid); } if(isValid(i,j + 1,grid)) { DFS(i,j + 1,grid); } if(isValid(i,j - 1,grid)) { DFS(i,j - 1,grid); } } int closedIsland(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); for(int i = 0; i < m; i++) { int j = 0; if(grid[i][j] == 0) { DFS(i,j,grid); } j = n - 1; if(grid[i][j] == 0) { DFS(i,j,grid); } } for(int j = 0; j < n; j++) { int i = 0; if(grid[i][j] == 0) { DFS(i,j,grid); } i = m - 1; if(grid[i][j] == 0) { DFS(i,j,grid); } } int cnt = 0; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] == 0) { cnt++; DFS(i,j,grid); } } } return cnt; } };
/** * @param {number[][]} grid * @return {number} */ var closedIsland = function(grid) { let rows = grid.length; let cols = grid[0].length; let islandCount = 0; // Initial island count // For Quick Response if (rows <= 2 || cols <= 2) return islandCount; for (let i = 0; i <= rows - 1; i++) { for (let j = 0; j <= cols - 1; j++) { /* If land was found on the border, it can never be enclosed by water. So, mark the all the adjacent land across grid as visited. */ if (grid[i][j] === 0 && (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)) { dfs(i, j); } } } // If land is found, increase the count and walk around land(adjacent indexes) to mark them as visited. for (let i = 1; i <= rows - 1; i++) { for (let j = 1; j <= cols - 1; j++) { if (grid[i][j] === 0) { islandCount++; dfs(i, j); } } } // To walk around land and mark it as visited function dfs(x, y) { if (x < 0 || y < 0 || x >= rows || y >= cols) return; if (grid[x][y] !== 0) return; grid[x][y] = 2; dfs(x + 1, y); dfs(x, y + 1); dfs(x - 1, y); dfs(x, y - 1); } return islandCount; };
Number of Closed Islands
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. &nbsp; Example 1: Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. Example 2: Input: left = "1", right = "2" Output: 1 &nbsp; Constraints: 1 &lt;= left.length, right.length &lt;= 18 left and right consist of only digits. left and right cannot have leading zeros. left and right represent integers in the range [1, 1018 - 1]. left is less than or equal to right.
class Solution: def superpalindromesInRange(self, left: str, right: str) -> int: min_num, max_num = int(left), int(right) count, limit = 0, 20001 # odd pals for num in range(limit + 1): num_str = str(num) if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9: pal = num_str + num_str[:-1][::-1] num_sqr = int(pal) ** 2 if num_sqr > max_num: break if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]: count += 1 # even pals for num in range(limit + 1): num_str = str(num) if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9: pal = num_str + num_str[::-1] num_sqr = int(pal) ** 2 if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \ len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18: if num_sqr > max_num: break if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]: count += 1 return count
class Solution { public int superpalindromesInRange(String left, String right) { int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0; for (int dig = 1; dig < 10; dig++) { boolean isOdd = dig % 2 > 0 && dig != 1; int innerLen = (dig >> 1) - 1, innerLim = Math.max(1, (int)Math.pow(2, innerLen)), midPos = dig >> 1, midLim = isOdd ? 3 : 1; for (int edge = 1; edge < 3; edge++) { char[] pal = new char[dig]; Arrays.fill(pal, '0'); pal[0] = (char)(edge + 48); pal[dig-1] = (char)(edge + 48); if (edge == 2) { innerLim = 1; midLim = Math.min(midLim, 2); } for (int inner = 0; inner < innerLim; inner++) { if (inner > 0) { String innerStr = Integer.toString(inner, 2); while (innerStr.length() < innerLen) innerStr = "0" + innerStr; for (int i = 0; i < innerLen; i++) { pal[1+i] = innerStr.charAt(i); pal[dig-2-i] = innerStr.charAt(i); } } for (int mid = 0; mid < midLim; mid++) { if (isOdd) pal[midPos] = (char)(mid + 48); String palin = new String(pal); long square = Long.parseLong(palin) * Long.parseLong(palin); if (square > Long.parseLong(right)) return ans; if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++; } } } } return ans; } private boolean isPal(String str) { for (int i = 0, j = str.length() - 1; i < j; i++, j--) if (str.charAt(i) != str.charAt(j)) return false; return true; } }
class Solution { public: int superpalindromesInRange(string lef, string rig) { long L = stol(lef) , R = stol(rig); int magic = 100000 , ans = 0; string s = ""; for(int k = 1 ; k < magic ; k++){ s = to_string(k); for(int i = s.length() - 2 ; i >= 0; i--){ s += s.at(i); } long v = stol(s); v *= v; if(v > R) break; if(v >= L && isPalindrome(v)) ans++; } for(int k = 1 ; k < magic ; k++){ s = to_string(k); for(int i = s.length() - 1 ; i >= 0 ; i--){ s += s.at(i); } long v = stol(s); v *= v; if(v > R) break; if(v >= L && isPalindrome(v)) ans++; } return ans; } bool isPalindrome(long x){ return x == reverse(x); } long reverse(long x ){ long ans = 0; while(x > 0){ ans = 10 * ans + x % 10; x /= 10; } return ans; } };
var superpalindromesInRange = function(left, right) { let ans = 9 >= left && 9 <= right ? 1 : 0 const isPal = str => { for (let i = 0, j = str.length - 1; i < j; i++, j--) if (str.charAt(i) !== str.charAt(j)) return false return true } for (let dig = 1; dig < 10; dig++) { let isOdd = dig % 2 && dig !== 1, innerLen = (dig >> 1) - 1, innerLim = Math.max(1, 2 ** innerLen), midPos = dig >> 1, midLim = isOdd ? 3 : 1 for (let edge = 1; edge < 3; edge++) { let pal = new Uint8Array(dig) pal[0] = edge, pal[dig-1] = edge if (edge === 2) innerLim = 1, midLim = Math.min(midLim, 2) for (let inner = 0; inner < innerLim; inner++) { if (inner > 0) { let innerStr = inner.toString(2).padStart(innerLen, '0') for (let i = 0; i < innerLen; i++) pal[1+i] = innerStr[i], pal[dig-2-i] = innerStr[i] } for (let mid = 0; mid < midLim; mid++) { if (isOdd) pal[midPos] = mid let palin = ~~pal.join(""), square = BigInt(palin) * BigInt(palin) if (square > right) return ans if (square >= left && isPal(square.toString())) ans++ } } } } return ans };
Super Palindromes
Run-length encoding is a string compression method that works by&nbsp;replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string&nbsp;"aabccc"&nbsp;we replace "aa"&nbsp;by&nbsp;"a2"&nbsp;and replace "ccc"&nbsp;by&nbsp;"c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding&nbsp;'1'&nbsp;after single characters. Given a&nbsp;string s&nbsp;and an integer k. You need to delete at most&nbsp;k characters from&nbsp;s&nbsp;such that the run-length encoded version of s&nbsp;has minimum length. Find the minimum length of the run-length encoded&nbsp;version of s after deleting at most k characters. &nbsp; Example 1: Input: s = "aaabcccd", k = 2 Output: 4 Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. Example 2: Input: s = "aabbaa", k = 2 Output: 2 Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. Example 3: Input: s = "aaaaaaaaaaa", k = 0 Output: 3 Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3. &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 0 &lt;= k &lt;= s.length s contains only lowercase English letters.
class Solution: def getLengthOfOptimalCompression(self, s: str, k: int) -> int: # Find min lenth of the code starting from group ind, if there are res_k characters to delete and # group ind needs to be increased by carry_over additional characters def FindMinLen(ind, res_k, carry_over=0): # If we already found the min length - just retrieve it (-1 means we did not calculate it) if carry_over == 0 and dynamic[ind][res_k] != -1: return dynamic[ind][res_k] # Number of character occurences that we need to code. Includes carry-over. cur_count = carry_over + frequency[ind] # Min code length if the group ind stays intact. The code accounts for single-character "s0" vs. "s" situation. min_len = 1 + min(len(str(cur_count)), cur_count - 1) + FindMinLen(ind+1,res_k) # Min length if we keep only 0, 1, 9, or 99 characters in the group - delete the rest, if feasible for leave_count, code_count in [(0,0), (1, 1), (9, 2), (99, 3)]: if cur_count > leave_count and res_k >= cur_count - leave_count: min_len = min(min_len, code_count + FindMinLen(ind + 1,res_k - (cur_count - leave_count))) # If we drop characters between this character group and next group, like drop "a" in "bbbabb" next_ind = chars.find(chars[ind], ind + 1) delete_count = sum(frequency[ind+1:next_ind]) if next_ind > 0 and res_k >= delete_count: min_len = min(min_len, FindMinLen(next_ind, res_k - delete_count, carry_over = cur_count)) # If there was no carry-over, store the result if carry_over == 0: dynamic[ind][res_k] = min_len return min_len # Two auxiliary lists - character groups (drop repeated) and number of characters in the group frequency, chars = [], "" for char in s: if len(frequency)==0 or char != chars[-1]: frequency.append(0) chars = chars + char frequency[-1] += 1 # Table with the results. Number of character groups by number of available deletions. dynamic = [[-1] * (k + 1) for i in range(len(frequency))] + [[0]*(k + 1)] return FindMinLen(0, k)
class Solution { public int getLengthOfOptimalCompression(String s, int k) { Map<String, Integer> memo = new HashMap<>(); return recur(s, '\u0000', 0, k, 0, memo); } private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map<String, Integer> memo) { if (index == s.length()) { return 0; } String key = prevChar + ", " + prevCharCount + ", " + k + ", " + index; Integer keyVal = memo.get(key); if (keyVal != null) { return keyVal; } char ch = s.charAt(index); int count = 1; int nextIndex = index + 1; for (int i = index + 1; i < s.length(); i++) { if (s.charAt(i) == ch) { count++; nextIndex = i + 1; } else { nextIndex = i; break; } } int totalCount = count; int prevCountRepresentation = 0; //if prev char is equal to current char that means we have removed middle element //So we have to subtract the previous representation length and add the new encoding //representation length if (ch == prevChar) { totalCount += prevCharCount; prevCountRepresentation = getLength(prevCharCount); } int representaionLength = getLength(totalCount); int ans = representaionLength + recur(s, ch, totalCount, k, nextIndex, memo) - prevCountRepresentation; if (k > 0) { for (int i = 1; i <= k && i <= count; i++) { int currentCount = totalCount - i; int length = getLength(currentCount); //checking if we have to send current char and current char count or previous char //and previous char count int holder = length + recur(s, currentCount == 0 ? prevChar : ch, currentCount == 0 ? prevCharCount : currentCount, k - i, nextIndex, memo) - prevCountRepresentation; ans = Math.min(ans, holder); } } memo.put(key, ans); return ans; } //Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc. private int getLength(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else if (n < 10) { return 2; } else if (n < 100) { return 3; } else { return 4; } } }
class Solution { public: int dp[101][101]; int dfs(string &s, int left, int K) { int k = K; if(s.size() - left <= k) return 0; if(dp[left][k] >= 0) return dp[left][k]; int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1; for(int i = left + 1; i <= s.size(); ++i) { res = min(res, dfs(s, i, k) + 1 + (c >= 100 ? 3 : (c >= 10 ? 2 : (c > 1 ? 1 :0)))); if(i == s.size()) break; if(s[i] == s[left]) ++c; else if(--k < 0) break; } return dp[left][K] = res; } int getLengthOfOptimalCompression(string s, int k) { memset(dp, -1, sizeof(dp)); return dfs(s, 0, k); } };
var getLengthOfOptimalCompression = function(s, k) { const memo = new Map() const backtrack = (i, lastChar, lastCharCount, k) => { if (k < 0) return Number.POSITIVE_INFINITY if (i >= s.length) return 0 const memoKey = `${i}#${lastChar}#${lastCharCount}#${k}` if (memoKey in memo) return memo[memoKey] if (s[i] === lastChar) { const incrementor = [1, 9, 99].includes(lastCharCount) ? 1 : 0 memo[memoKey] = incrementor + backtrack(i+1, lastChar, lastCharCount+1, k) } else { memo[memoKey] = Math.min( 1 + backtrack(i+1, s[i], 1, k), //keep char backtrack(i+1, lastChar, lastCharCount, k-1) //delete char ) } return memo[memoKey] } return backtrack(0, '', 0, k) };
String Compression II
You may recall that an array arr is a mountain array if and only if: arr.length &gt;= 3 There exists some index i (0-indexed) with 0 &lt; i &lt; arr.length - 1 such that: arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1] Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array. &nbsp; Example 1: Input: nums = [1,3,1] Output: 0 Explanation: The array itself is a mountain array so we do not need to remove any elements. Example 2: Input: nums = [2,1,1,5,6,2,3,1] Output: 3 Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. &nbsp; Constraints: 3 &lt;= nums.length &lt;= 1000 1 &lt;= nums[i] &lt;= 109 It is guaranteed that you can make a mountain array out of nums.
class Solution: def minimumMountainRemovals(self, nums: List[int]) -> int: n = len(nums) inc = [0] * n dec = [0] * n # Longest Increasing Subsequence for i in range(1,n): for j in range(0,i): if nums[i] > nums[j]: inc[i] = max(inc[i], inc[j] + 1) # Longest Decreasing Subsequence for i in range(n-2,-1,-1): for j in range(n-1,i,-1): if nums[i] > nums[j]: dec[i] = max(dec[i], dec[j] + 1) # Final calculation res = 0 for i in range(0,n): if inc[i] > 0 and dec[i] > 0: res = max(res, inc[i] + dec[i]) # Final conclusion return n - res - 1
class Solution { public int minimumMountainRemovals(int[] nums) { int n = nums.length; int[] LIS = new int[n]; int[] LDS = new int[n]; Arrays.fill(LIS, 1); Arrays.fill(LDS, 1); // calculate the longest increase subsequence (LIS) for every index i for(int i=1 ; i < n ; i++) { for(int j = 0 ; j < i ; j++) { if(nums[i] > nums[j] && LIS[j]+1 > LIS[i]) LIS[i] = LIS[j]+1; } } // calculate the longest decreasing subsequence(LDS) for every index i and keep track of the maximum of LIS+LDS int max = 0; for(int i=n-2 ; i >= 0 ; i--) { for(int j = n-1 ; j > i ; j--) { if(nums[i] > nums[j] && LDS[j]+1 > LDS[i]) LDS[i] = LDS[j]+1; } if(LIS[i] > 1 && LDS[i] > 1) max = Math.max(LIS[i]+LDS[i]-1, max); } return n - max; } }
class Solution { public: int minimumMountainRemovals(vector<int>& nums) { int n = nums.size(); vector<int> dp1(n,1), dp2(n,1); // LIS from front for(int i=0; i<n; i++) { for(int j=0; j<i; j++) { if(nums[i] > nums[j] && 1 + dp1[j] > dp1[i]) { dp1[i] = 1 + dp1[j]; } } } //LIS from back for(int i=n-1; i>=0; i--) { for(int j=n-1; j>i; j--) { if(nums[i] > nums[j] && dp2[j] + 1 > dp2[i]){ dp2[i] = dp2[j] + 1; } } } int maxi = 1; for(int i=0; i<n; i++){ if(dp1[i] > 1 && dp2[i] > 1){ maxi = max(maxi, dp1[i] + dp2[i] -1); } } return (n-maxi); } };
var minimumMountainRemovals = function(nums) { let n=nums.length let previous=Array.from({length:n},item=>1) let previous2=Array.from({length:n},item=>1) //calcultaing left and right side LIS in single iteration for (let i=0;i<n;i++){ for (let j=0;j<i;j++){ //reverse indexes let i2=n-1-i let j2=n-1-j //calculating first dp serially if (nums[i]>nums[j] && previous[i]<previous[j]+1){ previous[i]=previous[j]+1 } //calculating second dp reversely if (nums[i2]>nums[j2] && previous2[i2]<previous2[j2]+1){ previous2[i2]=previous2[j2]+1 } } } let max=0 for (let i=0;i<n;i++){ //golden condition// to avoid only increasing and decreasing //because if a combination of 1 indicates its increasing fully or decreasing ! if (previous[i]>1 && previous2[i]>1){ //at a specific index highest increasing will come from left LIS // and highest decreasing will come from right side LIS max=Math.max(max,previous[i]+previous2[i]-1) } } return n-max //we need to remove the rest from total };
Minimum Number of Removals to Make Mountain Array
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial, completely removing it and any connections from this node to any other node. Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. &nbsp; Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1] Output: 1 Example 3: Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1] Output: 1 &nbsp; Constraints: n == graph.length n == graph[i].length 2 &lt;= n &lt;= 300 graph[i][j] is 0 or 1. graph[i][j] == graph[j][i] graph[i][i] == 1 1 &lt;= initial.length &lt;&nbsp;n 0 &lt;= initial[i] &lt;= n - 1 All the integers in initial are unique.
from collections import defaultdict from collections import deque class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: n = len(graph) G = defaultdict(list) for v in range(n): for w in range(n): if graph[v][w]: G[v].append(w) affect = defaultdict(list) for s in initial: visited = set([v for v in initial if v != s]) que = deque([s]) while que: v = que.popleft() if v in visited: continue visited.add(v) affect[v].append(s) for w in G[v]: que.append(w) res = [0]*n for v in affect: if len(affect[v]) == 1: res[affect[v].pop()] += 1 if not max(res): return min(initial) return res.index(max(res))
class Solution { int[] parent; int[] size; public int find(int x){ if(parent[x]==x) return x; int f = find(parent[x]); parent[x] = f; return f; } void merge(int x, int y){ if(size[x]>size[y]){ parent[y] = x; size[x] += size[y]; }else{ parent[x] =y; size[y] +=size[x]; } } public int minMalwareSpread(int[][] graph, int[] initial) { int n =graph.length; parent = new int[n]; size= new int[n]; // putting initially infected nodes in hashset to ignore them while making graph HashSet<Integer> hs = new HashSet<>(); for(int a : initial){ hs.add(a); } //initializing Parent for DSU for(int i=0;i<parent.length;i++){ parent[i] = i; size[i]=1; } //constructing groups DSU for(int i=0;i<graph.length;i++){ for(int j=0;j<graph[0].length;j++){ if(graph[i][j]==1 && !hs.contains(i) && !hs.contains(j)){ int p1 = find(i); int p2 = find(j); if(p1!=p2){ merge(p1,p2); //merging if they are not already } } } } //Storing initial Nodes vs parents of connected node...if there are multiple edge to same component then we will get the same parent twice ...so we will take hashset for that purpose. HashMap<Integer,HashSet<Integer>> map = new HashMap<>(); //We need to ensure increase the count whenever a parent is influenced by initial Nodes...because if it influenced by more than one infectious node then it would still remain infectious. int[] infected = new int[n]; for(int e: initial){ map.put(e,new HashSet<>()); for(int j=0;j<n;j++){ // in adjaceny graph[i][i] is always one so we will ignore that if(!hs.contains(j) && e!=j && graph[e][j]==1){ int p = find(j); if(!map.get(e).contains(p)){ map.get(e).add(p); infected[p]++; } } } } int max = -1; int ans =-1; for(int e:initial){ HashSet<Integer> par = map.get(e); int total =0; for(int p: par){ if(infected[p]==1){ //add to total only if influenced by only one infectious node. total+=size[p]; } } if(total>=max){ if(max==total){ ans = Math.min(ans,e); }else{ ans =e; } max =total; } } if(ans!=-1) return ans; //for returining smallest element. Arrays.sort(initial); return initial[0]; } }
class Solution { public: int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { sort(initial.begin(), initial.end()); int ans = -1, mn = INT_MAX, n = graph.size(); vector<vector<int>> new_graph(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(graph[i][j]) new_graph[i].push_back(j); for(auto &k : initial) { vector<int> dsu(n, -1); for(int i = 0; i < n; i++) for(auto &j : new_graph[i]) if(i != k && j != k) { int a = findParent(dsu, i), b = findParent(dsu, j); if(a != b) dsu[b] += dsu[a], dsu[a] = b; } vector<int> infected(n, 0); for(auto &i : initial) if(i != k) infected[findParent(dsu, i)]++; int total_infected = 0; for(int i = 0; i < n; i++) if(infected[i]) total_infected += abs(dsu[i]); if(total_infected < mn) mn = total_infected, ans = k; } return ans == -1 ? initial[0] : ans; } int findParent(vector<int> &dsu, int i) { int a = i; while(dsu[i] >= 0) i = dsu[i]; if(i != a) dsu[a] = i; return i; } };
var minMalwareSpread = function(graph, initial) { let n = graph.length let AdjList = new Map(); let listFromGraph = (mat) => {// convert adj matrix to adj list for(let i=0; i<n; i++){ AdjList[i] = []; for(let j=0; j<n; j++){ if(mat[i][j] === 1 && i!==j){ AdjList[i].push(j); } } } } listFromGraph(graph); let visitedSet = new Set();//visited set, to manage the visited nodes & their count as they are unique let dfs = (curr,node) => {// dfs helper, visit the graph assuming that node, given as 2nd parameter is deleted if(curr===node){ return; } if(visitedSet.has(curr)){ return; } visitedSet.add(curr);// size of visited shows how many nodes are visited/affected by the malware let neighbours = AdjList[curr]; for(let i in neighbours){// visit all the neighbours dfs(neighbours[i],node); } } let MinSpread = n;// min index of node with max reduction in malware let SpreadDist = n;// number of nodes affected by malware if MinSpread was deleted for(let i=0; i<initial.length; i++){ for(let j=0; j<initial.length; j++){// find the total nodes affected if ith node is removed dfs(initial[j],initial[i]); } if(SpreadDist == visitedSet.size){// to get min index but same impact MinSpread = Math.min(initial[i],MinSpread); } if(SpreadDist > visitedSet.size){// to get max impact MinSpread = initial[i]; SpreadDist = visitedSet.size; } visitedSet.clear();// clear visited set for next index to be deleted } return MinSpread; };
Minimize Malware Spread II
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes. Note: The bottom face of each shape counts toward its surface area. &nbsp; Example 1: Input: grid = [[1,2],[3,4]] Output: 34 Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 32 Example 3: Input: grid = [[2,2,2],[2,1,2],[2,2,2]] Output: 46 &nbsp; Constraints: n == grid.length == grid[i].length 1 &lt;= n &lt;= 50 0 &lt;= grid[i][j] &lt;= 50
class Solution: def surfaceArea(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) area = 0 for r in range(m): for c in range(n): if grid[r][c] != 0: area += 2 if r == 0 or r == m - 1: area += grid[r][c] if m != 1 else 2*grid[r][c] if r != m - 1: area += abs(grid[r][c] - grid[r+1][c]) if c == 0 or c == n - 1: area += grid[r][c] if n != 1 else 2*grid[r][c] if c != n - 1: area += abs(grid[r][c] - grid[r][c+1]) return area
class Solution { public int surfaceArea(int[][] grid) { int area = 0; int n = grid.length; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ // Adding the top part of grid if(i==0) area += grid[i][j]; else area += Math.abs(grid[i][j] - grid[i-1][j]); // Adding the left part of grid if(j==0) area += grid[i][j]; else area += Math.abs(grid[i][j] - grid[i][j-1]); // Adding bottom part of bottom-most cubes if(i == n-1) area += grid[i][j]; // Adding right part for right-most cubes if(j == n-1) area += grid[i][j]; // Add top and bottom surfaces if there is no hole in grid if(grid[i][j] != 0) area += 2; } } return area; } }
class Solution { public: int surfaceArea(vector<vector<int>>& grid) { int area = 0; for(int i = 0; i < grid.size(); i++) { for(int j = 0; j < grid[0].size(); j++) { //adding 4 sides area += grid[i][j]*4; //adding two because of there will only one top and one bottom if cube is placed upon each other if(grid[i][j] != 0) area+=2; //subtracting adjacent side area if any if(i-1 >= 0) area -= min(grid[i-1][j], grid[i][j]); if(i+1 < grid.size()) area -= min(grid[i+1][j], grid[i][j]); if(j-1 >= 0) area -= min(grid[i][j-1], grid[i][j]); if(j+1 < grid.size()) area -= min(grid[i][j+1], grid[i][j]); } } return area; } };
var surfaceArea = function(grid) { let cube=0, overlap=0; for(let i=0; i<grid.length; i++){ for(let j=0; j<grid[i].length; j++){ cube+=grid[i][j]; if(i>0){overlap+=Math.min(grid[i][j], grid[i-1][j]);} // x-direction if(j>0){overlap+=Math.min(grid[i][j], grid[i][j-1]);} // y-direction if(grid[i][j]>1){overlap+=grid[i][j]-1}; // z-direction } } return cube*6-overlap*2; };
Surface Area of 3D Shapes
You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total. For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4&nbsp;➝ 17 Transform #2: 17 ➝ 1 + 7 ➝ 8 Return the resulting integer after performing the operations described above. &nbsp; Example 1: Input: s = "iiii", k = 1 Output: 36 Explanation: The operations are as follows: - Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999 - Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36 Thus the resulting integer is 36. Example 2: Input: s = "leetcode", k = 2 Output: 6 Explanation: The operations are as follows: - Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545 - Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33 - Transform #2: 33 ➝ 3 + 3 ➝ 6 Thus the resulting integer is 6. Example 3: Input: s = "zbax", k = 2 Output: 8 &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 1 &lt;= k &lt;= 10 s consists of lowercase English letters.
class Solution: def getLucky(self, s: str, k: int) -> int: nums = [str(ord(c) - ord('a') + 1) for c in s] for _ in range(k): nums = str(sum(int(digit) for num in nums for digit in num)) return nums
class Solution { public int getLucky(String s, int k) { StringBuilder sb=new StringBuilder(); for(int i=0;i<s.length();i++) sb.append((s.charAt(i)-'a')+1); String result=sb.toString(); if(result.length()==1) return Character.getNumericValue(result.charAt(0)); int sum=0; while(k-->0 && result.length()>1) { sum=0; for(int i=0;i<result.length();i++) sum+=Character.getNumericValue(result.charAt(i)); result=String.valueOf(sum); } return sum; } }
class Solution { public: int getLucky(string s, int k) { long long sum=0,d; string convert; for(auto& ch: s) { convert+= to_string((ch-96)); } while(k--) { sum=0; for(auto& ch: convert) { sum+= (ch-48); } convert=to_string(sum); } return sum; } };
/** * @param {string} s * @param {number} k * @return {number} */ var getLucky = function(s, k) { function alphabetPosition(text) { var result = []; for (var i = 0; i < text.length; i++) { var code = text.toUpperCase().charCodeAt(i) if (code > 64 && code < 91) result.push(code - 64); } return result; } let str = alphabetPosition(s).join(""); let sum = 0; let newArr; while(k>0){ newArr = str.split(""); sum = newArr.reduce((acc, e) => parseInt(acc)+parseInt(e)); str = sum.toString(); k--; } return sum };
Sum of Digits of String After Convert
Given a non-negative integer x,&nbsp;compute and return the square root of x. Since the return type&nbsp;is an integer, the decimal digits are truncated, and only the integer part of the result&nbsp;is returned. Note:&nbsp;You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or&nbsp;x ** 0.5. &nbsp; Example 1: Input: x = 4 Output: 2 Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. &nbsp; Constraints: 0 &lt;= x &lt;= 231 - 1
class Solution: def mySqrt(self, x: int) -> int: beg =0 end =x while beg <=end: mid = (beg+end)//2 sqr = mid*mid if sqr == x: return mid elif sqr < x: beg = mid+1 else: end = mid-1 return end
class Solution { public int mySqrt(int x) { long answer = 0; while (answer * answer <= x) { answer += 1; } return (int)answer - 1; } }
class Solution { public: int mySqrt(int x) { int s = 0 , e = x , mid; while(s<e) { mid = s + (e-s)/2 ; if(e-s == 1) break ; long double sqr = (long double)mid *mid; if(sqr <= x) s = mid ; else e = mid - 1 ; } if(e*e <= x ) return e ; else return s ; } }; ```
/** * @param {number} x * @return {number} */ var mySqrt = function(x) { const numx = x; let num = 0; while (num <= x) { const avg = Math.floor((num+x) / 2); if (avg * avg > numx) x = avg - 1; else num = avg + 1; } return x; };
Sqrt(x)
Given a binary tree root and a&nbsp;linked list with&nbsp;head&nbsp;as the first node.&nbsp; Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree&nbsp;otherwise return False. In this context downward path means a path that starts at some node and goes downwards. &nbsp; Example 1: Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Explanation: Nodes in blue form a subpath in the binary Tree. Example 2: Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: true Example 3: Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output: false Explanation: There is no path in the binary tree that contains all the elements of the linked list from head. &nbsp; Constraints: The number of nodes in the tree will be in the range [1, 2500]. The number of nodes in the list will be in the range [1, 100]. 1 &lt;= Node.val&nbsp;&lt;= 100&nbsp;for each node in the linked list and binary tree.
class Solution(object): def isSubPath(self, head, root): if not root: return False if self.issame(head, root): return True return self.isSubPath(head, root.left) or self.isSubPath(head, root.right) def issame(self, head, root): if not head: return True if not root: return False if head.val != root.val: return False return self.issame(head.next, root.left) or self.issame(head.next, root.right)
class Solution { public boolean isSubPath(ListNode head, TreeNode root) { if(root == null) return false; if(issame(head, root)) return true; return isSubPath(head, root.left) || isSubPath(head, root.right); } private boolean issame(ListNode head, TreeNode root) { if(head == null) return true; if(root == null) return false; if(head.val != root.val) return false; return issame(head.next, root.left) || issame(head.next, root.right); } }
class Solution { public: bool func(ListNode *head,TreeNode *root){ if(!head) return true; if(!root) return false; if(head->val == root->val) return func(head->next,root->left) or func(head->next,root->right); return false; } bool isSubPath(ListNode* head, TreeNode* root) { if(!root) return false; if(func(head,root)) return true; return isSubPath(head,root->left) or isSubPath(head,root->right); } };
var isSubPath = function(head, root) { if(!root) return false if(issame(head, root)) return true return isSubPath(head, root.left) || isSubPath(head, root.right) }; function issame(head, root){ if(!head) return true if(!root) return false if(head.val != root.val) return false return issame(head.next, root.left) || issame(head.next, root.right) };
Linked List in Binary Tree
You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. &nbsp; Example 1: Input: s = "(abcd)" Output: "dcba" Example 2: Input: s = "(u(love)i)" Output: "iloveu" Explanation: The substring "love" is reversed first, then the whole string is reversed. Example 3: Input: s = "(ed(et(oc))el)" Output: "leetcode" Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. &nbsp; Constraints: 1 &lt;= s.length &lt;= 2000 s only contains lower case English characters and parentheses. It is guaranteed that all parentheses are balanced.
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] ans = "" res = deque([]) s = list(s) for i in s: if i==")": while stack[-1] != "(": res.append(stack.pop()) stack.pop() while res: stack.append(res.popleft()) else: stack.append(i) return "".join(stack)
class Solution { public String reverseParentheses(String s) { Stack<String> stack = new Stack<>(); int j = 0; while(j < s.length()){ /* We need to keep on adding whatever comes as long as it is not a ')'. */ if(s.charAt(j) != ')') stack.push(s.charAt(j)+""); /* Now that we have encountered an ')', its time to start popping from top of stack unless we find an opening parenthesis then we just need to reverse the string formed by popping and put it back on stack. Try dry running and it will all make sense */ else{ StringBuilder sb = new StringBuilder(); while(!stack.isEmpty() && !stack.peek().equals("(")){ sb.append(stack.pop()); } stack.pop(); stack.push(sb.reverse().toString()); } j++; } /* We have our result string in the stack now, we just need to pop it and return the reverse of it. */ StringBuilder res = new StringBuilder(); while(!stack.isEmpty()) res.append(stack.pop()); return res.reverse().toString(); } }
class Solution { public: string reverseParentheses(string s) { stack<int> st; for(int i=0;i<s.size();i++) { if(s[i]=='(') { st.push(i); } else if(s[i]==')') { int strt=st.top(); strt=strt+1; int end=i; reverse(s.begin()+strt,s.begin()+end); st.pop(); } } string ans=""; for(int i=0;i<s.size();i++) { if(s[i]=='(' || s[i]==')') { continue; } ans+=s[i]; } return ans; } };
function reverse(s){ return s.split("").reverse().join(""); } function solve(s,index) { let ans = ""; let j = index; while(j<s.length) { if(s[j] == '(') { let store = solve(s,j+1); ans += store.ans; j = store.j; } else if(s[j] == ')') return {ans : reverse(ans),j}; else ans+=s[j]; j++; } return ans; } var reverseParentheses = function(s) { return solve(s,0); };
Reverse Substrings Between Each Pair of Parentheses
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: PeekingIterator(Iterator&lt;int&gt; nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the array and moves the pointer to the next element. boolean hasNext() Returns true if there are still elements in the array. int peek() Returns the next element in the array without moving the pointer. Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions. &nbsp; Example 1: Input ["PeekingIterator", "next", "peek", "next", "next", "hasNext"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 2, 2, 3, false] Explanation PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,2,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 1 &lt;= nums[i] &lt;= 1000 All the calls to next and peek are valid. At most 1000 calls will be made to next, hasNext, and peek. &nbsp; Follow up: How would you extend your design to be generic and work with all types, not just integer?
class PeekingIterator: def __init__ (self,iterator): self.arr = iterator.v self._next = 0 self.is_has_next = True def next(self): val = self.arr[self._next] self.next+=1 if self.next >= len(self.arr): self.is_has_next = False return val def hasNext(self): return self.is_has_next def peek(self): return self.arr[self._next]
// Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { Queue<Integer> q; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. q= new LinkedList<>(); while(iterator.hasNext()) q.add(iterator.next()); } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { return q.peek(); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { return q.remove(); } @Override public boolean hasNext() { return q.size()!=0; } }
/* * Below is the interface for Iterator, which is already defined for you. * **DO NOT** modify the interface for Iterator. * * class Iterator { * struct Data; * Data* data; * public: * Iterator(const vector<int>& nums); * Iterator(const Iterator& iter); * * // Returns the next element in the iteration. * int next(); * * // Returns true if the iteration has more elements. * bool hasNext() const; * }; */ class PeekingIterator : public Iterator { public: int _nextVal; bool _hasNext; PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. _nextVal = 0; _hasNext = Iterator::hasNext(); if (_hasNext) _nextVal = Iterator::next(); } // Returns the next element in the iteration without advancing the iterator. int peek() { return (_nextVal); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { int tmp = _nextVal; _hasNext = Iterator::hasNext(); if (_hasNext) _nextVal = Iterator::next(); return (tmp); } bool hasNext() const { return (_hasNext); } };
var PeekingIterator = function(iterator) { this.iterator = iterator this.curr = iterator.next() }; PeekingIterator.prototype.peek = function() { return this.curr }; PeekingIterator.prototype.next = function() { let temp = this.curr this.curr = this.iterator.next() return temp }; PeekingIterator.prototype.hasNext = function() { return this.curr > 0 // the input iterator return -100000000 when next() after it run out of members, instead of return undefined. };
Peeking Iterator
There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7. Note that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street. &nbsp; Example 1: Input: n = 1 Output: 4 Explanation: Possible arrangements: 1. All plots are empty. 2. A house is placed on one side of the street. 3. A house is placed on the other side of the street. 4. Two houses are placed, one on each side of the street. Example 2: Input: n = 2 Output: 9 Explanation: The 9 possible arrangements are shown in the diagram above. &nbsp; Constraints: 1 &lt;= n &lt;= 104
class Solution: def countHousePlacements(self, n: int) -> int: @lru_cache(None) def rec(i, k): # i is the index of the house # k is the state of last house, 1 if there was a house on the last index else 0 if i>=n: return 1 elif k==0: return rec(i+1,1) + rec(i+1,0) else: return rec(i+1,0) #l1 are the combinations possible in lane 1, the final answer will be the square #of of l1 as for every combination of l1 there will be "l1" combinations in lane2. l1 = rec(1,0) + rec(1,1) mod = 10**9 +7 return pow(l1, 2, mod) #use this when there is mod involved along with power
class Solution { int mod = (int)1e9+7; public int countHousePlacements(int n) { if(n == 1) return 4; if(n == 2) return 9; long a = 2; long b = 3; if(n==1) return (int)(a%mod); if(n==2) return (int)(b%mod); long c=0; for(int i=3;i<=n;i++) { c = (a+b)%mod; a=b%mod; b=c%mod; } return (int)((c*c)%mod); } }
class Solution { public: typedef long long ll; ll mod = 1e9+7; int countHousePlacements(int n) { ll house=1, space=1; ll total = house+space; for(int i=2;i<=n;i++){ house = space; space = total; total = (house+space)%mod; } return (total*total)%mod; } };
const mod = (10 ** 9) + 7 var countHousePlacements = function(n) { let prev2 = 1 let prev1 = 1 let ways = 2 for ( let i = 2; i <= n; i++ ) { prev2 = prev1 prev1 = ways ways = ( prev1 + prev2 ) % mod } return (ways ** 2) % mod }
Count Number of Ways to Place Houses
You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: 0 represents grass, 1 represents fire, 2 represents a wall that you and fire cannot pass through. You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109. Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). &nbsp; Example 1: Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]] Output: 3 Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes. You will still be able to safely reach the safehouse. Staying for more than 3 minutes will not allow you to safely reach the safehouse. Example 2: Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]] Output: -1 Explanation: The figure above shows the scenario where you immediately move towards the safehouse. Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse. Thus, -1 is returned. Example 3: Input: grid = [[0,0,0],[2,2,0],[1,2,0]] Output: 1000000000 Explanation: The figure above shows the initial grid. Notice that the fire is contained by walls and you will always be able to safely reach the safehouse. Thus, 109 is returned. &nbsp; Constraints: m == grid.length n == grid[i].length 2 &lt;= m, n &lt;= 300 4 &lt;= m * n &lt;= 2 * 104 grid[i][j] is either 0, 1, or 2. grid[0][0] == grid[m - 1][n - 1] == 0
class Solution(object): def maximumMinutes(self, A): m, n = len(A), len(A[0]) inf = 10 ** 10 d = [[0,1],[1,0],[0,-1],[-1,0]] fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1] A = [[inf if a < 2 else -1 for a in r] for r in A] def bfs(queue, seen): for i, j, t in queue: if seen[i][j] < inf: continue seen[i][j] = t for di,dj in d: x, y = i + di, j + dj if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]: queue.append([x, y, t + 1]) def die(t): seen = [[inf + 10] * n for i in range(m)] bfs([[0, 0, t]], seen) return seen[-1][-1] > A[-1][-1] bfs(fires, A) A[-1][-1] += 1 return bisect_left(range(10**9 + 1), True, key=die) - 1
import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; class Solution { public boolean ok(int[][] grid, int[][] dist, int wait_time) { int n = grid.length; int m = grid[0].length; Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>(); Q.add(new Pair<>(0, 0, wait_time)); int[][] visited = new int[n][m]; visited[0][0] = 1; while (!Q.isEmpty()) { Pair<Integer, Integer, Integer> at = Q.poll(); int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int[] to : moves) { int ii = at.first + to[0]; int jj = at.second + to[1]; if (!inBounds(ii, jj, n, m) || visited[ii][jj] == 1 || grid[ii][jj] == 2) continue; if (ii == n - 1 && jj == m - 1 && dist[ii][jj] >= at.third + 1) return true; if (dist[ii][jj] <= at.third + 1) continue; Q.add(new Pair<>(ii, jj, 1 + at.third)); visited[ii][jj] = 1; } } return false; } public boolean inBounds(int i, int j, int n, int m) { return (0 <= i && i < n && 0 <= j && j < m); } public int maximumMinutes(int[][] grid) { int n = grid.length; int m = grid[0].length; int[][] dist = new int[n][m]; for (int[] r : dist) Arrays.fill(r, Integer.MAX_VALUE); Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { Q.add(new Pair<>(i, j, 0)); dist[i][j] = 0; } } } while (!Q.isEmpty()) { Pair<Integer, Integer, Integer> at = Q.poll(); int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int[] to : moves) { int ii = at.first + to[0]; int jj = at.second + to[1]; if (!inBounds(ii, jj, n, m) || grid[ii][jj] == 2 || dist[ii][jj] <= at.third + 1) continue; dist[ii][jj] = 1 + at.third; Q.add(new Pair<>(ii, jj, 1 + at.third)); } } int left = 0; int right = 1_000_000_000; int ans = -1; while (left <= right) { int mid = left + (right - left) / 2; if (ok(grid, dist, mid)) { ans = mid; left = mid + 1; } else right = mid - 1; } return ans; } static class Pair<T, K, L> { T first; K second; L third; public Pair(T first, K second, L third) { this.first = first; this.second = second; this.third = third; } } }
class Solution { public: int maximumMinutes(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> firetime(m, vector<int>(n, INT_MAX)); queue<pair<int, int>> q; // push fire positions into queue, and set the time as 0 for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]==1){ q.push(make_pair(i, j)); firetime[i][j] = 0; } } } int time = 0; pair<int, int> xy; int x,y; // use BFS to find fire spread time while(!q.empty()){ int points = q.size(); time++; for(int i=0; i<points; i++){ xy = q.front(); q.pop(); x = xy.first, y = xy.second; if(x-1>=0 && grid[x-1][y]==0 && firetime[x-1][y]==INT_MAX){ q.push(make_pair(x-1, y)); firetime[x-1][y] = time; } if(x+1<m && grid[x+1][y]==0 && firetime[x+1][y]==INT_MAX){ q.push(make_pair(x+1, y)); firetime[x+1][y] = time; } if(y-1>=0 && grid[x][y-1]==0 && firetime[x][y-1]==INT_MAX){ q.push(make_pair(x, y-1)); firetime[x][y-1] = time; } if(y+1<n && grid[x][y+1]==0 && firetime[x][y+1]==INT_MAX){ q.push(make_pair(x, y+1)); firetime[x][y+1] = time; } } } vector<vector<int>> peopletime(m, vector<int>(n, INT_MAX)); time = 0; // push the initial position of the top left cell into the queue // and set the time as 0 q.push(make_pair(0, 0)); peopletime[0][0] = 0; // use BFS to find the traversal time while(!q.empty()){ int points = q.size(); time++; for(int i=0; i<points; i++){ xy = q.front(); q.pop(); x = xy.first, y = xy.second; if(x-1>=0 && grid[x-1][y]==0 && peopletime[x-1][y]==INT_MAX && firetime[x-1][y]>time){ q.push(make_pair(x-1, y)); peopletime[x-1][y] = time; } if(x+1<m && grid[x+1][y]==0 && peopletime[x+1][y]==INT_MAX && firetime[x+1][y]>time){ q.push(make_pair(x+1, y)); peopletime[x+1][y] = time; } if(y-1>=0 && grid[x][y-1]==0 && peopletime[x][y-1]==INT_MAX && firetime[x][y-1]>time){ q.push(make_pair(x, y-1)); peopletime[x][y-1] = time; } if(y+1<n && grid[x][y+1]==0 && peopletime[x][y+1]==INT_MAX && firetime[x][y+1]>time){ q.push(make_pair(x, y+1)); peopletime[x][y+1] = time; } if(((x==m-2 && y==n-1) || (x==m-1 && y==n-2))&&(firetime[m-1][n-1]<=time)){ q.push(make_pair(m-1, n-1)); peopletime[m-1][n-1] = time; } } } // if you cannot reach the safehouse or fire reaches the safehouse first, // return -1 if(peopletime[m-1][n-1]==INT_MAX || firetime[m-1][n-1]<peopletime[m-1][n-1]){ return -1; } // if fire can never reach the safehouse, // return 1000000000 if(firetime[m-1][n-1]==INT_MAX){ return 1000000000; } if(firetime[m-1][n-1]==peopletime[m-1][n-1]){ return 0; } int diff = (firetime[m-1][n-1]-peopletime[m-1][n-1]); if(m>1 && n>1){ if(peopletime[m-2][n-1]!=INT_MAX && peopletime[m-1][n-2]!=INT_MAX && ((firetime[m-2][n-1]-peopletime[m-2][n-1])>diff || (firetime[m-1][n-2]-peopletime[m-1][n-2]>diff))){ return diff; } } return diff-1; } };
var maximumMinutes = function(grid) { let fireSpread = getFireSpreadTime(grid); let low = 0, high = 10 ** 9; while (low < high) { let mid = Math.ceil((low + high) / 2); if (canReachSafehouse(grid, fireSpread, mid)) low = mid; else high = mid - 1; } return canReachSafehouse(grid, fireSpread, low) ? low : -1; }; function canReachSafehouse(originalGrid, fireSpread, timeToWait) { const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; let grid = originalGrid.map((row) => [...row]); let m = grid.length, n = grid[0].length; let queue = [[0, 0]], time = timeToWait; while (queue.length) { for (let i = queue.length; i > 0; i--) { let [row, col] = queue.shift(); if (row === m - 1 && col === n - 1) { return true; } for (let [x, y] of directions) { let newX = row + x, newY = col + y; if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass let isTarget = newX === m - 1 && newY === n - 1; if ((isTarget && time + 1 <= fireSpread[newX][newY]) || time + 1 < fireSpread[newX][newY]) { // only visit if fire will not spread to new cell at the next minute grid[newX][newY] = 1; queue.push([newX, newY]); } } } time++; } return false; } function getFireSpreadTime(originalGrid) { const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; let grid = originalGrid.map((row) => [...row]); let m = grid.length, n = grid[0].length; let queue = []; for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { queue.push([i, j]); } } } let time = 0, fireSpread = Array(m).fill(0).map(() => Array(n).fill(Infinity)); while (queue.length) { for (let i = queue.length; i > 0; i--) { let [row, col] = queue.shift(); fireSpread[row][col] = time; for (let [x, y] of directions) { let newX = row + x, newY = col + y; if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass grid[newX][newY] = 1; queue.push([newX, newY]); } } time++; } return fireSpread; }
Escape the Spreading Fire
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given&nbsp;as a list of&nbsp;three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom. You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid. Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise. &nbsp; Example 1: Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"] Output: true Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1. There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed. Example 2: Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"] Output: false Explanation: The allowed triangular patterns are shown on the right. Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1. &nbsp; Constraints: 2 &lt;= bottom.length &lt;= 6 0 &lt;= allowed.length &lt;= 216 allowed[i].length == 3 The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}. All the values of allowed are unique.
class Solution(object): def pyramidTransition(self, bottom, allowed): """ :type bottom: str :type allowed: List[str] :rtype: bool """ dic = defaultdict(list) for i in allowed: dic[(i[0], i[1])].append(i[2]) res = [] def dfs(arr, nxt): #base case second floor and check top exists if len(arr) == 2 and dic[(arr[0], arr[1])]: return True #go to the next row now if len(arr) == len(nxt) + 1: return dfs(nxt, []) #keep iterating the same row if dic[(arr[len(nxt)], arr[len(nxt) + 1])]: for val in dic[(arr[len(nxt)], arr[len(nxt) + 1])]: if dfs(arr, nxt + [val]): return True return False return dfs(bottom, [])
class Solution { HashMap<String, List<Character>> map = new HashMap<>(); HashMap<String, Boolean> dp = new HashMap<>(); public boolean pyramidTransition(String bottom, List<String> allowed) { for(String s:allowed){ String sub = s.substring(0,2); char c = s.charAt(2); if(!map.containsKey(sub)) map.put(sub, new ArrayList<>()); map.get(sub).add(c); } return dfs(bottom, "", 0); } boolean dfs(String currBottom, String newBottom, int index){ if(currBottom.length()==1) return true; if(index+1>=currBottom.length()) return false; String sub = currBottom.substring(index,index+2); String state = currBottom+" "+newBottom+" "+index; if(dp.containsKey(state)) return dp.get(state); if(map.containsKey(sub)){ List<Character> letters = map.get(sub); for(char c:letters){ if(index==currBottom.length()-2){ if(dfs(newBottom+c, "", 0)) { dp.put(state, true); return true; } } else if(dfs(currBottom, newBottom+c, index+1)) { dp.put(state, true); return true; } } } dp.put(state, false); return false; } }
class Solution { unordered_map<string,vector<char> > m; public: bool dfs(string bot,int i,string tem){ if(bot.size()==1) return true; if(i==bot.size()-1) { string st; return dfs(tem,0,st); } for(auto v:m[bot.substr(i,2)]){ tem.push_back(v); if(dfs(bot,i+1,tem)){ return true; } tem.pop_back(); } return false; } bool pyramidTransition(string bottom, vector<string>& allowed) { for(auto a:allowed){ m[a.substr(0,2)].push_back(a[2]); } string te; return dfs(bottom,0,te); } };
var pyramidTransition = function(bottom, allowed) { const set = new Set(allowed); const memo = new Map(); const chars = ["A", "B", "C", "D", "E", "F"]; return topDown(bottom, bottom.length - 1); function topDown(prev, row) { const key = `${prev}#${row}`; if (row === 0) return true; if (memo.has(key)) return memo.get(key); let pats = new Set(); pats.add(""); for (let i = 0; i < row; i++) { const tmp = new Set(); const leftBot = prev.charAt(i); const rightBot = prev.charAt(i + 1); for (const char of chars) { const triadStr = leftBot + rightBot + char; if (set.has(triadStr)) { for (const pat of pats) { tmp.add(pat + char); } } } pats = tmp; } for (const pat of pats) { if (topDown(pat, row - 1)) return true; } memo.set(key, false); return false; } };
Pyramid Transition Matrix
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr. &nbsp; Example 1: Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6] Example 2: Input: n = 1 Output: 1 &nbsp; Constraints: 1 &lt;= n &lt;= 109
class Solution: def lastRemaining(self, n: int) -> int: beg = 1 len = n d = 1 fromleft = True while len > 1: if(fromleft or len%2 == 1): beg += d d <<= 1 len >>= 1 fromleft = not fromleft return beg
class Solution { public int lastRemaining(int n) { int head = 1; int remain = n; boolean left = true; int step =1; while(remain > 1){ if(left || remain%2==1){ head = head + step; } remain /= 2; step *= 2; left = !left; } return head; } }
class Solution { public: int lastRemaining(int n) { bool left=true; int head=1,step=1;//step is the difference between adjacent elements. while(n>1){ if(left || (n&1)){//(n&1)->odd head=head+step; } step=step*2; n=n/2; left=!left; } return head; } };
var lastRemaining = function(n) { let sum=1; let num=1; let bool=true; while(n>1){ if(bool){sum+=num; bool=false;} else{if(n%2){sum+=num;} bool=true;} num*=2; n=Math.floor(n/2); } return sum; };
Elimination Game
Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. &nbsp; Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3. Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. &nbsp; Constraints: The number of nodes in the list is in the range [1, 100]. 1 &lt;= Node.val &lt;= 100
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: # basically we create two pointers # move one pointer extra fast # another pointer would be slow # when fast reaches end slow would be in mid slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
class Solution { public ListNode middleNode(ListNode head) { ListNode temp = head; int size = 0; while(temp!=null){ size++; temp = temp.next; } int mid = size/2; temp = head; for(int i=0;i<mid;i++){ temp = temp.next; } return temp; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* middleNode(ListNode* head) { ListNode * slow=head; ListNode * fast=head; while(fast!=NULL && fast->next!=NULL){ slow=slow->next; fast=fast->next->next; } return slow; } };
var middleNode = function(head) { var runner1 = head var runner2 = head?.next while(runner1 && runner2) { runner1 = runner1?.next runner2 = (runner2?.next)?.next } return runner1 };
Middle of the Linked List
Design a food rating system that can do the following: Modify the rating of a food item listed in the system. Return the highest-rated food item for a type of cuisine in the system. Implement the FoodRatings class: FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. foods[i] is the name of the ith food, cuisines[i] is the type of cuisine of the ith food, and ratings[i] is the initial rating of the ith food. void changeRating(String food, int newRating) Changes the rating of the food item with the name food. String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. &nbsp; Example 1: Input ["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] [[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] Output [null, "kimchi", "ramen", null, "sushi", null, "ramen"] Explanation FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); foodRatings.highestRated("korean"); // return "kimchi" // "kimchi" is the highest rated korean food with a rating of 9. foodRatings.highestRated("japanese"); // return "ramen" // "ramen" is the highest rated japanese food with a rating of 14. foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. foodRatings.highestRated("japanese"); // return "sushi" // "sushi" is the highest rated japanese food with a rating of 16. foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. foodRatings.highestRated("japanese"); // return "ramen" // Both "sushi" and "ramen" have a rating of 16. // However, "ramen" is lexicographically smaller than "sushi". &nbsp; Constraints: 1 &lt;= n &lt;= 2 * 104 n == foods.length == cuisines.length == ratings.length 1 &lt;= foods[i].length, cuisines[i].length &lt;= 10 foods[i], cuisines[i] consist of lowercase English letters. 1 &lt;= ratings[i] &lt;= 108 All the strings in foods are distinct. food will be the name of a food item in the system across all calls to changeRating. cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated. At most 2 * 104 calls in total will be made to changeRating and highestRated.
from heapq import heapify, heappop, heappush class RatedFood: def __init__(self, rating, food): self.rating = rating self.food = food def __lt__(self, other): if other.rating == self.rating: return self.food < other.food return self.rating < other.rating class FoodRatings: def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): self.cuis_to_score_heap = defaultdict(list) self.food_to_latest_ratings = defaultdict(int) self.food_to_cuis = defaultdict(str) for food, cuis, rating in zip(foods, cuisines, ratings): self.food_to_cuis[food] = cuis self.food_to_latest_ratings[food] = rating heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food)) def changeRating(self, food: str, newRating: int) -> None: self.food_to_latest_ratings[food] = newRating cuis = self.food_to_cuis[food] heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food)) def highestRated(self, cuisine: str) -> str: while True: ratedFood = heappop(self.cuis_to_score_heap[cuisine]) if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating): # because the food item is still valid, we put it back into the heap heappush(self.cuis_to_score_heap[cuisine], ratedFood) return ratedFood.food
class FoodRatings { HashMap<String, TreeSet<String>> cuiToFood = new HashMap(); HashMap<String, Integer> foodToRat = new HashMap(); HashMap<String, String> foodToCui = new HashMap(); public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { for(int i = 0; i < foods.length; i++){ TreeSet<String> foodOfThisCuisine = cuiToFood.getOrDefault(cuisines[i], new TreeSet<String> ((a,b)-> foodToRat.get(a).equals(foodToRat.get(b)) ? a.compareTo(b) : foodToRat.get(b)-foodToRat.get(a))); // Both comparators are equal /* new Comparator<String>(){ @Override public int compare(String a, String b){ int aRat = foodToRat.get(a); int bRat = foodToRat.get(b); if(aRat != bRat) return bRat - aRat; // largest rating first for(int i = 0; i < Math.min(a.length(), b.length()); i++){ if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i); } return a.length() - b.length(); } }) */ foodToRat.put(foods[i], ratings[i]); foodOfThisCuisine.add(foods[i]); foodToCui.put(foods[i], cuisines[i]); cuiToFood.put(cuisines[i], foodOfThisCuisine); } } // CompareTo() is used to compare whether 2 strings are equal in hashSet! So remove, change value of key in HashMap, then insert again public void changeRating(String food, int newRating) { String cui = foodToCui.get(food); TreeSet<String> foodOfThisCui = cuiToFood.get(cui); foodOfThisCui.remove(food); foodToRat.put(food, newRating); foodOfThisCui.add(food); cuiToFood.put(cui, foodOfThisCui); } public String highestRated(String cuisine) { return cuiToFood.get(cuisine).first(); } }
class FoodRatings { public: unordered_map<string, set<pair<int, string>>> cuisine_ratings; unordered_map<string, string> food_cuisine; unordered_map<string, int> food_rating; FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) { for (int i = 0; i < foods.size(); ++i) { cuisine_ratings[cuisines[i]].insert({ -ratings[i], foods[i] }); food_cuisine[foods[i]] = cuisines[i]; food_rating[foods[i]] = ratings[i]; } } void changeRating(string food, int newRating) { auto &cuisine = food_cuisine.find(food)->second; cuisine_ratings[cuisine].erase({ -food_rating[food], food }); cuisine_ratings[cuisine].insert({ -newRating, food }); food_rating[food] = newRating; } string highestRated(string cuisine) { return begin(cuisine_ratings[cuisine])->second; } };
var FoodRatings = function(foods, cuisines, ratings) { this.heaps = {}, this.foods = {}; let n = foods.length; for (let i = 0; i < n; i++) { let food = foods[i], cuisine = cuisines[i], rating = ratings[i]; if (!this.heaps[cuisine]) this.heaps[cuisine] = new PriorityQueue((a, b) => { // [food, rating] return a[1] === b[1] ? a[0].localeCompare(b[0]) : b[1] - a[1]; }) this.heaps[cuisine].add([food, rating]); this.foods[food] = { cuisine, rating }; } }; FoodRatings.prototype.changeRating = function(food, newRating) { this.foods[food].rating = newRating; let { cuisine } = this.foods[food]; this.heaps[cuisine].add([food, newRating]); }; FoodRatings.prototype.highestRated = function(cuisine) { let heap = this.heaps[cuisine]; while (this.foods[heap.top()[0]].rating !== heap.top()[1]) { heap.remove(); } return heap.top()[0]; }; class PriorityQueue { constructor(comparator = ((a, b) => a - b)) { this.values = []; this.comparator = comparator; this.size = 0; } add(val) { this.size++; this.values.push(val); let idx = this.size - 1, parentIdx = Math.floor((idx - 1) / 2); while (parentIdx >= 0 && this.comparator(this.values[parentIdx], this.values[idx]) > 0) { [this.values[parentIdx], this.values[idx]] = [this.values[idx], this.values[parentIdx]]; idx = parentIdx; parentIdx = Math.floor((idx - 1) / 2); } } remove() { if (this.size === 0) return -1; this.size--; if (this.size === 0) return this.values.pop(); let removedVal = this.values[0]; this.values[0] = this.values.pop(); let idx = 0; while (idx < this.size && idx < Math.floor(this.size / 2)) { let leftIdx = idx * 2 + 1, rightIdx = idx * 2 + 2; if (rightIdx === this.size) { if (this.comparator(this.values[leftIdx], this.values[idx]) > 0) break; [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]]; idx = leftIdx; } else if (this.comparator(this.values[leftIdx], this.values[idx]) < 0 || this.comparator(this.values[rightIdx], this.values[idx]) < 0) { if (this.comparator(this.values[leftIdx], this.values[rightIdx]) <= 0) { [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]]; idx = leftIdx; } else { [this.values[rightIdx], this.values[idx]] = [this.values[idx], this.values[rightIdx]]; idx = rightIdx; } } else { break; } } return removedVal; } top() { return this.values[0]; } isEmpty() { return this.size === 0; } }
Design a Food Rating System
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.&nbsp; Each glass holds one cup&nbsp;of champagne. Then, some champagne is poured into the first glass at the top.&nbsp; When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.&nbsp; When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.&nbsp; (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.&nbsp; After two cups of champagne are poured, the two glasses on the second row are half full.&nbsp; After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.&nbsp; After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.) &nbsp; Example 1: Input: poured = 1, query_row = 1, query_glass = 1 Output: 0.00000 Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. Example 2: Input: poured = 2, query_row = 1, query_glass = 1 Output: 0.50000 Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. Example 3: Input: poured = 100000009, query_row = 33, query_glass = 17 Output: 1.00000 &nbsp; Constraints: 0 &lt;=&nbsp;poured &lt;= 109 0 &lt;= query_glass &lt;= query_row&nbsp;&lt; 100
class Solution: def champagneTower(self, poured: int, r: int, c: int) -> float: quantity=defaultdict(int) quantity[(0,0)]=poured for i in range(r+1): flag=False for j in range(i+1): prev_flow=quantity[(i,j)]-1 if prev_flow<=0: continue flag=True quantity[(i,j)]=1 quantity[(i+1,j)]+=prev_flow/2 quantity[(i+1,j+1)]+=prev_flow/2 if not flag: break return quantity[(r,c)]
// Champagne Tower // Leetcode: https://leetcode.com/problems/champagne-tower/ class Solution { public double champagneTower(int poured, int query_row, int query_glass) { if (poured == 0) return 0; double[] memo = new double[101]; memo[0] = poured; for (int i=0; i<100; i++) { for (int j=i; j>=0; j--) { if (memo[j] > 1) { if (i == query_row && j == query_glass) return 1; double val = (memo[j] - 1) / 2; memo[j+1] += val; memo[j] = val; } else { if (i == query_row && j == query_glass) return memo[query_glass]; memo[j+1] += 0; memo[j] = 0; } } } return memo[query_glass]; } }
class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { vector<double> currRow(1, poured); for(int i=0; i<=query_row; i++){ //we need to make the dp matrix only till query row. No need to do after that vector<double> nextRow(i+2, 0); //If we are at row 0, row 1 will have 2 glasses. So next row will have currRow number + 2 number of glasses. for(int j=0; j<=i; j++){ //each row will have currRow number + 1 number of glasses. if(currRow[j]>=1){ //if the champagne from the current glass is being overflowed. nextRow[j] += (currRow[j]-1)/2.0; //fill the left glass with the overflowing champagne nextRow[j+1] += (currRow[j]-1)/2.0; //fill the right glass with the overflowing champagne currRow[j] = 1; //current glass will store only 1 cup of champagne } } if(i!=query_row) currRow = nextRow; //change the currRow for the next iteration. But if we have already reached the query_row, then the next iteration will not even take place, so the currRow is the query_row itself. So don't change as we need the currRow only. } return currRow[query_glass]; } };
var champagneTower = function(poured, query_row, query_glass) { let water = [poured]; let hasOverflow = true; let row = 0; while(true){ if (! hasOverflow) return 0 // We haven't reached query_row yet, and water ran out hasOverflow = false; let rowGlass = Array(water.length).fill(0); // List of glasses at current row for (let i = 0; i < rowGlass.length; i++){ let input = water[i]; if (input <= 1){ rowGlass[i] = input; water[i] = 0 }else{ rowGlass[i] = 1; water[i]-- } if (row == query_row && i == query_glass){ // Return if we reach goal before water run out return rowGlass[i] } } // console.log('row,rowGlass',row,rowGlass); // to debug let nextWater = Array(water.length + 1).fill(0); // water poured towards next row, for (let i = 0; i < rowGlass.length; i++){ let overflow = water[i]; if (overflow > 0) hasOverflow = true; nextWater[i] += overflow / 2; nextWater[i+1] += overflow / 2; } water = nextWater; row ++; } };
Champagne Tower
Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent. &nbsp; Example 1: Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33. Example 2: Input: s = "jjjj", letter = "k" Output: 0 Explanation: The percentage of characters in s that equal the letter 'k' is 0%, so we return 0. &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s consists of lowercase English letters. letter is a lowercase English letter.
class Solution: def percentageLetter(self, s: str, letter: str) -> int: return (s.count(letter)*100)//len(s)
class Solution { public int percentageLetter(String str, char letter) { int count=0; int n=str.length(); for(int i=0;i<n;i++){ if(str.charAt(i)==letter){ count ++; } } int per= (100*count)/n; return per; } }
class Solution { public: int percentageLetter(string s, char letter) { int count=0; for(int i=0;i<s.length();i++) { if(s[i]==letter) { count++; } } return (count*100)/s.length(); } };
var percentageLetter = function(s, letter) { let count = 0; for (let i of s) { // count how many letters are in s if (i == letter) count++; } return (Math.floor((count*1.0) / (s.length*1.0) * 100)) // get percentage };
Percentage of Letter in String
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni &lt; positioni+1. speedi is the initial speed of the ith car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted. &nbsp; Example 1: Input: cars = [[1,2],[2,1],[4,3],[7,2]] Output: [1.00000,-1.00000,3.00000,-1.00000] Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. Example 2: Input: cars = [[3,4],[5,4],[6,3],[9,1]] Output: [2.00000,1.00000,1.50000,-1.00000] &nbsp; Constraints: 1 &lt;= cars.length &lt;= 105 1 &lt;= positioni, speedi &lt;= 106 positioni &lt; positioni+1
class Car: def __init__(self, pos, speed, idx, prev=None, next=None): self.pos = pos self.speed = speed self.idx = idx self.prev = prev self.next = next class Solution: def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: colis_times = [-1] * len(cars) cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)] for i in range(len(cars)-1): cars[i].next = cars[i+1] for i in range(1, len(cars)): cars[i].prev = cars[i-1] catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a) for i, (a, b) in enumerate(zip(cars, cars[1:])) if a.speed > b.speed] heapify(catchup_order) while catchup_order: catchup_time, idx, car = heappop(catchup_order) if colis_times[idx] > -1: continue # ith car has already caught up colis_times[idx] = catchup_time if not car.prev: continue # no car is following us car.prev.next, car.next.prev = car.next, car.prev if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed) heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev)) return colis_times
class Solution { public double[] getCollisionTimes(int[][] cars) { int n = cars.length; double[] res = new double[n]; Arrays.fill(res, -1.0); // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that // after catching c2, we may view c1 as non-existing (cars before c1 may not catches c1); /** Define a stack storing the index of cars as follows: Assuming cars c_0, c_1, c_2, ... , c_k are in the stack, they satisfy: 1. v0 > v1 > v2 ... > vk where v_i is the velocity of car c_i 2. c_(i+1) is the car that c_i vanishes into Namely, if only these cars exist, then what will happened is that c_0 vanishes into c_1, then c_1 vanishes into c_2, ..., c_(k-1) vanishes into c_k; */ Deque<Integer> stack = new LinkedList<>(); for (int i = n-1; i >= 0; i--) { int[] c1 = cars[i]; while (!stack.isEmpty()) { int j = stack.peekLast(); int[] c2 = cars[j]; /** If both conditions are satisfied: 1. c1 is faster than c2 2. c1 catches c2 before c2 vanishes into other car Then we know that c2 is the car that c1 catches first (i.e., c1 vanishes into c2) ==> get the result for c1 Note neither c1 nor c2 is polled out from the stack considering the rule of stack. */ if (c1[1] > c2[1] && (res[j] == -1.0 || catchTime(cars, i, j) <= res[j])) { res[i] = catchTime(cars, i, j); break; } /** Now we have either one of situations 1. c1 is slower than c2 2. c1 potentially catches c2 AFTER c2 vanishes Claim: no car before c1 will vanish into c2 1. ==> cars before c1 will vanish into c1 first before catching c2 2. <==> c2 "vanishes" into another car even before c1 catches it Either way, c2 can not be catched by c1 or cars beofre c1 ==> poll it out from stack */ stack.pollLast(); } stack.offerLast(i); } return res; } // time for cars[i] to catch cars[j] private double catchTime(int[][] cars, int i, int j) { int dist = cars[j][0] - cars[i][0]; int v = cars[i][1] - cars[j][1]; return (double)dist / v; } }
class Solution { public: vector<double> getCollisionTimes(vector<vector<int>>& cars) { int n = cars.size(); vector<double> res(n,-1.0); stack<int> st;// for storing indices for(int i=n-1;i>=0;i--) { //traversing from back if someone has greater speed and ahead of lesser speed car it will always be ahead while(!st.empty() && cars[st.top()][1]>= cars[i][1]) st.pop(); while(!st.empty()) // for lesser speed car ahead of greater spped car { double collision_time = (double)(cars[st.top()][0]-cars[i][0])/(cars[i][1]-cars[st.top()][1]); if(collision_time <=res[st.top()] || res[st.top()] == -1) { res[i] = collision_time; break; } st.pop(); } st.push(i); } return res; } };
var getCollisionTimes = function(cars) { // create a stack to hold all the indicies of the cars that can be hit const possibleCarsToHit = []; const result = new Array(cars.length).fill(-1); for (let i = cars.length - 1; i >= 0; i--) { // if there are cars to hit, check if the current car will hit the car before or after hitting // the car in front of them // you can also think of this as if the current car will hit the car before or after being absorbed by // the slower car in front. while (possibleCarsToHit.length && result[possibleCarsToHit[possibleCarsToHit.length - 1]] >= 0) { const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1]; const timeToCatchNextCar = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]); const timeToCatchNextNextCar = result[nextCarIndex]; if (timeToCatchNextCar > 0 && timeToCatchNextCar <= timeToCatchNextNextCar) { break; } // pop off the stack because the car was absorbed by the next car // before getting hit by the current car possibleCarsToHit.pop(); } if (possibleCarsToHit.length) { const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1]; result[i] = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]); } possibleCarsToHit.push(i); } return result; }; function getTimeToCatchNextCar(leftCar, rightCar) { const [leftCarPosition, leftCarSpeed] = leftCar const [rightCarPosition, rightCarSpeed] = rightCar; const distanceToCatchCar = rightCarPosition - leftCarPosition; const differenceInSpeed = leftCarSpeed - rightCarSpeed; return differenceInSpeed > 0 ? distanceToCatchCar / differenceInSpeed : -1; }
Car Fleet II
Given an integer array arr, return the length of a maximum size turbulent subarray of arr. A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if: For i &lt;= k &lt; j: arr[k] &gt; arr[k + 1] when k is odd, and arr[k] &lt; arr[k + 1] when k is even. Or, for i &lt;= k &lt; j: arr[k] &gt; arr[k + 1] when k is even, and arr[k] &lt; arr[k + 1] when k is odd. &nbsp; Example 1: Input: arr = [9,4,2,10,7,8,8,1,9] Output: 5 Explanation: arr[1] &gt; arr[2] &lt; arr[3] &gt; arr[4] &lt; arr[5] Example 2: Input: arr = [4,8,12,16] Output: 2 Example 3: Input: arr = [100] Output: 1 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 4 * 104 0 &lt;= arr[i] &lt;= 109
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: def cmp(a,b): if a == b: return 0 if a > b : return 1 return -1 n = len(arr) ans = 1 prev = 0 for i in range(1,n): c = cmp(arr[i-1],arr[i]) if c == 0: # we shift prev to i prev = i elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1: ans = ans if ans > i - prev + 1 else i - prev + 1 prev = i return ans
class Solution { public int maxTurbulenceSize(int[] arr) { if(arr.length == 1) { return 1; } int l = 0, r = 1; int diff = arr[l] - arr[r]; int max; if(diff == 0) { l = 1; r = 1; max = 1; } else { l = 0; r = 1; max = 2; } for(int i = 1; r < arr.length-1; i++) { int nextdiff = arr[i] - arr[i+1]; if(diff < 0) { if(nextdiff > 0) { r++; } else if(nextdiff == 0) { l = i+1; r = i+1; } else { l = i; r = i+1; } } else { if(nextdiff < 0) { r++; } else if(nextdiff == 0) { l = i+1; r = i+1; } else { l = i; r = i+1; } } diff = nextdiff; max = Math.max(max, r-l+1); } return max; } }
class Solution { public: int maxTurbulenceSize(vector<int>& arr) { vector<int> table1(arr.size(), 0); vector<int> table2(arr.size(), 0); table1[0] = 1; table2[0] = 1; int max_len = 1; for (int i=1; i<arr.size(); ++i) { table1[i] = 1; table2[i] = 1; if (arr[i] < arr[i - 1] && (i & 1) == 0) { table1[i] = table1[i - 1] + 1; } else if (arr[i] > arr[i - 1] && (i & 1) == 1) { table1[i] = table1[i - 1] + 1; } if (arr[i] > arr[i - 1] && (i & 1) == 0) { table2[i] = table2[i - 1] + 1; } else if (arr[i] < arr[i - 1] && (i & 1) == 1) { table2[i] = table2[i - 1] + 1; } max_len = max(max_len, table1[i]); max_len = max(max_len, table2[i]); } return max_len; } };
var maxTurbulenceSize = function(arr) { const len = arr.length; const dp = Array.from({ length: len + 1 }, () => { return new Array(2).fill(0); }); let ans = 0; for(let i = 1; i < len; i++) { if(arr[i-1] > arr[i]) { dp[i][0] = dp[i-1][1] + 1; } else if(arr[i-1] < arr[i]) { dp[i][1] = dp[i-1][0] + 1; } ans = Math.max(ans, ...dp[i]); } // console.log(dp); return ans + 1; };
Longest Turbulent Subarray
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: &nbsp; Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Output: [1,1] &nbsp; Constraints: 0 &lt;= rowIndex &lt;= 33 &nbsp; Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
class Solution: def getRow(self, rowIndex: int) -> List[int]: # base case # we know that there exist two base case one which is for zero input # One when we have to exit our recursive loop if rowIndex == 0: return [1] if rowIndex == 1: return [1,1] #recurance relation or prev call prev_prob = self.getRow(rowIndex-1) # post processing on data # if someone has given us prev_Row what operation we can perform to get current_Row return [1]+[prev_prob[i]+prev_prob[i-1] for i in range(1,len(prev_prob))]+[1]
class Solution { public List<Integer> getRow(int rowIndex) { List<List<Integer>> out = new ArrayList<>(); for(int i = 0; i<=rowIndex; i++){ List<Integer>in = new ArrayList<>(i+1); for(int j = 0 ; j<= i; j++){ if(j == 0 || j == i){ in.add(1); } else{ in.add(out.get(i-1).get(j-1) + out.get(i-1).get(j)); } } out.add(in); } return out.get(rowIndex); } }
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> ans(rowIndex+1,0); ans[0]=1; for(int i=1;i<rowIndex+1;i++){ for(int j=i;j>=1;j--){ ans[j]=ans[j]+ans[j-1]; } } return ans; } };
var getRow = function(rowIndex) { const triangle = []; for (let i = 0; i <= rowIndex; i++) { const rowValue = []; for (let j = 0; j < i + 1; j++) { if (j === 0 || j === i) { rowValue[j] = 1; } else { rowValue[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; } } triangle.push(rowValue) } return triangle[rowIndex]; };
Pascal's Triangle II
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). &nbsp; Example 1: Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9]. Example 2: Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] Output: 4 Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. Example 3: Input: matrix = [[1]] Output: 1 &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 200 0 &lt;= matrix[i][j] &lt;= 231 - 1
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: ROWS, COLS = len(matrix), len(matrix[0]) dp = {} def dfs(r, c, prevVal): if (r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal): return 0 if (r, c) in dp: return dp[(r, c)] res = 1 res = max(res, 1 + dfs(r + 1, c, matrix[r][c])) res = max(res, 1 + dfs(r - 1, c, matrix[r][c])) res = max(res, 1 + dfs(r, c + 1, matrix[r][c])) res = max(res, 1 + dfs(r, c - 1, matrix[r][c])) dp[(r, c)] = res return res for r in range(ROWS): for c in range(COLS): dfs(r, c, -1) return max(dp.values())
class Solution { public int longestIncreasingPath(int[][] matrix) { int[][] memo = new int[matrix.length][matrix[0].length]; int longestPath = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { dfs(matrix, i, j, memo); longestPath = Math.max(longestPath, memo[i][j]); } } return longestPath; } private void dfs(int[][] matrix, int i, int j, int[][] memo) { if (memo[i][j] != 0) return; int[][] dirs = {{-1,0}, {0,1}, {1,0}, {0,-1}}; int max = 0; for (int k = 0; k < dirs.length; k++) { int x = dirs[k][0] + i; int y = dirs[k][1] + j; if (isValid(matrix, x, y) && matrix[x][y] > matrix[i][j]) { // Get/compute the largest path for that index if (memo[x][y] == 0) { // If longest path doesn't exist for that path then compute it dfs(matrix, x, y, memo); } max = Math.max(max, memo[x][y]); } } memo[i][j] = 1 + max; } private boolean isValid(int[][] matrix, int i, int j) { if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length) return false; return true; } }
class Solution { public: // declare a dp int dp[205][205]; // direction coordinates of left, right, up, down vector<int> dx = {-1, 0, 1, 0}; vector<int> dy = {0, 1, 0, -1}; // dfs function int dfs(vector<vector<int>>& matrix, int i, int j, int n, int m) { // if value is already calculated for (i, j)th cell if(dp[i][j] != -1) return dp[i][j]; // take the maximum of longest increasing path from all four directions int maxi = 0; for(int k = 0; k < 4; k++) { int new_i = i + dx[k]; int new_j = j + dy[k]; if(new_i >= 0 && new_i < n && new_j >= 0 && new_j < m && matrix[new_i][new_j] > matrix[i][j]) { maxi = max(maxi, dfs(matrix, new_i, new_j, n, m)); } } // store the res and return it return dp[i][j] = 1 + maxi; } int longestIncreasingPath(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); // initialize dp with -1 memset(dp, -1, sizeof(dp)); // find the longest increasing path for each cell and take maximum of it int maxi = INT_MIN; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { int ans = dfs(matrix, i, j, n, m); maxi = max(maxi, ans); } } return maxi; } };
var longestIncreasingPath = function(matrix) { const m = matrix.length, n = matrix[0].length; const dp = new Array(m).fill(0).map(() => { return new Array(n).fill(-1); }); let ans = 0; const dir = [0, -1, 0, 1, 0]; const dfs = (x, y) => { if(dp[x][y] != -1) return dp[x][y]; for(let i = 1; i <= 4; i++) { const [nx, ny] = [x + dir[i], y + dir[i - 1]]; if( nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] > matrix[x][y] ) { dp[x][y] = Math.max(dp[x][y], 1 + dfs(nx, ny)); } } if(dp[x][y] == -1) dp[x][y] = 1; ans = Math.max(ans, dp[x][y]); return dp[x][y]; } for(let i = 0; i < m; i++) { for(let j = 0; j < n; j++) { if(dp[i][j] == -1) dfs(i, j); } } return ans; };
Longest Increasing Path in a Matrix
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: i + minJump &lt;= j &lt;= min(i + maxJump, s.length - 1), and s[j] == '0'. Return true if you can reach index s.length - 1 in s, or false otherwise. &nbsp; Example 1: Input: s = "011010", minJump = 2, maxJump = 3 Output: true Explanation: In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. Example 2: Input: s = "01101110", minJump = 2, maxJump = 3 Output: false &nbsp; Constraints: 2 &lt;= s.length &lt;= 105 s[i] is either '0' or '1'. s[0] == '0' 1 &lt;= minJump &lt;= maxJump &lt; s.length
class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: # dp[i] represents whether i is reachable dp = [False for _ in s] dp[0] = True for i in range(1, len(s)): if s[i] == "1": continue # iterate through the solutions in range [i - maxJump, i - minJump] # and if any previous spot in range is reachable, then i is also reachable window_start = max(0, i - maxJump) window_end = i - minJump for j in range(window_start, window_end + 1): if dp[j]: dp[i] = True break return dp[-1]
class Solution { public boolean canReach(String s, int minJump, int maxJump) { if(s.charAt(s.length() - 1) != '0') return false; Queue<Integer> queue = new LinkedList<>(); queue.add(0); // This variable tells us till which index we have processed int maxReach = 0; while(!queue.isEmpty()){ int idx = queue.remove(); // If we reached the last index if(idx == s.length() - 1) return true; // start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)] for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){ if(s.charAt(j) == '0') queue.add(j); } // since we have processed till idx + maxJump so update maxReach to next index maxReach = Math.min(idx + maxJump + 1, s.length() - 1); } return false; } }
class Solution { public: bool canReach(string s, int minJump, int maxJump) { int n = s.length(); if(s[n-1]!='0') return false; int i = 0; queue<int> q; q.push(0); int curr_max = 0; while(!q.empty()){ i = q.front(); q.pop(); if(i == n-1) return true; for(int j = max(i + minJump, curr_max); j <= min(i + maxJump, n - 1); j++){ if(s[j] == '0') q.push(j); } curr_max = min(i+maxJump+1, n); } return false; } };
var canReach = function(s, minJump, maxJump) { const validIdxs = [0]; for (let i = 0; i < s.length; i++) { // skip if character is a 1 or if all the // valid indicies are too close if (s[i] === '1' || i - validIdxs[0] < minJump) { continue; } // remove all the indexes that are too far while (validIdxs.length && i - validIdxs[0] > maxJump) { validIdxs.shift(); } if (validIdxs.length === 0) { return false; } validIdxs.push(i); // if we are at the last index // return if we have an index within range if (i === s.length - 1) { return i - validIdxs[0] >= minJump; } } // if the last character is a 1 we must return False return false; };
Jump Game VII
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules. &nbsp; Example 1: Input ["TopVotedCandidate", "q", "q", "q", "q", "q", "q"] [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]] Output [null, 0, 1, 1, 0, 0, 1] Explanation TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 &nbsp; Constraints: 1 &lt;= persons.length &lt;= 5000 times.length == persons.length 0 &lt;= persons[i] &lt; persons.length 0 &lt;= times[i] &lt;= 109 times is sorted in a strictly increasing order. times[0] &lt;= t &lt;= 109 At most 104 calls will be made to q.
class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): counter = defaultdict(int) mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i] largestVote = -1 # keep largest vote person index for i in range(len(persons)): counter[persons[i]] += 1 if largestVote == -1 or counter[persons[i]] >= counter[largestVote]: largestVote = persons[i] mostVotePersons[i] = largestVote self.times = times self.mostVotePersons = mostVotePersons def q(self, t: int) -> int: idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t return self.mostVotePersons[idx]
class TopVotedCandidate { int[] persons; int[] times; int length; Map<Integer, Integer> voteCount; Map<Integer, Integer> voteLead; public TopVotedCandidate(int[] persons, int[] times) { this.persons = persons; this.times = times; length = times.length-1; int leadCount = 0; int leadPerson = -1; voteCount = new HashMap<>(); voteLead = new HashMap<>(); for(int i=0; i<=length; i++){ int newCount = voteCount.getOrDefault(persons[i], 0) + 1; voteCount.put(persons[i], newCount); if(newCount >= leadCount){ leadCount = newCount; leadPerson = persons[i]; } voteLead.put(times[i], leadPerson); } } public int q(int t) { int leadPerson = -1; if(voteLead.containsKey(t)) { leadPerson = voteLead.get(t); } else if(t < times[0]){ leadPerson = voteLead.get(times[0]); } else if(t > times[length]){ leadPerson = voteLead.get(times[length]); } else { int low = 0; int high = length; while(low <= high){ int mid = low + (high-low)/2; if(times[mid] > t) high = mid - 1; else low = mid + 1; } leadPerson = voteLead.get(times[high]); } return leadPerson; } }
class TopVotedCandidate { public: vector<int> pref; vector<int> glob_times; TopVotedCandidate(vector<int>& persons, vector<int>& times) { int n = times.size(); glob_times = times; pref.resize(n); vector<int> cnt; int sz = persons.size(); cnt.resize(sz+1, 0); cnt[persons[0]]++; pref[0] = persons[0]; int maxi = 1; int maxi_person = persons[0]; for(int i = 1; i < n; i++){ cnt[persons[i]]++; if(cnt[persons[i]] > maxi){ maxi = cnt[persons[i]]; maxi_person = persons[i]; } else if(cnt[persons[i]] == maxi){ maxi_person = persons[i]; } pref[i] = maxi_person; } } int q(int t) { int it = upper_bound(glob_times.begin(), glob_times.end(), t) - glob_times.begin(); if(it == 0) it++; return pref[it-1]; } }; /** * Your TopVotedCandidate object will be instantiated and called as such: * TopVotedCandidate* obj = new TopVotedCandidate(persons, times); * int param_1 = obj->q(t); */
var TopVotedCandidate = function(persons, times) { this.times = times; this.len = times.length; this.votes = new Array(this.len).fill(0); let max = 0; // max votes received by any single candidate so far. let leader = -1l; this.leaders = persons.map((person, i) => { this.votes[person]++; if (this.votes[person] >= max) { max = this.votes[person]; leader = person; } return leader; }); }; TopVotedCandidate.prototype.q = function(t) { let left = 0; let right = this.len - 1; while (left <= right) { const mid = left + Math.floor((right - left) / 2); if (this.times[mid] === t) return this.leaders[mid]; else if (this.times[mid] < t) left = mid + 1; else right = mid - 1; } return this.leaders[right]; };
Online Election
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. &nbsp; Example 1: Input: nums = [21,4,7] Output: 32 Explanation: 21 has 4 divisors: 1, 3, 7, 21 4 has 3 divisors: 1, 2, 4 7 has 2 divisors: 1, 7 The answer is the sum of divisors of 21 only. Example 2: Input: nums = [21,21] Output: 64 Example 3: Input: nums = [1,2,3,4,5] Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 1 &lt;= nums[i] &lt;= 105
import math class Solution: def sumFourDivisors(self, nums: List[int]) -> int: s=0 for i in nums: r=i+1 c=2 for j in range(2, int(math.sqrt(i))+1): if i%j==0: if (i / j == j) : c+=1 r+=j else : c+=2 r+=j+int(i/j) print(c, r) if c==4: s+=r return s
class Solution { public int sumFourDivisors(int[] nums) { int res = 0; for(int val : nums){ int sum = 0; int count = 0; for(int i=1;i*i <= val;i++){ if(val % i == 0){ sum += i; count++; if(i != val/i){ sum += val/i; count++; } } } if(count == 4){ res += sum; } } return res; } }
class Solution { public: int sumFourDivisors(vector<int>& nums) { int n = nums.size(); int sum = 0,cnt=0,temp=0; for(int i=0;i<n;i++){ int x = nums[i]; int sq = sqrt(x); for(int j=1;j<=sq;j++){ if(x%j==0){ cnt+=2; temp += (j+x/j); if(j==x/j){ cnt--; temp-=j; } if(cnt>4) break; } } if(cnt==4){ sum += temp; } temp=0; cnt=0; } return sum; } };
var sumFourDivisors = function(nums) { let check = (num) => { let divs = [num]; // init the array with the number itself let orig = num; num = num >> 1; // divide in half to avoid checking too many numbers while (num > 0) { if (orig % num === 0) divs.push(num); num--; if (divs.length > 4) return 0; } if (divs.length === 4) { return divs.reduce((a, b) => a + b, 0); } return 0; } let total = 0; for (let num of nums) { total += check(num); } return total; };
Four Divisors
You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. &nbsp; Example 1: Input: num = 310 Output: 103 Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. The arrangement with the smallest value that does not contain any leading zeros is 103. Example 2: Input: num = -7605 Output: -7650 Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567. The arrangement with the smallest value that does not contain any leading zeros is -7650. &nbsp; Constraints: -1015 &lt;= num &lt;= 1015
class Solution: def smallestNumber(self, num: int) -> int: lst=[i for i in str(num)] if num<0: return ''.join(['-'] + sorted(lst[1:],reverse=True)) lst=sorted(lst) if '0' in lst: itr=0 while itr<len(lst) and lst[itr]=='0': itr+=1 if itr==len(lst): #All zeroes return ''.join(lst) return ''.join([lst[itr]]+lst[:itr]+lst[itr+1:]) return ''.join(lst)
class Solution { public long smallestNumber(long num) { if(num == 0){ return 0; } boolean isNegative = num < 0; num = num < 0 ? num * -1 : num; char[] c = String.valueOf(num).toCharArray(); Arrays.sort(c); String str; if(!isNegative){ int non = 0; //if not negative we need to find out the first non-leading zero then swap with first zero for(; non < c.length; non++){ if(c[non] != '0'){ break; } } char temp = c[non]; c[non] = c[0]; c[0] = temp; str = new String(c); }else{ str = new String(c); StringBuilder sb = new StringBuilder(str); str = "-".concat(sb.reverse().toString()); } return Long.valueOf(str); } }
class Solution { public: long long smallestNumber(long long num) { if (num < 0) { string s = to_string(-num); sort(s.rbegin(), s.rend()); return -stoll(s); } else if (num == 0) return 0; string s = to_string(num); sort(s.begin(), s.end()); int i = 0; while (s[i] == '0') i++; char c = s[i]; s.erase(s.begin() + i); s = c + s; return stoll(s); } };
var smallestNumber = function(num) { let arr = Array.from(String(num)); if(num>0){ arr.sort((a,b)=>{ return a-b; }) } else{ arr.sort((a,b)=>{ return b-a; }) } for(let i=0;i<arr.length;i++){ if(arr[i]!=0){ [arr[0],arr[i]]=[arr[i],arr[0]]; break; } } return arr.join(""); };
Smallest Value of the Rearranged Number
An&nbsp;integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers&nbsp;in the range [low, high]&nbsp;inclusive that have sequential digits. &nbsp; Example 1: Input: low = 100, high = 300 Output: [123,234] Example 2: Input: low = 1000, high = 13000 Output: [1234,2345,3456,4567,5678,6789,12345] &nbsp; Constraints: 10 &lt;= low &lt;= high &lt;= 10^9
class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: l = len(str(low)) h = len(str(high)) ans = [] for i in range(l,h+1): for j in range(1,11-i): t = str(j) for k in range(i-1): t+=str(int(t[-1])+1) if int(t)<=high and int(t)>=low: ans.append(int(t)) ans.sort() return ans
class Solution { public List<Integer> sequentialDigits(int low, int high) { int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length(); List<Integer> output = new ArrayList<>(); for(int size=lowSize; size<=highSize; size++) { int seedNumber = getSeedNumber(size); int increment = getIncrement(size); int limit = (int)Math.pow(10,size); // System.out.println(seedNumber+":"+increment+":"+limit); while(true){ if(seedNumber>=low && seedNumber<=high) output.add(seedNumber); if(seedNumber%10==9 || seedNumber>high) break; seedNumber+=increment; } } return output; } private int getSeedNumber(int size) { int seed = 1; for(int i=2;i<=size;i++) seed=10*seed + i; return seed; } private int getIncrement(int size) { int increment = 1; for(int i=2;i<=size;i++) increment=10*increment + 1; return increment; } }
class Solution { public: vector<int> sequentialDigits(int low, int high) { string lf = to_string(low); string rt = to_string(high); vector<int> ans; for(int i = lf.size(); i <= rt.size(); i++){ // 字符串长度 for(int st = 1; st <= 9; st++){ string base(i, '0'); // "000000" i个0 for(int j = 0; j < i; j++){ base[j] += st + j; } if(base.back() <= '9'){ int num = stoi(base); if(low <= num && num <= high){ ans.push_back(num); } } } } return ans; } };
var sequentialDigits = function(low, high) { const digits = '123456789'; const ans = []; const minLen = low.toString().length; const maxLen = high.toString().length; for (let windowSize = minLen; windowSize <= maxLen; ++windowSize) { for (let i = 0; i + windowSize <= digits.length; ++i) { const num = parseInt(digits.substring(i, i + windowSize)); if (num >= low && num <= high) { ans.push(num); } } } return ans; };
Sequential Digits
You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name. Note: Uppercase letters come before lowercase letters in lexicographical order. "Alice" and "alice" are distinct. &nbsp; Example 1: Input: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"] Output: "Alice" Explanation: Alice sends a total of 2 + 3 = 5 words. userTwo sends a total of 2 words. userThree sends a total of 3 words. Since Alice has the largest word count, we return "Alice". Example 2: Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"] Output: "Charlie" Explanation: Bob sends a total of 5 words. Charlie sends a total of 5 words. Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie. &nbsp; Constraints: n == messages.length == senders.length 1 &lt;= n &lt;= 104 1 &lt;= messages[i].length &lt;= 100 1 &lt;= senders[i].length &lt;= 10 messages[i] consists of uppercase and lowercase English letters and ' '. All the words in messages[i] are separated by a single space. messages[i] does not have leading or trailing spaces. senders[i] consists of uppercase and lowercase English letters only.
class Solution: def largestWordCount(self, messages: List[str], senders: List[str]) -> str: d={} l=[] for i in range(len(messages)): if senders[i] not in d: d[senders[i]]=len(messages[i].split()) else: d[senders[i]]+=len(messages[i].split()) x=max(d.values()) for k,v in d.items(): if v==x : l.append(k) if len(l)==1: return l[0] else: l=sorted(l)[::-1] #Lexigograhical sorting of list return l[0]
class Solution { public String largestWordCount(String[] messages, String[] senders) { HashMap<String,Integer> hm=new HashMap<>(); int max=0; String name=""; for(int i=0;i<messages.length;i++){ String[] words=messages[i].split(" "); int freq=hm.getOrDefault(senders[i],0)+words.length; hm.put(senders[i],freq); if(hm.get(senders[i])>max){ max=hm.get(senders[i]); name=senders[i]; } else if(hm.get(senders[i])==max && name.compareTo(senders[i])<0){ name=senders[i]; } } return name; } }
class Solution { public: string largestWordCount(vector<string>& messages, vector<string>& senders) { int n(size(messages)); map<string, int> m; for (auto i=0; i<n; i++) { stringstream ss(messages[i]); string word; int count(0); while (ss >> word) count++; m[senders[i]] += count; } int count(0); string res; for (auto& p : m) { if (p.second >= count) { count = p.second; if (!res.empty() or res < p.first) res = p.first; } } return res; } };
/** * @param {string[]} messages * @param {string[]} senders * @return {string} */ var largestWordCount = function(messages, senders) { let wordCount = {} let result = '' let maxCount = -Infinity for (let i = 0; i < messages.length;i++) { let count=messages[i].split(' ').length wordCount[senders[i]] = wordCount[senders[i]] == undefined ? count : wordCount[senders[i]] + count; if (wordCount[senders[i]] > maxCount || (wordCount[senders[i]] == maxCount && senders[i] > result)) { maxCount = wordCount[senders[i]]; result = senders[i]; } } return result; };
Sender With Largest Word Count
Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. The test cases are generated so that the answer fits in 32-bit integer. &nbsp; Example 1: Input: nums = [2,4,6,8,10] Output: 7 Explanation: All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] Example 2: Input: nums = [7,7,7,7,7] Output: 16 Explanation: Any subsequence of this array is arithmetic. &nbsp; Constraints: 1&nbsp; &lt;= nums.length &lt;= 1000 -231 &lt;= nums[i] &lt;= 231 - 1
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0 for i in range(1, sz): for j in range(i): difference = nums[i] - nums[j] dp[i][difference] += 1 if difference in dp[j]: dp[i][difference] += dp[j][difference] ans += dp[j][difference] return ans
class Solution { public int numberOfArithmeticSlices(int[] nums) { int n=nums.length; HashMap<Integer,Integer> []dp=new HashMap[n]; for(int i=0;i<n;i++){ dp[i]=new HashMap<Integer,Integer>(); } int ans=0; for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ long cd=(long)nums[i]-(long)nums[j]; if(cd<=Integer.MIN_VALUE || cd>=Integer.MAX_VALUE){ continue; } int endingAtj=dp[j].getOrDefault((int)cd,0); int endingAti=dp[i].getOrDefault((int)cd,0); ans+=endingAtj; dp[i].put((int)cd,endingAtj+endingAti+1); } } return ans; } }
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { int n=nums.size(),ans=0; unordered_map<long long, unordered_map<int,int>> ma; // [diff, [index, count]] unordered_map<int,int> k; for(int i=1;i<n;i++) { for(int j=0;j<i;j++) { long long diff= (long long)nums[i]-(long long)nums[j]; if(ma.find(diff)==ma.end()) ma[diff]= k; if(ma[diff].find(j)==ma[diff].end()) ma[diff][j]=0; ma[diff][i] += ma[diff][j] + 1; ans += ma[diff][j]; } } return ans; } };
/** * @param {number[]} nums * @return {number} */ var numberOfArithmeticSlices = function(nums) { let dp = new Array(nums.length); for(let i = 0; i < nums.length; i++) { dp[i] = new Map(); } let ans = 0; for(let j = 1; j < nums.length; j++) { for(let i = 0; i < j; i++) { let commonDifference = nums[j] - nums[i]; if ((commonDifference > (Math.pow(2, 31) - 1)) || commonDifference < (-Math.pow(2, 31))) { continue; } let apsEndingAtI = dp[i].get(commonDifference) || 0 let apsEndingAtJ = dp[j].get(commonDifference) || 0 dp[j].set(commonDifference, (apsEndingAtI + apsEndingAtJ + 1)); ans += apsEndingAtI; } } return ans; };
Arithmetic Slices II - Subsequence
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. &nbsp; Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5] Example 2: Input: head = [2,1], x = 2 Output: [1,2] &nbsp; Constraints: The number of nodes in the list is in the range [0, 200]. -100 &lt;= Node.val &lt;= 100 -200 &lt;= x &lt;= 200
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ lessthan = [] greateql = [] while head: if head.val < x: lessthan.append(head.val) else: greateql.append(head.val) head = head.next h = res = ListNode() for i in range(len(lessthan)): res.next = ListNode(lessthan[i]) res = res.next for i in range(len(greateql)): res.next = ListNode(greateql[i]) res = res.next return h.next
class Solution { public ListNode partition(ListNode head, int x) { ListNode left = new ListNode(0); ListNode right = new ListNode(0); ListNode leftTail = left; ListNode rightTail = right; while(head != null){ if(head.val < x){ leftTail.next = head; leftTail = leftTail.next; } else{ rightTail.next = head; rightTail = rightTail.next; } head = head.next; } leftTail.next = right.next; rightTail.next = null; return left.next; } }
class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode *left = new ListNode(0); ListNode *right = new ListNode(0); ListNode *leftTail = left; ListNode *rightTail = right; while(head != NULL){ if(head->val < x){ leftTail->next = head; leftTail = leftTail->next; } else{ rightTail->next = head; rightTail = rightTail->next; } head = head->next; } leftTail->next = right->next; rightTail->next = NULL; return left->next; } };
var partition = function(head, x) { if (!head) { return head; } const less = []; const greater = []; let concat; rec(head); return head; function rec(currentNode) { if (currentNode.val < x) { less.push(currentNode.val); } else { greater.push(currentNode.val); } if (!currentNode.next) { concat = [...less, ...greater]; currentNode.val = concat.pop(); return; } rec(currentNode.next); currentNode.val = concat.pop(); } };
Partition List
Given an m x n matrix, return&nbsp;true&nbsp;if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. &nbsp; Example 1: Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] Output: true Explanation: In the above grid, the&nbsp;diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True. Example 2: Input: matrix = [[1,2],[2,2]] Output: false Explanation: The diagonal "[1, 2]" has different elements. &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 20 0 &lt;= matrix[i][j] &lt;= 99 &nbsp; Follow up: What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? What if the matrix is so large that you can only load up a partial row into the memory at once?
########################################################################################### # Number of rows(M) x expected numbers(N) # Space: O(N) # We need to store the expected numbers in list ############################################################################################ class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: # Validate Input if not matrix or not matrix[0]: return False # Create a deque tracking the expected values for the next row expected = matrix[0] # We only care about the elements before last element expected.pop() # From the second row, pop out the last element of the expected numbers and compare it with the target row[1:] for row in matrix[1:]: # Compare row with expected numbers, invalidate it as soon as we find the numbers are not the same (O(N)) if row[1:] != expected: return False else: # Pop the last element from row, use it as the expected numbers for the next iteration row.pop() expected = row # If we've reached here, all diagonals aligned return True
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; for(int i = 0; i < m; i++){ int row = 0; int col = i; int e = matrix[row++][col++]; while(row < n && col< m){ if(e == matrix[row][col]){ row++; col++; }else{ return false; } } } for(int r = 1; r < n; r++){ int row = r; int col = 0; int e =matrix[row++][col++]; while(row < n && col < m){ if(e == matrix[row][col]){ row++; col++; }else{ return false; } } } return true; } }
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) if (matrix[i][j] != matrix[i - 1][j - 1]) return false; return true; } };
var isToeplitzMatrix = function(matrix) { for (let i=0; i < matrix.length-1; i++) { for (let j=0; j < matrix[i].length-1; j++) { if (matrix[i][j] !== matrix[i+1][j+1]) { return false } } } return true };
Toeplitz Matrix