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
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you can replace it with "01". For example, "00010" -> "00001" Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.   Example 1: Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011" Example 2: Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further.   Constraints: 1 <= binary.length <= 105 binary consist of '0' and '1'.
class Solution: def maximumBinaryString(self, binary: str) -> str: zero = binary.count('0') # count number of '0' zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's) return f"{binary[:zero_idx]}{'1'*(zero-1)}{'0'*min(zero, 1)}{'1'*one}"
class Solution { public String maximumBinaryString(String binary) { int n = binary.length(); StringBuffer ans = new StringBuffer(""); StringBuffer buffer = new StringBuffer(""); int onesAfter1stZero = 0; boolean found1stZero = false; for(int i=0;i<n;i++){ if(found1stZero){ if(binary.charAt(i)=='0') ans.append('1'); else buffer.append('1'); } else{ if(binary.charAt(i)=='0'){ found1stZero = true; buffer.append('0'); } else ans.append('1'); } } ans.append(buffer); return ans.toString(); } }
class Solution { public: string maximumBinaryString(string binary) { int n = binary.size(); int z_count=0; //count the number of zeros int z_index=-1; //index of the leftmost zero that is why we start iterating from the right for(int i=n-1;i>=0;i--) { if(binary[i]=='0') { z_count++; z_index = i; binary[i] = '1'; //changing all occurances to 1 } } if(z_index!=-1) //to check if there is atleast 1 zero { binary[z_index+z_count-1] = '0'; //this is the only zero present // -1 because the only zero is also included in zero count } return binary; } };
/** * @param {string} binary * @return {string} */ var maximumBinaryString = function(binary) { /* 10 -> 01 allows us to move any zero to left by one position 00 -> 10 allows us to convert any consicutive 00 to 10 So we can collect all the zeros together then convert them in 1 except for the rightmost 0 We will club all the zeros togegher on the rightmost possition, to achieve the biggest value, then covert them into 1 except for the rightmost 0 So we need to choose indexOfFirstZero as the starting possition of the group of zeros If there is no 0 then given string is the maximum possible string If there are 1 or more zeros Then there will be only 1 zero in the answer Position of this will be indexOfFirstZero in given string + countOfZeros - 1 */ let firstZeroIndex=-1,zeroCount=0,ans=""; for(let i=0;i<binary.length;i++){ if(binary[i]==='0'){ zeroCount++; if(firstZeroIndex===-1){ firstZeroIndex=i; } } } if(firstZeroIndex==-1){ return binary; } let onlyZeroInAns = firstZeroIndex + (zeroCount-1); for(let i=0;i<binary.length;i++){ if(i==onlyZeroInAns){ ans+="0"; } else{ ans+="1"; } } return ans; };
Maximum Binary String After Change
Given an array of non-negative integers arr, you are initially positioned at start&nbsp;index of the array. When you are at index i, you can jump&nbsp;to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. &nbsp; Example 1: Input: arr = [4,2,3,0,3,1,2], start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -&gt; index 4 -&gt; index 1 -&gt; index 3 index 5 -&gt; index 6 -&gt; index 4 -&gt; index 1 -&gt; index 3 Example 2: Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -&gt; index 4 -&gt; index 1 -&gt; index 3 Example 3: Input: arr = [3,0,2,1,2], start = 2 Output: false Explanation: There is no way to reach at index 1 with value 0. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 5 * 104 0 &lt;= arr[i] &lt;&nbsp;arr.length 0 &lt;= start &lt; arr.length
class Solution: def canReach(self, arr: List[int], start: int) -> bool: vis = [0]*len(arr) q = deque() q.append(start) while q: cur = q.popleft() print(cur) vis[cur] = 1 if arr[cur] == 0: return True if cur+arr[cur]<len(arr) and vis[cur+arr[cur]] == 0: q.append(cur+arr[cur]) if cur-arr[cur]>=0 and vis[cur-arr[cur]] == 0: q.append(cur-arr[cur]) return False
class Solution { public boolean canReach(int[] arr, int start) { int n = arr.length; boolean[] vis = new boolean[n]; Queue<Integer> q = new LinkedList<>(); q.add(start); while(!q.isEmpty()){ int size = q.size(); while(size-- > 0){ int curr = q.poll(); if(vis[curr]) continue; if(arr[curr] == 0) return true; if(curr+arr[curr] < n) q.add(curr+arr[curr]); if(curr-arr[curr] >= 0) q.add(curr-arr[curr]); vis[curr] = true; } } return false; } }
class Solution { public: bool dfs(int curr, vector<int>& arr, vector<bool>& visited, int size) { // edge cases - we can't go outside the array size and if the curr index is alredy visited it will repeat same recursion all over again so we can return false in that case too. if(curr < 0 || curr >= size || visited[curr]) return false; // If we reach zero we can return true if(arr[curr] == 0) return true; visited[curr] = true; // do dfs in left and right and return two if any of the two paths end up reaching to zero return dfs(curr - arr[curr], arr, visited, size) || dfs(curr + arr[curr], arr, visited, size); } bool canReach(vector<int>& arr, int start) { int size = arr.size(); vector<bool> visited(size, false); return dfs(start, arr, visited, size); } };
/** * @param {number[]} arr * @param {number} start * @return {boolean} */ var canReach = function(arr, start) { let queue = [start]; while(queue.length) { let index = queue.shift(); if(index >= 0 && index < arr.length && arr[index] >=0 ){ if(arr[index] === 0)return true; let move = arr[index] arr[index] = -1 queue.push(index +move , index-move) } } return false; };
Jump Game III
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. &nbsp; Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]] &nbsp; Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length &lt;= 1000 to_delete contains distinct values between 1 and 1000.
# 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 traverse(self,node,par): if node: self.parent[node.val] = par self.traverse(node.left,node) self.traverse(node.right,node) def deleteNode(self,toDelete): node = None par = self.parent[toDelete] if par.val == toDelete: node = par elif par.left and par.left.val == toDelete: node = par.left elif par.right and par.right.val == toDelete: node = par.right if node.left: self.unique[node.left] = True if node.right: self.unique[node.right] = True if node in self.unique: self.unique.pop(node) if node != self.parent[toDelete]: if par.left == node: par.left = None else: par.right = None def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: self.parent = {} self.traverse(root,root) self.unique = {root:True} for node in to_delete: self.deleteNode(node) return self.unique
class Solution { HashMap<Integer, List<TreeNode>> parent_val_child_nodes_map; HashMap<Integer, TreeNode> child_val_parent_node_map; public List<TreeNode> delNodes(TreeNode root, int[] to_delete) { // initialize map parent_val_child_nodes_map = new HashMap<> (); child_val_parent_node_map = new HashMap<> (); // fill map dfsFillMap(root); // traverse to_delete to find those that do not have parent after deleting it List<TreeNode> res = new ArrayList<> (); // actually deleting nodes for (int delete_val : to_delete) { // if the node has parent if (child_val_parent_node_map.containsKey(delete_val)) { TreeNode parent_node = child_val_parent_node_map.get(delete_val); if (parent_node.left != null && parent_node.left.val == delete_val) { parent_node.left = null; } if (parent_node.right != null && parent_node.right.val == delete_val) { parent_node.right = null; } } } // add root to the list first because root has no parent // only if root.val is not in to_delete if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) { res.add(root); } // add other nodes that do not have parent for (int delete_val : to_delete) { if (parent_val_child_nodes_map.containsKey(delete_val)) { for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) { // make sure the add node is not in to_delete int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val; if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) { res.add(parent_val_child_nodes_map.get(delete_val).get(i)); } } } } return res; } public void dfsFillMap(TreeNode root) { if (root == null) { return; } if (root.left != null) { parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ()); parent_val_child_nodes_map.get(root.val).add(root.left); child_val_parent_node_map.putIfAbsent(root.left.val, root); dfsFillMap(root.left); } if (root.right != null) { parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ()); parent_val_child_nodes_map.get(root.val).add(root.right); child_val_parent_node_map.putIfAbsent(root.right.val, root); dfsFillMap(root.right); } return; } }
class Solution { void solve(TreeNode* root,TreeNode* prev,unordered_map<int,int>& mp,int left,vector<TreeNode*>& ans){ if(root==NULL) return; int f=0; solve(root->left,root,mp,1,ans); solve(root->right,root,mp,0,ans); if(mp.find(root->val)!=mp.end()){ f=1; if(root->right) ans.push_back(root->right); // cout<<root->left->val<<" ";} if(root->left) ans.push_back(root->left); // cout<<root->right->val<<" ";} } if(f==1){ if(left) prev->left=NULL; else prev->right=NULL; } } public: vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) { if(root==NULL) return {}; unordered_map<int,int> mp; for(int i=0;i<to_delete.size();i++) mp[to_delete[i]]++; vector<TreeNode*> ans; TreeNode* dummy=new TreeNode(-1); dummy->left=root; solve(dummy->left,dummy,mp,1,ans); if(dummy->left) ans.push_back(root); return ans; } }; ```
var delNodes = function(root, to_delete) { if(!root) return []; to_delete = new Set(to_delete); // know how to delete // while deleting add new nodes to same algo const ans = []; const traverse = (r = root, p = null, d = 0) => { if(!r) return null; if(to_delete.has(r.val)) { if(p != null) { p[d == -1 ? 'left' : 'right'] = null; } traverse(r.left, null, 0); traverse(r.right, null, 0); } else { if(p == null) ans.push(r); traverse(r.left, r, -1); traverse(r.right, r, 1); } } traverse(); return ans; };
Delete Nodes And Return Forest
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even. Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. &nbsp; Example 1: Input: n = 1 Output: 5 Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8". Example 2: Input: n = 4 Output: 400 Example 3: Input: n = 50 Output: 564908303 &nbsp; Constraints: 1 &lt;= n &lt;= 1015
class Solution: def countGoodNumbers(self, n: int) -> int: ans = 1 rem = n % 2 n -= rem ans = pow(20, n//2, 10**9 + 7) if rem == 1: ans *= 5 return ans % (10**9 + 7)
class Solution { int mod=(int)1e9+7; public int countGoodNumbers(long n) { long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd long second=n/2;//second power would be n/2 only irrespective of even or odd long mul1=power(5,first)%mod;//5 power n/2 long mul2=power(4,second)%mod;//4 power n/2 long ans=1; ans=(ans*mul1)%mod;//computing total product ans=(second!=0)?(ans*mul2)%mod:ans;//computing total product return (int)(ans%mod); } public long power(long x,long y){// this method computes pow(x,y) in O(logn) using divide & conquer long temp; if(y==0) return 1;//base case (x power 0 = 1) temp=power(x,y/2);//computing power for pow(x,y/2) -> divide & conquer step if(y%2==0) return (temp*temp)%mod; //using that result of subproblem (2 power 2 = 2 power 1 * 2 power 1) else return (x*temp*temp)%mod;//using that result of subproblem (2 power 3 = 2 power 1 * 2 power 1 * 2) // if y is odd, x power y = x power y/2 * x power y/2 * x // if y is even, x power y = x power y/2 * x power y/2 } }
// Approach :-> This is question of combination // if n as large no.... // 0 1 2 3 4 5 6 7 8 9 10 11 . . . . . n // 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 . . . . . n/4 times of 4 and n/4 times of 5; //so calculate 5*4 = 20 -------> 20 * 20 * 20 * . . . . .. n/2 times //so calcultae pow(20,n/2) // if n is even return pow(20,n/2) // if n is odd return 5*pow(20,n/2) beacause if n is odd then one 5 is left out // we can easily calculate pow(x,y) in log(y) times // durign calculation take care about mod class Solution { public: int mod = 1000000007; long long solve(long long val,long long pow){ // calculatin pow in log(n) time if(pow==0) return 1; if(pow%2==0){ return solve((val*val)%mod,pow/2)%mod; } else return (val*solve((val*val)%mod,pow/2))%mod; } int countGoodNumbers(long long n) { // even means 5 options // odd means 4 option long long pow = n/2; // calculate no of times 5*4 means 20 occurs long long ans = solve(20,pow); // calculate power(20,pow) if(n%2==0){ // if n is even then 5 and 4 occur same no of time n/2 return ans; } return ((5*ans) % mod); // if n is odd then 5 occurs n/2+1 times means one extra times so return ans*5 and don't forgot to mod } };
class Math1 { // https://en.wikipedia.org/wiki/Modular_exponentiation static modular_pow(base, exponent, modulus) { if (modulus === 1n) return 0n let result = 1n base = base % modulus while (exponent > 0n) { if (exponent % 2n == 1n) result = (result * base) % modulus exponent = exponent >> 1n base = (base * base) % modulus } return result } } var countGoodNumbers = function(n) { // NOTE: 0n, 1n, 2n, 3n, 4n, 5n are numbers in BigInt n = BigInt(n); // convert to BigInt, to avoid no rounding issues const odds = n / 2n, evens = n - odds, MOD = BigInt(Math.pow(10, 9) + 7) // from wikipedia return (Math1.modular_pow(4n, odds, MOD) * Math1.modular_pow(5n, evens, MOD)) % MOD; };
Count Good Numbers
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3]. Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order. It is guaranteed an answer exists. &nbsp; Example 1: Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2] Example 2: Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2] &nbsp; Constraints: 1 &lt;= req_skills.length &lt;= 16 1 &lt;= req_skills[i].length &lt;= 16 req_skills[i] consists of lowercase English letters. All the strings of req_skills are unique. 1 &lt;= people.length &lt;= 60 0 &lt;= people[i].length &lt;= 16 1 &lt;= people[i][j].length &lt;= 16 people[i][j] consists of lowercase English letters. All the strings of people[i] are unique. Every skill in people[i] is a skill in req_skills. It is guaranteed a sufficient team exists.
from collections import defaultdict from functools import lru_cache class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: N = len(req_skills) skills = {skill: i for i, skill in enumerate(req_skills)} people_mask = defaultdict(int) for i, cur_skills in enumerate(people): mask = 0 for skill in cur_skills: mask |= 1<<skills[skill] people_mask[i] = mask self.path = [] self.res = float('inf') self.respath = None @lru_cache(None) #i: people i #l: length of current self.path #mask: mask for current skills def dfs(i, l, mask): if mask == (1<<N) - 1: if l < self.res: self.res = l self.respath = self.path[:] return if i == len(people): return if l >= self.res: return dfs(i+1, l, mask) self.path.append(i) if mask & people_mask[i] != people_mask[i]: dfs(i+1, l+1, mask | people_mask[i]) self.path.pop() dfs(0,0,0) return self.respath
class Solution { public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { int N = 1 << req_skills.length, INF = (int)1e9; int[] parent = new int[N]; int[] who = new int[N]; int[] dp = new int[N]; Arrays.fill(dp, INF); dp[0] = 0; for (int i = 0; i < N; i++){ if (dp[i]!=INF){ // valid state for (int k = 0; k < people.size(); k++){ int cur = i; for (int j = 0; j < req_skills.length; j++){ for (String skill : people.get(k)){ if (req_skills[j].equals(skill)){ cur |= 1<<j; // set the mask break; } } } if (dp[cur]>dp[i]+1){ // replace if better dp[cur]=dp[i]+1; parent[cur]=i; who[cur]=k; } } } } int[] ans = new int[dp[N-1]]; for (int i = 0,cur=N-1; i < ans.length; i++){ ans[i]=who[cur]; cur=parent[cur]; } return ans; } }
class Solution { public: vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) { vector<int> mask(people.size(), 0); for(int i=0; i<people.size(); i++){ for(int j=0; j<req_skills.size(); j++){ for(int z=0; z<people[i].size(); z++){ if(people[i][z] == req_skills[j]){ mask[i] += (1<<j); break; } } } } vector<long long> dp(1<<req_skills.size(), INT_MAX); vector<vector<int>> save(1<<req_skills.size()); dp[0] = 0; for(int i=0; i<(1<<req_skills.size()); i++){ for(int j=0; j<mask.size(); j++){ int new_mask = i&(i^mask[j]); if(dp[new_mask]+1<dp[i]){ dp[i] = dp[new_mask]+1; save[i] = save[new_mask]; save[i].push_back(j); } } } return save[(1<<req_skills.size())-1]; } };
/** * @param {string[]} req_skills * @param {string[][]} people * @return {number[]} */ var smallestSufficientTeam = function(req_skills, people) { const skillIndexMap = new Map(); req_skills.forEach((skill, index) => skillIndexMap.set(skill,index) ); const skillTeamMap = new Map([[0, []]]); people.forEach( (skills, index) => { let hisSkills = 0; for (const skill of skills) { hisSkills |= 1 << skillIndexMap.get(skill); } for (const [currSkill, team] of skillTeamMap) { const totalSkills = currSkill | hisSkills; if (totalSkills === currSkill) { continue; } if ( !skillTeamMap.has(totalSkills) || team.length + 1 < skillTeamMap.get(totalSkills).length ) { skillTeamMap.set(totalSkills, [...team, index]) } } }); return skillTeamMap.get( (1<<req_skills.length) - 1); };
Smallest Sufficient Team
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. &nbsp; Example 1: Input: nums = [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. Example 2: Input: nums = [1,2,3,4] Output: 2 Example 3: Input: nums = [1,1,1,1] Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 -109 &lt;= nums[i] &lt;= 109
"" from collections import Counter class Solution: def findLHS(self, nums: List[int]) -> int: counter=Counter(nums) # values=set(nums) res=0 # if len(values)==1:return 0 for num in nums: if num+1 in counter or num-1 in counter: res=max(res,counter[num]+counter.get(num+1,0)) res=max(res,counter[num]+counter.get(num-1,0)) return res ""
class Solution { public static int firstOccurence(int[] arr,int target) { int res=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=start + (end-start)/2; if(arr[mid]==target) { res=mid; end=mid-1; } else if(arr[mid]<target) { start=mid+1; } else { end=mid-1; } } return res; } public static int lastOccurence(int[] arr,int target) { int res=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=start + (end-start)/2; if(arr[mid]==target) { res=mid; start=mid+1; } else if(arr[mid]<target) { start=mid+1; } else { end=mid-1; } } return res; } public int findLHS(int[] nums) { Arrays.sort(nums); int maxLen=0; for(int i=0;i<nums.length-1;i++) { if(nums[i+1]==nums[i]+1) { int a=firstOccurence(nums,nums[i]); int b=lastOccurence(nums,nums[i]+1); if(b-a+1>maxLen) maxLen=b-a+1; } } return maxLen; } }
class Solution { public: int findLHS(vector<int>& nums) { map<int,int> m; for(int i=0;i<nums.size();i++) { m[nums[i]]++; } int ans=0; int x=-1,y=0; for(auto i=m.begin();i!=m.end();i++) { if(i->first-x==1) { ans=max(ans,y+i->second); } x=i->first; y=i->second; } return ans; } }; //if you like the solution plz upvote.
var findLHS = function(nums) { let countNumber = {}; let result = []; for (let i=0; i<nums.length; i++) { if (!countNumber[nums[i]]) { countNumber[nums[i]] = 1; } else { countNumber[nums[i]]++; } } for (let value of Object.keys(countNumber)) { let count; let current = parseInt(value); if (countNumber[current + 1]) { count = countNumber[current] + countNumber[current + 1]; result.push(count); } }; if (result.length === 0) { return 0; } return Math.max(...result); };
Longest Harmonious Subsequence
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. &nbsp; Example 1: Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 108
class Solution: def maximumXOR(self, nums: List[int]) -> int: res=0 for i in nums: res |= i return res
class Solution { public int maximumXOR(int[] nums) { int res = 0; for (int i=0; i<nums.length; i++){ res |= nums[i]; } return res; } }
class Solution { public: int maximumXOR(vector<int>& nums) { int res = 0; for (int i=0; i<nums.size() ; i++){ res |= nums[i]; } return res; } };
/** * @param {number[]} nums * @return {number} */ var maximumXOR = function(nums) { return nums.reduce((acc, cur) => acc |= cur, 0); };
Maximum XOR After Operations
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 &lt;= i &lt; j &lt; dominoes.length, and dominoes[i] is equivalent to dominoes[j]. &nbsp; Example 1: Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1 Example 2: Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] Output: 3 &nbsp; Constraints: 1 &lt;= dominoes.length &lt;= 4 * 104 dominoes[i].length == 2 1 &lt;= dominoes[i][j] &lt;= 9
import math class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: d=dict() for i in dominoes: i.sort() #Just to make everything equal and comparable if(tuple(i) in d.keys()): #In python, lists are unhashable so converted the list into tuples d[tuple(i)]+=1 else: d[tuple(i)]=1 count=0 for x,y in d.items(): if(y>1): count+=y*(y-1)//2 #To check the number of pairs, if 2 elements pairs is 1,if 3 pair is 3 and so on.....formula is n*n-1/2 return count
class Solution { /** Algorithm 1. Brute force cannot be used because of the set size. 2. Traverse the dominos and group & count them by min-max value. As pieces can be from 1 to 9, means their groups will be from 11 to 99. eg: [1,2] will be the same as [2,1]. Their value is 10 * (min(1,2)) + max(1,2) => 10 * 1 + 2 = 12. so pieces[12]++; 3. After finishing traversing, iterate over the counted pieces and if the count is > 1, calculate the combinations of X by 2. 4. The formula is n!/ (k! * (n-k)!) As n! can be very large, use the short version of it; (n * (n-1)) / 2. EG n= 40 Eg: 40! simplify this(divide by 38!) 39 * 40 -------- --------- 2! * (38!) 2 5. Return the total result */ public int numEquivDominoPairs(int[][] dominoes) { int[] pieces = new int[100]; for (int[] domino : dominoes) { pieces[10 * Math.min(domino[0], domino[1]) + Math.max(domino[0], domino[1])]++; } int pairs = 0; for (int i = 11; i <= 99; i++) { if (pieces[i] > 1) { pairs += getCombinations(pieces[i]); } } return pairs; } private int getCombinations(int n) { return (n * (n-1)) / 2; } }
class Solution { public: int numEquivDominoPairs(vector<vector<int>>& dominoes) { map<pair<int,int>,int> m; int ans=0; for(auto &d:dominoes) { int a=min(d[0],d[1]),b=max(d[0],d[1]); m[{a,b}]++; } for(auto &p:m) { int n=p.second; ans+=((n-1)*n)/2; } return ans; } }; //if you like the solution plz upvote.
var numEquivDominoPairs = function(dominoes) { let map = {}; let count = 0; for (let [a, b] of dominoes) { if (b > a) { [a, b] = [b, a]; } let key = `${a}-${b}`; if (map.hasOwnProperty(key)) { map[key]++; count += map[key]; } else { map[key] = 0; } } return count; };
Number of Equivalent Domino Pairs
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231. &nbsp; Example 1: Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. &nbsp; Constraints: -231 &lt;= dividend, divisor &lt;= 231 - 1 divisor != 0
class Solution: def divide(self, dividend: int, divisor: int) -> int: # Solution 1 - bitwise operator << """ positive = (dividend < 0) is (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) if divisor == 1: quotient = dividend else: quotient = 0 while dividend >= divisor: temp, i = divisor, 1 while dividend >= temp: dividend -= temp quotient += i i <<= 1 temp <<= 1 if not positive: return max(-2147483648, -quotient) else: return min(quotient, 2147483647) """ # Solution 2 - cumulative sum - faster than bitwise positive = (dividend < 0) == (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) if divisor == 1: quotient = dividend else: quotient = 0 _sum = divisor while _sum <= dividend: current_quotient = 1 while (_sum + _sum) <= dividend: _sum += _sum current_quotient += current_quotient dividend -= _sum _sum = divisor quotient += current_quotient if not positive: return max(-2147483648, -quotient) else: return min(quotient, 2147483647)
class Solution { public int divide(int dividend, int divisor) { if(dividend == 1<<31 && divisor == -1){ return Integer.MAX_VALUE; } boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false; dividend = Math.abs(dividend); divisor = Math.abs(divisor); int result = 0; while(dividend - divisor >= 0){ int count = 0; while(dividend - (divisor << 1 << count) >= 0){ count++; } result += 1 <<count; dividend -= divisor << count; } return sign ? result : -result; } }
class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) { return INT_MAX; } long dvd = labs(dividend), dvs = labs(divisor), ans = 0; int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; while (dvd >= dvs) { long temp = dvs, m = 1; while (temp << 1 <= dvd) { temp <<= 1; m <<= 1; } dvd -= temp; ans += m; } return sign * ans; } };
var divide = function(dividend, divisor) { if (dividend == -2147483648 && divisor == -1) return 2147483647; let subdividend = Math.abs(dividend) let subdivisor = Math.abs(divisor) let string_dividend = subdividend.toString() let i = 0 let ans=0 let remainder = 0 while(i<string_dividend.length){ remainder =remainder*10+Number(string_dividend[i]) let quotient = Math.floor(remainder/subdivisor) ans = ans *10 + quotient remainder = remainder - quotient*subdivisor i++; } if((dividend >0 && divisor <0) || (dividend <0 && divisor >0)) return 0-ans return ans };
Divide Two Integers
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. &nbsp; Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 &nbsp; Constraints: n == height.length 1 &lt;= n &lt;= 2 * 104 0 &lt;= height[i] &lt;= 105
class Solution: def trap(self, a: List[int]) -> int: l=0 r=len(a)-1 maxl=0 maxr=0 res=0 while (l<=r): if a[l]<=a[r]: if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >= else: res+=maxl-a[l] #adding captured water when maxl>a[l] l+=1 else: if a[r]>=maxr: maxr=a[r] else: res+=maxr-a[r] r-=1 return res
class Solution { public int trap(int[] height) { int left = 0; int right = height.length - 1; int l_max = height[left]; int r_max = height[right]; int res = 0; while(left < right) { if(l_max < r_max) { left+=1; l_max = Math.max(l_max, height[left]); res += l_max - height[left]; } else{ right-=1; r_max = Math.max(r_max, height[right]); res += r_max - height[right]; } } return res; } }
class Solution { public: int trap(vector<int>& height) { int left=0,right=height.size()-1; int maxleft=0,maxright=0; int res=0; while(left<=right){ if(height[left]<=height[right]){ if(height[left]>=maxleft)maxleft=height[left]; else res += maxleft-height[left]; left++; }else{ if(height[right]>=maxright)maxright=height[right]; else res += maxright-height[right]; right--; } } return res; } };
var trap = function(height) { let left = 0, right = height.length - 1; let hiLevel = 0, water = 0; while(left <= right) { let loLevel = height[height[left] < height[right] ? left++ : right--]; hiLevel = Math.max(hiLevel, loLevel); water += hiLevel - loLevel ; } return water; };
Trapping Rain Water
You are given a string s consisting of digits and an integer k. A round can be completed if the length of s is greater than k. In one round, do the following: Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k. Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13. Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1. Return s after all rounds have been completed. &nbsp; Example 1: Input: s = "11111222223", k = 3 Output: "135" Explanation: - For the first round, we divide s into groups of size 3: "111", "112", "222", and "23". ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. &nbsp; So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round. - For the second round, we divide s into "346" and "5". &nbsp; Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. &nbsp; So, s becomes "13" + "5" = "135" after second round. Now, s.length &lt;= k, so we return "135" as the answer. Example 2: Input: s = "00000000", k = 3 Output: "000" Explanation: We divide s into "000", "000", and "00". Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000". &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 2 &lt;= k &lt;= 100 s consists of digits only.
class Solution: def digitSum(self, s: str, k: int) -> str: while len(s) > k: set_3 = [s[i:i+k] for i in range(0, len(s), k)] s = '' for e in set_3: val = 0 for n in e: val += int(n) s += str(val) return s
class Solution { public String digitSum(String s, int k) { while(s.length() > k) s = gen(s,k); return s; } public String gen(String s,int k){ String res = ""; for(int i=0;i < s.length();){ int count = 0,num=0; while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++)); res+=num; } return res; } }
class Solution { public: string digitSum(string s, int k) { if(s.length()<=k) return s; string ans=""; int sum=0,temp=k; int len = s.length(); for(int i=0;i<len;i++){ sum += (s[i] -'0'); temp--; if(temp==0){ ans+= to_string(sum); temp=k; sum=0; } } if(temp!=k){ ans+= to_string(sum); } if(ans.length()>k) ans = digitSum(ans,k); return ans; } };
var digitSum = function(s, k) { while (s.length > k) { let newString = ""; for (let i = 0; i < s.length; i += k) newString += s.substring(i, i + k).split("").reduce((acc, val) => acc + (+val), 0); s = newString; } return s; };
Calculate Digit Sum of a String
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. &nbsp; Example 1: Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. Example 2: Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. Example 3: Input: prices = [7,6,4,3,1] Output: 0 Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. &nbsp; Constraints: 1 &lt;= prices.length &lt;= 3 * 104 0 &lt;= prices[i] &lt;= 104
class Solution: def maxProfit(self, prices: List[int]) -> int: n=len(prices) ans=0 want="valley" for i in range(n-1): if want=="valley" and prices[i]<prices[i+1]: ans-=prices[i] want="hill" elif want=="hill" and prices[i]>prices[i+1]: ans+=prices[i] want="valley" if want=="hill": ans+=prices[-1] return ans
class Solution { public int maxProfit(int[] prices) { int n = prices.length,profit = 0; for(int i=0;i<n-1;i++){ if(prices[i+1]>prices[i]){ profit += prices[i+1]-prices[i]; } } return profit; } }
class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); int ans=0,currMin=prices[0]; for(int i=1;i<n;i++){ while(i<n && prices[i]>prices[i-1]){ i++; } ans+=(prices[i-1]-currMin); currMin=prices[i]; } return ans; } };
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { let lowestNum = prices[0]; let highestNum = prices[0]; let profit = highestNum - lowestNum; for(var indexI=1; indexI<prices.length; indexI++) { if(prices[indexI] < prices[indexI - 1]) { lowestNum = prices[indexI]; } if(prices[indexI] > lowestNum) { lowestNum = prices[indexI - 1]; profit = profit + prices[indexI] - lowestNum; highestNum = prices[indexI]; } } return profit; };
Best Time to Buy and Sell Stock II
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each&nbsp;of the two arrays. &nbsp; Example 1: Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"] Output: 2 Explanation: - "leetcode" appears exactly once in each of the two arrays. We count this string. - "amazing" appears exactly once in each of the two arrays. We count this string. - "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string. - "as" appears once in words1, but does not appear in words2. We do not count this string. Thus, there are 2 strings that appear exactly once in each of the two arrays. Example 2: Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] Output: 0 Explanation: There are no strings that appear in each of the two arrays. Example 3: Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"] Output: 1 Explanation: The only string that appears exactly once in each of the two arrays is "ab". &nbsp; Constraints: 1 &lt;= words1.length, words2.length &lt;= 1000 1 &lt;= words1[i].length, words2[j].length &lt;= 30 words1[i] and words2[j] consists only of lowercase English letters.
class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: count = Counter(words1 + words2) return len([word for word in count if count[word] == 2 and word in words1 and word in words2])
class Solution { public int countWords(String[] words1, String[] words2) { HashMap<String, Integer> map1 = new HashMap<>(); HashMap<String, Integer> map2 = new HashMap<>(); for(String word : words1) map1.put(word,map1.getOrDefault(word,0)+1); for(String word : words2) map2.put(word,map2.getOrDefault(word,0)+1); int count = 0; for(String word : words1) if(map1.get(word) == 1 && map2.getOrDefault(word,0) == 1) count++; return count; } }
class Solution { public: int countWords(vector<string>& words1, vector<string>& words2) { unordered_map<string, int> freq1, freq2; for (auto& s : words1) ++freq1[s]; for (auto& s : words2) ++freq2[s]; int ans = 0; for (auto& [s, v] : freq1) if (v == 1 && freq2[s] == 1) ++ans; return ans; } };
var countWords = function(words1, words2) { const map1 = new Map(); const map2 = new Map(); let count = 0; for (const word of words1) { map1.set(word, map1.get(word) + 1 || 1); } for (const word of words2) { map2.set(word, map2.get(word) + 1 || 1); } for (const word of words1) { if (map1.get(word) === 1 && map2.get(word) === 1) count++; } return count; };
Count Common Words With One Occurrence
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a &lt; b b - a equals to the minimum absolute difference of any two elements in arr &nbsp; Example 1: Input: arr = [4,2,1,3] Output: [[1,2],[2,3],[3,4]] Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. Example 2: Input: arr = [1,3,6,10,15] Output: [[1,3]] Example 3: Input: arr = [3,8,-10,23,19,-4,-14,27] Output: [[-14,-10],[19,23],[23,27]] &nbsp; Constraints: 2 &lt;= arr.length &lt;= 105 -106 &lt;= arr[i] &lt;= 106
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() diff=float(inf) for i in range(0,len(arr)-1): if arr[i+1]-arr[i]<diff: diff=arr[i+1]-arr[i] lst=[] for i in range(0,len(arr)-1): if arr[i+1]-arr[i]==diff: lst.append([arr[i],arr[i+1]]) return lst
class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { List<List<Integer>> ans=new ArrayList<>(); Arrays.sort(arr); int min=Integer.MAX_VALUE; for(int i=0;i<arr.length-1;i++){ int diff=Math.abs(arr[i]-arr[i+1]); if(diff<min) { min=diff; } } for(int i=0;i<arr.length-1;i++){ int diff=Math.abs(arr[i]-arr[i+1]); if(diff==min){ List<Integer> pair=new ArrayList<>(2); pair.add(arr[i]); pair.add(arr[i+1]); ans.add(pair); } } return ans; } }
class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { sort(arr.begin(),arr.end()); int diff=INT_MAX; for(int i=1;i<arr.size();i++){ diff=min(diff,abs(arr[i]-arr[i-1])); } vector<vector<int>>v; for(int i=1;i<arr.size();i++){ if(abs(arr[i]-arr[i-1])==diff){ int a=min(arr[i],arr[i-1]); int b=max(arr[i],arr[i-1]); v.push_back({a,b}); } } return v; } };
var minimumAbsDifference = function(arr) { arr.sort((a, b) => a - b) let minDif = Infinity let res = [] for (let i = 0; i < arr.length - 1; i++) { let currDif = Math.abs(arr[i + 1] - arr[i]) if (currDif < minDif) minDif = currDif } for (let i = 0; i < arr.length - 1; i++) { let dif = Math.abs(arr[i + 1] - arr[i]) if (dif === minDif) { res.push([arr[i], arr[i + 1]]) } } return res };
Minimum Absolute Difference
We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z &gt; threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly.&nbsp;(i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path. &nbsp; Example 1: Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]] Output: [false,false,true] Explanation: The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: [1,4] 1 is not connected to 4 [2,5] 2 is not connected to 5 [3,6] 3 is connected to 6 through path 3--6 Example 2: Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]] Output: [true,true,true,true,true] Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. Example 3: Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]] Output: [false,false,false,false,false] Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x]. &nbsp; Constraints: 2 &lt;= n &lt;= 104 0 &lt;= threshold &lt;= n 1 &lt;= queries.length &lt;= 105 queries[i].length == 2 1 &lt;= ai, bi &lt;= cities ai != bi
class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: parent = list(range(n+1)) def find(i): if parent[i] != i: parent[i] = find(parent[i]) return parent[i] def union(i,j): parent[find(i)] = find(j) if not threshold: return [True]*len(queries) for i in range(1, n+1): for j in range(2*i, n+1, i): if i > threshold: union(i,j) return [find(i) == find(j) for i,j in queries]
//Solving the problem using Disjoint Set Union Find approach class Solution { public int find(int x){ if(parent[x] == x) return x; //Optimising by placing the same parent for all the elements to reduce reduntant calls return parent[x] = find(parent[x]); } public void union(int a, int b){ a = find(a); b = find(b); //Using Rank optimisation if(rank[a] > rank[b]){ parent[b] = a; rank[a] += rank[b]; } else{ parent[a] = b; rank[b] += rank[a]; } //parent[b] = a; } int parent[]; int rank[]; public List<Boolean> areConnected(int n, int threshold, int[][] queries) { List<Boolean> ans = new ArrayList<Boolean>(); parent = new int[n+1]; rank = new int[n+1]; for(int i=1; i<=n; i++){ //Each element is its own parent parent[i] = i; //At beginning each element has rank 1 rank[i] = 1; } // Finding the possible divisors with pairs above given threshold for(int th = threshold+1; th<=n; th++){ int mul = 1; while(mul * th <= n){ //If possible pair then making a union of those paired element union(th, mul*th); mul++; } } //Generating ans for all possible queries for(int[] query : queries){ ans.add((find(query[0]) == find(query[1]))); } return ans; } }
// DSU Class Template class DSU { vector<int> parent, size; public: DSU(int n) { for(int i=0; i<=n; i++) { parent.push_back(i); size.push_back(1); } } int findParent(int num) { if(parent[num] == num) return num; return parent[num] = findParent(parent[num]); } void unionBySize(int u, int v) { int parU = findParent(u); int parV = findParent(v); if(parU == parV) return; if(size[parU] < size[parV]) { parent[parU] = parV; size[parV] += size[parU]; } else { parent[parV] = parU; size[parU] += size[parV]; } } }; class Solution { public: vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) { DSU dsu(n); // Make connections with its multiple for(int i=threshold+1; i<=n; i++) { int j = 1; while(i*j <= n) { dsu.unionBySize(i, i*j); j++; } } vector<bool> res; for(auto& query : queries) { int u = query[0]; int v = query[1]; // Check if both cities belong to same component or not if(dsu.findParent(u) == dsu.findParent(v)) res.push_back(true); else res.push_back(false); } return res; } };
var areConnected = function(n, threshold, queries) { // if(gcd(a,b)>threshold), a and b are connected // 2 is connected with : 2, 4,6,8,10,12,14,16, (gcd(2,y)=2) // 3 is connected with : 3,6,9,12,... (gcd(3,y)=3) // 4 is connected with : 4,8,12,16,20,24,28, (gcd(4,y)=4) // 6 is connected with : 6,12,18...,cos (gcd(6,y)=6) // 5 is connected with : 10,15,20,25,...n cos (gcd(5,y)=6) // etc let dsu=new UnionFind(n+1) //to map n=>n (no node 0 on my question) for (let node = threshold+1; node <=n; node++) //basically this ensures that the road exists //cos gcd(node,secondnode)==node >threshold for (let secondnode = node+node; secondnode <=n; secondnode+=node) dsu.union(node,secondnode) return queries.map(([a,b])=>dsu.sameGroup(a,b)) }; class UnionFind { constructor(size){ //the total count of different elements(not groups) in this union find this.count=size //tracks the sizes of each of the components(groups/sets) //groupsize[a] returns how many elements the component with root a has this.groupSize=[...Array(size)] //number of components(groups) in the union find this.numComponents=size //points to the parent of i, if parent[i]=i, i is a root node this.parent=[...Array(size)] //which is also the index of the group //put every element into its own group // rooted at itself for (let i = 0; i < size; i++) { this.groupSize[i]=i this.parent[i]=i } } //returns to which component (group) my element belongs to // (n) --Amortized constant time // Update: Also compresses the paths so that each child points to its // parent find(element){ let root=element //find the parent of the group the elemnt belongs to // When root===parent[root] is always the parent of that group (root) while(root!=this.parent[root]) root=this.parent[root] // Compression, point the element to its parent if its not already pointed // Tldr: Not only do I point my element to its actual root, i point any // inbetween elements to that root aswell while(element!=root){ let next=this.parent[element] this.parent[element]=root element=next } return root } //Unifies the sets containing A and B // if not already unified // (n) --Amortized constant time union(A,B){ let root1=this.find(A) //parent of A ,root2=this.find(B) //parent of B if(root1===root2) //already unified return // I want to put the set with fewer elements // to the one with more elemenets if(this.groupSize[root1]<this.groupSize[root2]){ this.groupSize[root2]+=this.groupSize[root1] this.parent[root1]=this.parent[root2] } else { this.groupSize[root1]+=this.groupSize[root2] this.parent[root2]=this.parent[root1] } this.numComponents-- //cos 1 less group, since i merged 2 } //same parent=>samegroup sameGroup=(A,B)=>this.find(A)==this.find(B) //essentially the groupSize of its parent's group sizeOfGroup=(A)=>this.groupSize[this.find(A)] }
Graph Connectivity With Threshold
Given an integer n, return an array ans of length n + 1 such that for each i (0 &lt;= i &lt;= n), ans[i] is the number of 1's in the binary representation of i. &nbsp; Example 1: Input: n = 2 Output: [0,1,1] Explanation: 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 Example 2: Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 3 --&gt; 11 4 --&gt; 100 5 --&gt; 101 &nbsp; Constraints: 0 &lt;= n &lt;= 105 &nbsp; Follow up: It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass? Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
class Solution: def countBits(self, n: int) -> List[int]: # We know that all exponential values of two have 1 bit turned on, the rest are turned off. # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed # into smaller numbers where we already have found the # of 1s, for example. # F(3) = F(2^1) + F(1) = 1 + 1 = 3 # F(4) = F(2^2) + F(0) = 1 + 0. ( Even thought we havent defined F(4) = F(2^2), by the previous established) # comment, we can safely say that all F(2^X) has only 1 bit so thats where F(4) would be = 1 # F(5) = F(2^2) + F(1) = 1 + 1 = 2 # F(6) = F(2^2) + F(2) = F(4) + F(2) = 1 + 1 # The relation countinues for all following numbers # This solution is O(N) # With O(1) extra space ( considering dp is the returned answer ) dp = [0] for i in range(1, n + 1): exponent = int(math.log(i) / math.log(2)) num = 2**exponent decimal = i % (num) if num == i: dp.append(1) else: dp.append(dp[num] + dp[decimal]) return(dp)
class Solution { public void count(int n, int[] a, int k) { int i; for(i=k ; i<k*2 && i<=n; i++) a[i]=a[i-k]+1; if(i==n+1) return; count(n,a,k*2); } public int[] countBits(int n) { int a[] = new int[n+1]; a[0]=0; count(n,a,1); return a; } }
class Solution { private: int countones( int n ){ int count = 0; while(n){ count ++; n = n & ( n-1 ); } return count; } public: vector<int> countBits(int n) { vector<int> ans; for( int i = 0; i <= n; i++ ){ int x = countones(i); ans.push_back(x); } return ans; } };
var countBits = function(n) { if (n === 0) return [0]; const ans = new Array(n + 1).fill(0); let currRoot = 0; for (let idx = 1; idx <= n; idx++) { if ((idx & (idx - 1)) === 0) { ans[idx] = 1; currRoot = idx; continue; } ans[idx] = 1 + ans[idx - currRoot]; } return ans; };
Counting Bits
You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. &nbsp; Example 1: Input: nums = [1,2,1,4], k = 2 Output: 4 Explanation: The optimal distribution of subsets is [1,2] and [1,4]. The incompatibility is (2-1) + (4-1) = 4. Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements. Example 2: Input: nums = [6,3,8,1,3,1,2,2], k = 4 Output: 6 Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. Example 3: Input: nums = [5,3,3,6,3,3], k = 3 Output: -1 Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset. &nbsp; Constraints: 1 &lt;= k &lt;= nums.length &lt;= 16 nums.length is divisible by k 1 &lt;= nums[i] &lt;= nums.length
class Solution(object): def minimumIncompatibility(self, nums, k): nums.sort(reverse = True) upperbound = len(nums) // k arr = [[] for _ in range(k)] self.res = float('inf') def assign(i): if i == len(nums): self.res = min(self.res, sum(arr[i][0]-arr[i][-1] for i in range(k))) return True flag = 0 for j in range(k): if not arr[j] or (len(arr[j]) < upperbound and arr[j][-1] != nums[i]): arr[j].append(nums[i]) if assign(i+1): flag += 1 arr[j].pop() if flag >= 2: break return flag != 0 if max(collections.Counter(nums).values()) > k: return -1 assign(0) return self.res
class Solution { public int minimumIncompatibility(int[] nums, int k) { Arrays.sort(nums); k=nums.length/k; int n = nums.length,INF=100; int[][] dp = new int[1<<n][n]; for (int[] d : dp){ Arrays.fill(d, INF); } for (int i=0;i<n;i++){ dp[1<<i][i]=0; } for (int i = 1; i < 1<<n; i++){ int c = Integer.bitCount(i); for (int j=0;j<n&&c%k==0;j++){ for (int w=0;w<n&&(i&1<<j)>0;w++){ if ((i&1<<w)==0){ dp[i|1<<w][w]=Math.min(dp[i|1<<w][w], dp[i][j]); } } } for (int j=0;j<n&&c%k!=0;j++){ for (int w=j+1;w<n&&(i&1<<j)>0;w++){ if ((i&1<<w)==0&&nums[w]!=nums[j]){ dp[i|1<<w][w]=Math.min(dp[i|1<<w][w], dp[i][j]+nums[w]-nums[j]); } } } } int ans = Arrays.stream(dp[(1<<n)-1]).min().getAsInt(); return ans==INF?-1:ans; } }
const int INF = 1e9; class Solution { public: int minimumIncompatibility(vector<int>& nums, int k) { int i, n = nums.size(), subset_size = n / k; sort(nums.begin(), nums.end()); // Pre-calculate the range (max - min) for each subset of nums // Note that there are (1 << n) subsets (i.e. 2 ^ n subsets) of an array of size n vector<int> range(1 << n, INF); // Each mask represents every possible subset of elements in num (so, "mask" == "subset") // Specifically, if the bit at position i of mask is set to 1, then we include that number in the subset for(int mask = 1; mask < (1 << n); mask++) { int small = -1, big = -1; bool dup = false; // Identify elements that belong to this subset, find the largest & smallest, check for duplicates // Recall that this array was sorted in the beginning of the function for(i=0; i<n && !dup; i++) if(mask & (1 << i)) { if(small == -1) small = nums[i]; if(big == nums[i]) dup = true; big = nums[i]; } // If no duplicates were found, then calculate and store the range for this subset if(!dup) range[mask] = big - small; } vector<int> dp(1 << n, INF); dp[0] = 0; // Iterate over every mask (i.e. subset) and calculate its minimum sum for(int mask = 1; mask < (1 << n); mask++) { // Iterate over every submask for current mask for(int submask = mask; submask; submask = (submask - 1) & mask) { // Check that submask has the right number of elements if(__builtin_popcount(submask) == subset_size) // Note that mask = submask + (mask ^ submask) // ==> i.e., mask ^ submask = mask - submask // In other words, (mask ^ submask) represents those elements in mask that are not in submask dp[mask] = min(dp[mask], range[submask] + dp[mask ^ submask]); } } // dp.back() == dp[(1 << n) - 1]; return dp.back() >= INF ? -1 : dp.back(); } };
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// var minimumIncompatibility = function(nums, k) { ////// FROM HERE TO if (nums.length === k) return 0; const maxInBucket = nums.length / k; const freqCount = {}; for (const n of nums) { if (freqCount[n]) { if (freqCount[n] === k) { return -1 } else { freqCount[n]++ } } else { freqCount[n] = 1 } } /////// HERE is just saving time // create a cache (aka memo, dp, dynamic programming, momoization) const cache = {} // create a mask to know when all the indicies are used const allIndiciesUsedMask = 2 ** nums.length - 1; const dfs = (usedIndicesBitMask) => { // if we have used all the indicies then we return 0 if (usedIndicesBitMask === allIndiciesUsedMask) { return 0; } // if we have seen this combination before, return the // result that was calculated before // otherwise do the hard work LOL if (cache[usedIndicesBitMask]) { return cache[usedIndicesBitMask]; } // find all the indicies that are available to be used // skip duplicate values const valsToIndices = {}; for (let i = 0; i < nums.length; i++) { const indexMask = 1 << i; if (usedIndicesBitMask & indexMask) continue; const value = nums[i]; if (!valsToIndices.hasOwnProperty(value)) { valsToIndices[value] = i; } } const indicesAvailable = Object.values(valsToIndices); // this is hard to explain but it's basically calculating the minimum // cost while marking the indicies that are going to be used for each // combination let minIncompatibilityCost = Infinity; const combinations = createCombinations(indicesAvailable, maxInBucket); for (const indices of combinations) { let nextMask = usedIndicesBitMask; let minVal = Infinity; let maxVal = -Infinity; for (const index of indices) { minVal = Math.min(minVal, nums[index]); maxVal = Math.max(maxVal, nums[index]); nextMask = nextMask | (1 << index); } const incompatibilityCost = maxVal - minVal; minIncompatibilityCost = Math.min(minIncompatibilityCost, dfs(nextMask) + incompatibilityCost); } return cache[usedIndicesBitMask] = minIncompatibilityCost; } return dfs(0); }; function createCombinations(indices, len) { const combinations = []; if (indices.length < len) { return combinations; } const stack = [[[], 0]]; while (stack.length > 0) { let [combi, i] = stack.pop(); for (; i < indices.length; i++) { const combination = [...combi, indices[i]]; if (combination.length === len) { combinations.push(combination); } else { stack.push([combination, i + 1]); } } } return combinations; }
Minimum Incompatibility
Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists. &nbsp; Example 1: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 18 Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents. Example 2: Input: root = [1] Output: 0 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. 1 &lt;= Node.val &lt;= 100
class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: def dfs(root, p, gp): if not root: return 0 if gp and gp.val%2==0: return root.val + dfs(root.left,root,p)+dfs(root.right,root,p) return 0 + dfs(root.left,root,p)+dfs(root.right,root,p) return dfs(root,None,None)
class Solution { int sum=0; public int sumEvenGrandparent(TreeNode root) { dfs(root,null,null); return sum; } void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) { if (current == null) return; // base case if (grandParent != null && grandParent.val % 2 == 0) { sum += current.val; } //cur->cur.left ||cur.right , parent=cur,grandPrarent=parent dfs(current.left, current, parent) dfs(current.right, current, parent); } }
class Solution { public: void sumGparent(TreeNode* child, int& sum, TreeNode* parent, TreeNode* Gparent){ if(!child) return; if(Gparent) if(Gparent->val % 2 ==0) sum += child->val; sumGparent(child->left, sum, child, parent); sumGparent(child->right, sum, child, parent); } int sumEvenGrandparent(TreeNode* root) { if(!root) return 0; int sum=0; sumGparent(root, sum, NULL, NULL); // (child, sum, parent, grand-parent) return sum; } };
const dfs = function(node, evenParent) { if (!node) return 0; const isEvenNode = node.val % 2 === 0; const left = dfs(node.left, isEvenNode); const right = dfs(node.right, isEvenNode); if (!evenParent) return left + right; return left + right + (node.left ? node.left.val : 0) + (node.right ? node.right.val : 0); } var sumEvenGrandparent = function(root) { if (!root) return 0; return dfs(root, false); };
Sum of Nodes with Even-Valued Grandparent
Given a 2D matrix matrix, handle multiple queries of the following type: Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). You must design an algorithm where sumRegion works on O(1) time complexity. &nbsp; Example 1: Input ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] Output [null, 8, 11, 12] Explanation NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 200 -104 &lt;= matrix[i][j] &lt;= 104 0 &lt;= row1 &lt;= row2 &lt; m 0 &lt;= col1 &lt;= col2 &lt; n At most 104 calls will be made to sumRegion.
class NumMatrix: def __init__(self, matrix: List[List[int]]): m, n = len(matrix), len(matrix[0]) # Understand why we need to create a new matrix with extra one row/column self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)] for r in range(1, m + 1): for c in range(1, n + 1): self.sum[r][c] = self.sum[r - 1][c] + self.sum[r][c - 1] - self.sum[r - 1][c - 1] + matrix[r - 1][c - 1] def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: r1, c1, r2, c2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1 return self.sum[r2][c2] - self.sum[r1 - 1][c2] - self.sum[r2][c1 - 1] + self.sum[r1 - 1][c1 - 1] # Your NumMatrix object will be instantiated and called as such: # obj = NumMatrix(matrix) # param_1 = obj.sumRegion(row1,col1,row2,col2)
class NumMatrix { int mat[][]; public NumMatrix(int[][] matrix) { mat = matrix; int rows = mat.length; int cols = mat[0].length; for(int i = 0; i< rows; i++) { for(int j = 0; j < cols; j++) { if(i > 0) mat[i][j] += mat[i-1][j]; if(j > 0) mat[i][j] += mat[i][j-1]; if(i>0 && j > 0) mat[i][j] -= mat[i-1][j-1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { int res = mat[row2][col2]; if(row1 > 0) res -= mat[row1-1][col2]; if(col1 > 0) res -= mat[row2][col1-1]; if(row1> 0 && col1 > 0) res += mat[row1-1][col1-1]; return res; } }
//Using row prefix sum O(m) class NumMatrix { vector<vector<int>> prefix; public: NumMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for(int i = 0;i<m;i++){ vector<int> row(n); row[0] = matrix[i][0]; for(int j = 1;j<n;j++){ row[j] = row[j-1] + matrix[i][j]; } prefix.push_back(row); } } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for(int i = row1;i<=row2;i++){ sum += prefix[i][col2]; if(col1>0) sum -= prefix[i][col1-1]; } return sum; } }; //Using mat prefix sum O(1) class NumMatrix { vector<vector<int>> prefix; public: NumMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); prefix = vector<vector<int>>(m+1,vector<int>(n+1,0)); prefix[1][1] = matrix[0][0]; for(int i = 1;i<=m;i++){ for(int j = 1;j<=n;j++){ prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] + matrix[i-1][j-1] - prefix[i-1][j-1]; } } } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; sum += prefix[row2+1][col2+1]; sum -= prefix[row1][col2+1]; sum -= prefix[row2+1][col1]; sum += prefix[row1][col1]; return sum; } };
/** * @param {number[][]} matrix */ var NumMatrix = function(matrix) { const n = matrix.length, m = matrix[0].length; // n * m filled with 0 this.prefix = Array.from({ length: n}, (_, i) => { return new Array(m).fill(0); }); const prefix = this.prefix; // precompute for(let i = 0; i < m; i++) { if(i == 0) prefix[0][i] = matrix[0][i]; else prefix[0][i] = prefix[0][i-1] + matrix[0][i]; } for(let i = 0; i < n; i++) { if(i == 0) continue; else prefix[i][0] = prefix[i-1][0] + matrix[i][0]; } for(let i = 1; i < n; i++) { for(let j = 1; j < m; j++) { prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] + matrix[i][j]; } } }; /** * @param {number} row1 * @param {number} col1 * @param {number} row2 * @param {number} col2 * @return {number} */ NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { const prefix = this.prefix; const biggerRectSum = prefix[row2][col2]; if(row1 == col1 && row1 == 0) return biggerRectSum; if(row1 == 0 || col1 == 0) { let subtractRegion = 0; if(row1 == 0) subtractRegion = prefix[row2][col1 - 1]; else subtractRegion = prefix[row1 - 1][col2]; return biggerRectSum - subtractRegion; } return biggerRectSum - prefix[row1-1][col2] - prefix[row2][col1 - 1] + prefix[row1-1][col1-1]; }; /** * Your NumMatrix object will be instantiated and called as such: * var obj = new NumMatrix(matrix) * var param_1 = obj.sumRegion(row1,col1,row2,col2) */
Range Sum Query 2D - Immutable
You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part. For example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2. &nbsp; Example 1: Input: nums = [7,4,3,9,1,8,5,2,6], k = 3 Output: [-1,-1,-1,5,4,4,-1,-1,-1] Explanation: - avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index. - The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37. Using integer division, avg[3] = 37 / 7 = 5. - For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4. - For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4. - avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index. Example 2: Input: nums = [100000], k = 0 Output: [100000] Explanation: - The sum of the subarray centered at index 0 with radius 0 is: 100000. avg[0] = 100000 / 1 = 100000. Example 3: Input: nums = [8], k = 100000 Output: [-1] Explanation: - avg[0] is -1 because there are less than k elements before and after index 0. &nbsp; Constraints: n == nums.length 1 &lt;= n &lt;= 105 0 &lt;= nums[i], k &lt;= 105
class Solution: def getAverages(self, nums: list[int], k: int) -> list[int]: n, diam = len(nums), 2*k+1 if n < diam: return [-1]*n ans = [-1]*k arr = list(accumulate(nums, initial = 0)) for i in range(n-diam+1): ans.append((arr[i+diam]-arr[i])//diam) return ans + [-1]*k
class Solution { public int[] getAverages(int[] nums, int k) { if(k == 0) return nums; int N = nums.length; long[] sum = new long[N]; sum[0] = nums[0]; for(int i = 1; i < N; i++) sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i] int[] ret = new int[N]; Arrays.fill(ret,-1); for(int i = k; i < N-k; i++) // Beyond this range, there are less than k elements so -1 { long temp = (sum[i+k]-sum[i-k]+nums[i-k])/(k*2+1); ret[i] = (int)temp; } return ret; } }
class Solution { public: vector<int> getAverages(vector<int>& nums, int k) { int n = nums.size(); vector<int> ans(n , -1); if(2 * k + 1 > n) return ans; // Simple Sliding Window long long int sum = 0; // Take a window of size 2 * k + 1 for(int i =0 ; i < 2 * k + 1 ; i++) { sum += nums[i]; } ans[k] = sum / (2 * k + 1); // Then slide it untill the end of the window reaches at the end for(int i = 2 * k + 1 , j = k + 1, s = 0; i < n ; i++ , j++, s++) { sum += nums[i]; sum -= nums[s]; ans[j] = sum /(2 * k + 1); } return ans; } };
var getAverages = function(nums, k) { const twoK = 2 * k; const windowSize = twoK + 1; const result = [...nums].fill(-1); let sum = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (i >= twoK) { result[i - k] = Math.floor(sum / windowSize) sum -= nums[i - twoK]; } } return result; };
K Radius Subarray Averages
Given a positive integer num, write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt. &nbsp; Example 1: Input: num = 16 Output: true Example 2: Input: num = 14 Output: false &nbsp; Constraints: 1 &lt;= num &lt;= 2^31 - 1
class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True lo = 2 hi = num // 2 while lo <= hi: mid = lo + (hi - lo) //2 print(mid) if mid * mid == num: return True if mid * mid > num: hi = mid - 1 else: lo = mid + 1 return False
class Solution { public boolean isPerfectSquare(int num) { long start = 1; long end = num; while(start<=end){ long mid = start +(end - start)/2; if(mid*mid==num){ return true; } else if(mid*mid<num){ start = mid+1; } else end = mid-1; } return false; } }
class Solution { public: bool isPerfectSquare(int num) { if (num == 1)return true; long long l = 1, h = num / 2; while (l <= h) { long long mid = l + (h - l) / 2; long long midSqr = mid * mid; if (midSqr == num) return true; if (num < midSqr) { h = mid - 1; } else { l = mid + 1; } } return false; } };
var isPerfectSquare = function(num) { let low = 1; let high = 100000; while(low <= high){ let mid = (low + high) >> 1; let sqrt = mid * mid if( sqrt == num) { return true; }else if(num > sqrt ){ low = mid + 1 }else { high = mid - 1 } } return false; };
Valid Perfect Square
Given an integer array nums where&nbsp;every element appears three times except for one, which appears exactly once. Find the single element and return it. You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space. &nbsp; Example 1: Input: nums = [2,2,3,2] Output: 3 Example 2: Input: nums = [0,1,0,1,0,1,99] Output: 99 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 3 * 104 -231 &lt;= nums[i] &lt;= 231 - 1 Each element in nums appears exactly three times except for one element which appears once.
import math class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int [0,-1,1,0] [2,2,3,2] [2,2,3,2] [2,2,3,2] 10 10 11 10 """ total = sum(nums) uniqueTotals = set() while nums: uniqueTotals.add(nums.pop()) return (sum(uniqueTotals)*3 - total)/2
class Solution { public int singleNumber(int[] nums) { int[] bitCount = new int[32]; // 32 bit number // Count occurrence of each bits in each num for (int i = 0; i < bitCount.length; i++) { for (int num : nums) { if ((num & 1 << i) != 0) // If ith bit in "num" is 1 bitCount[i]++; } } // Check the bit which doesn't have count multiple of 3 (i.e. no of repeating digits in input nums arr) // and add it to the result. int result = 0; for (int i = 0; i < bitCount.length; i++) result += (bitCount[i] % 3) * (1 << i); return result; } }
class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int,int> mp; int ans= 0; for(auto i: nums){ mp[i]++; } for(auto j: mp){ if(j.second == 1){ ans = j.first; break; } } return ans; } };
/** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { if(nums.length === 1) return nums[0]; const objNums = {}; for(var indexI=0; indexI<nums.length; indexI++){ if(objNums[nums[indexI]] === 2) delete objNums[nums[indexI]]; else objNums[nums[indexI]] = (objNums[nums[indexI]] || 0) + 1; } return Object.keys(objNums)[0]; };
Single Number II
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 &lt;= i &lt; nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). &nbsp; Example 1: Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3] Explanation: The array ans is built as follows: ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] = [0,1,2,4,5,3] Example 2: Input: nums = [5,0,1,2,3,4] Output: [4,5,0,1,2,3] Explanation: The array ans is built as follows: ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] = [4,5,0,1,2,3] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt; nums.length The elements in nums are distinct. &nbsp; Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?
class Solution: #As maximum value of the array element is 1000, this solution would work def buildArray(self, nums: List[int]) -> List[int]: for i in range(len(nums)): if nums[nums[i]] <= len(nums): nums[i] = nums[nums[i]] * 1000 + nums[i] else: nums[i] = mod(nums[nums[i]],1000) * 1000 + nums[i] for i in range(len(nums)): nums[i] = nums[i] // 1000 return nums
class Solution { public int[] buildArray(int[] nums) { int n=nums.length; for(int i=0;i<n;i++) nums[i] = nums[i] + n*(nums[nums[i]]%n); for(int i=0;i<n;i++) nums[i] = nums[i]/n; return nums; } }
class Solution { public: vector<int> buildArray(vector<int>& nums) { int n=nums.size(); vector<int> ans(n); for(int i=0;i<n;i++){ ans[i]=nums[nums[i]]; } return ans; } };
var buildArray = function(nums) { return nums.map(a=>nums[a]); };
Build Array from Permutation
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. A substring is a contiguous non-empty sequence of characters within a string. &nbsp; Example 1: Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] Output: true Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. Now sub = "l3e7" is a substring of s, so we return true. Example 2: Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] Output: false Explanation: The string "f00l" is not a substring of s and no replacements can be made. Note that we cannot replace '0' with 'o'. Example 3: Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] Output: true Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. Now sub = "l33tb" is a substring of s, so we return true. &nbsp; Constraints: 1 &lt;= sub.length &lt;= s.length &lt;= 5000 0 &lt;= mappings.length &lt;= 1000 mappings[i].length == 2 oldi != newi s and sub consist of uppercase and lowercase English letters and digits. oldi and newi are either uppercase or lowercase English letters or digits.
from collections import defaultdict import re class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: reachable = defaultdict(set) for a, b in mappings: reachable[a].add(b) for c in sub: reachable[c].add(c) regex = "" for c in sub: if len(reachable[c]) > 1: regex += "(" regex += "|".join(reachable[c]) regex += ")" else: regex += c return re.compile(regex).search(s)
class Solution { public boolean matchReplacement(String s, String sub, char[][] mappings) { HashMap<Character, HashSet<Character>> m = new HashMap<>(); for(char[] carr: mappings) { if (!m.containsKey(carr[0])){ m.put(carr[0], new HashSet<Character>()); } m.get(carr[0]).add(carr[1]); } int len_s = s.length(); int len_sub = sub.length(); for (int pos = 0; pos < s.length(); pos++ ){ int i = pos; int j = 0; boolean cont = false; while (j <= sub.length()) { if ( j == sub.length()) return true; int lenlefts = len_s - i; int lenleftsub = len_sub - j; if (lenlefts < lenleftsub) { break; } else if ((s.charAt(i) == sub.charAt(j)) || (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) { i += 1; j += 1; } else { break; } } } return false; } }
class Solution { public: bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) { int m(size(s)), n(size(sub)); unordered_map<char, unordered_set<char>> mp; auto doit = [&](int ind) { for (int i=ind, j=0; i<ind+n; i++, j++) { if (s[i] == sub[j] or mp[sub[j]].count(s[i])) continue; return false; } return true; }; for (auto& mapping : mappings) mp[mapping[0]].insert(mapping[1]);; for (int i=0; i<=m-n; i++) if (doit(i)) return true; return false; } };
var matchReplacement = function(s, sub, mappings) { let n= s.length; let m = sub.length; let map = new Array(36).fill().map(_=>new Array(36).fill(0)); for(let i=0;i<mappings.length;i++) { let [o,ne] = mappings[i]; if(isNaN(o)) { o = (o.toUpperCase()).charCodeAt(0)-55; } else { o = parseInt(o); } if(isNaN(ne)) { ne = (ne.toUpperCase()).charCodeAt(0)-55; } else { ne = parseInt(ne); } map[o][ne]=1; } // let map = new Map(mappings); for(let i=0;i<=n-m;i++) { let z=i; let j=0; while(j<m){ if(s[z] !== sub[j]) { let ne = s[z]; let o = sub[j]; if(isNaN(o)) { o = (o.toUpperCase()).charCodeAt(0)-55; } else { o = parseInt(o); } if(isNaN(ne)) { ne = (ne.toUpperCase()).charCodeAt(0)-55; } else { ne = parseInt(ne); } if(map[o][ne] !== 1){ break; } } z++; j++; } if(j == m){ return true } } return false };
Match Substring After Replacement
Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name. If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names. For example, "m.y+name@email.com" will be forwarded to "my@email.com". It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails. &nbsp; Example 1: Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] Output: 2 Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails. Example 2: Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"] Output: 3 &nbsp; Constraints: 1 &lt;= emails.length &lt;= 100 1 &lt;= emails[i].length &lt;= 100 emails[i] consist of lowercase English letters, '+', '.' and '@'. Each emails[i] contains exactly one '@' character. All local and domain names are non-empty. Local names do not start with a '+' character. Domain names end with the ".com" suffix.
class Solution: def numUniqueEmails(self, emails: List[str]) -> int: def ets(email): s, domain = email[:email.index('@')], email[email.index('@'):] s = s.replace(".", "") s = s[:s.index('+')] if '+' in s else s return s+domain dict = {} for i in emails: dict[ets(i)] = 1 return len(dict)
class Solution { public int numUniqueEmails(String[] emails) { Set<String> finalEmails = new HashSet<>(); for(String email: emails){ StringBuilder name = new StringBuilder(); boolean ignore = false; for(int i=0;i<email.length();i++){ char c = email.charAt(i); switch(c){ case '.': break; case '+': ignore = true; break; case '@': name.append(email.substring(i)); i = email.length(); break; default: if(!ignore) name.append(c); } } finalEmails.add(name.toString()); } finalEmails.forEach(System.out::println); return finalEmails.size(); } }
class Solution { public: int numUniqueEmails(vector<string>& emails) { unordered_set<string> st; for(auto &e:emails) { string clean_email=""; for(auto &ch:e) { if(ch=='+'||ch=='@') break; if(ch=='.') continue; clean_email+=ch; } clean_email+=e.substr(e.find('@')); st.insert(clean_email); } return st.size(); } }; //if you like the solution plz upvote.
var numUniqueEmails = function(emails) { let set = new Set(); for (let email of emails) { let curr = email.split('@'); let currEmail = ''; for (let char of curr[0]) { if (char === '.') continue; if (char === '+') break; currEmail += char; } currEmail += '@' + curr[1]; set.add(currEmail) } return set.size };
Unique Email Addresses
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise. &nbsp; Example 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets. Example 2: Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. Example 3: Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets. &nbsp; Constraints: 1 &lt;= triplets.length &lt;= 105 triplets[i].length == target.length == 3 1 &lt;= ai, bi, ci, x, y, z &lt;= 1000
class Solution: def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: i=0 while True: if i==len(triplets): break for j in range(3): if triplets[i][j]>target[j]: triplets.pop(i) i-=1 break i+=1 a = [x[0] for x in triplets] b = [x[1] for x in triplets] c = [x[2] for x in triplets] if target[0] not in a: return False if target[1] not in b: return False if target[2] not in c: return False return True
class Solution { public boolean mergeTriplets(int[][] triplets, int[] target) { boolean xFound = false, yFound = false, zFound = false; for(int[] triplet : triplets){ //Current Triplet is target if(triplet[0] == target[0] && triplet[1] == target[1] && triplet[2] == target[2])return true; if(triplet[0] == target[0]){ if(triplet[1] <= target[1] && triplet[2] <= target[2]) if(yFound && zFound)return true; else xFound = true; } if(triplet[1] == target[1]){ if(triplet[0] <= target[0] && triplet[2] <= target[2]) if(xFound && zFound)return true; else yFound = true; } if(triplet[2] == target[2]){ if(triplet[1] <= target[1] && triplet[0] <= target[0]) if(yFound && xFound)return true; else zFound = true; } } return xFound && yFound && zFound; } }
class Solution { public: bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) { int first = 0, second = 0, third = 0; for (auto tr : triplets) { if (tr[0] == target[0] && tr[1] <= target[1] && tr[2] <= target[2]) first = 1; if (tr[0] <= target[0] && tr[1] == target[1] && tr[2] <= target[2]) second = 1; if (tr[0] <= target[0] && tr[1] <= target[1] && tr[2] == target[2]) third = 1; } return first && second && third; } };
var mergeTriplets = function(triplets, target) { let fst = false, snd = false, thrd = false; const [t1, t2, t3] = target; for(let i = 0; i < triplets.length; i++) { const [a, b, c] = triplets[i]; if(a === t1 && b <= t2 && c <= t3) fst = true; if(b === t2 && a <= t1 && c <= t3) snd = true; if(c === t3 && a <= t1 && b <= t2) thrd = true; if(fst && snd && thrd) return true; } return false; };
Merge Triplets to Form Target Triplet
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false otherwise. Notes: You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. &nbsp; Example 1: Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false &nbsp; Constraints: 1 &lt;= x &lt;= 9 At most 100&nbsp;calls will be made to push, pop, peek, and empty. All the calls to pop and peek are valid. &nbsp; Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.
class MyStack: def __init__(self): self.stack = [] def push(self, x): self.stack.append(x) def top(self): return self.stack[-1] def pop(self): return self.stack.pop() def size(self): return len(self.stack) def isEmpty(self): return len(self.stack) == 0 class MyQueue: def __init__(self): self.stack1 = MyStack() self.stack2 = MyStack() def push(self, x: int) -> None: self.stack1.push(x) def pop(self) -> int: while not self.stack1.isEmpty(): self.stack2.push(self.stack1.pop()) out = self.stack2.pop() while not self.stack2.isEmpty(): self.stack1.push(self.stack2.pop()) return out def peek(self) -> int: while not self.stack1.isEmpty(): self.stack2.push(self.stack1.pop()) out = self.stack2.top() while not self.stack2.isEmpty(): self.stack1.push(self.stack2.pop()) return out def empty(self) -> bool: return self.stack1.isEmpty() # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
class MyQueue { private final Deque<Integer> stack = new ArrayDeque<>(); private final Deque<Integer> temp = new ArrayDeque<>(); /** * Initialize your data structure here. */ public MyQueue() {} /** * Pushes element x to the back of the queue. */ public void push(int x) { stack.push(x); } /** * @return the element at the front of the queue and remove it. */ public int pop() { while (stack.size() > 1) temp.push(stack.pop()); var val = stack.pop(); while (!temp.isEmpty()) stack.push(temp.pop()); return val; } /** * @return the element at the front of the queue. */ public int peek() { while (stack.size() > 1) temp.push(stack.pop()); var val = stack.peek(); while (!temp.isEmpty()) stack.push(temp.pop()); return val; } /** * @return true if the queue is empty, false otherwise. */ public boolean empty() { return stack.isEmpty(); } }
class MyQueue { public: stack<int>s1; stack<int>s2; MyQueue() { } void push(int x) { s1.push(x); } int pop() { if(s1.empty() && s2.empty()) return -1; while(s2.empty()){ while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } } int x = s2.top(); s2.pop(); return x; } int peek() { if(!s2.empty()){ return s2.top(); } else{ while(!s1.empty()){ int val = s1.top(); s2.push(val); s1.pop(); } return s2.top(); } } bool empty() { if(s1.empty() && s2.empty()){ return true; } return false; } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
var MyQueue = function() { this.queue = []; }; /** * @param {number} x * @return {void} */ MyQueue.prototype.push = function(x) { this.queue.push(x); }; /** * @return {number} */ MyQueue.prototype.pop = function() { return this.queue.splice(0, 1); }; /** * @return {number} */ MyQueue.prototype.peek = function() { return this.queue[0] }; /** * @return {boolean} */ MyQueue.prototype.empty = function() { return this.queue.length === 0; }; /** * Your MyQueue object will be instantiated and called as such: * var obj = new MyQueue() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.peek() * var param_4 = obj.empty() */
Implement Queue using Stacks
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 &lt;= i, j &lt; arr1.length. &nbsp; Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20 &nbsp; Constraints: 2 &lt;= arr1.length == arr2.length &lt;= 40000 -10^6 &lt;= arr1[i], arr2[i] &lt;= 10^6
class Solution(object): def maxAbsValExpr(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf') min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),float('inf'),float('inf'),float('inf') for i,(a,b) in enumerate(zip(arr1,arr2)): ppp=a+b+i if ppp>max_ppp:max_ppp=ppp if ppp<min_ppp:min_ppp=ppp ppm=a+b-i if ppm>max_ppm:max_ppm=ppm if ppm<min_ppm:min_ppm=ppm pmp=a-b+i if pmp>max_pmp:max_pmp=pmp if pmp<min_pmp:min_pmp=pmp pmm=a-b-i if pmm>max_pmm:max_pmm=pmm if pmm<min_pmm:min_pmm=pmm return max(max_ppp-min_ppp,max_ppm-min_ppm,max_pmp-min_pmp,max_pmm-min_pmm)
class Solution { public int maxAbsValExpr(int[] arr1, int[] arr2) { //1. remove the modulas - //i & j are interchangable because they are inside the modulas // A[i] - A[j] + B[i] -B[j] + i-j // A[i] + B[i] + i - B[j] - A[j] - j // (A[i] + B[i] + i) ->X // (B[j] - A[j] - j) -> y // X - Y; //to get max value X should be max & Y should min // Possible cases (Since both arrays have same number of indexes, we can use single for loop & i as index) //A[i] + B[i] + i ->1 //A[i] - B[i] + i ->2 //A[i] + B[i] - i ->3 //A[i] - B[i] - i ->4 // Find out max of all response int arrayLength =arr1.length; int v1[] = new int [arrayLength]; int v2[] = new int [arrayLength] ; int v3[] = new int [arrayLength] ; int v4[] = new int [arrayLength] ; int res = 0; for(int i = 0 ; i< arrayLength; i++) { v1[i] = i + arr1[i] + arr2[i]; v2[i] = i + arr1[i] - arr2[i]; v3[i] = i - arr1[i] + arr2[i]; v4[i] = i - arr1[i] - arr2[i]; } res = Math.max(res,Arrays.stream(v1).max().getAsInt()-Arrays.stream(v1).min().getAsInt()); res = Math.max(res,Arrays.stream(v2).max().getAsInt()-Arrays.stream(v2).min().getAsInt()); res = Math.max(res,Arrays.stream(v3).max().getAsInt()-Arrays.stream(v3).min().getAsInt()); res = Math.max(res,Arrays.stream(v4).max().getAsInt()-Arrays.stream(v4).min().getAsInt()); return res; } }
class Solution { public: int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) { int res=0; int n = arr1.size(); vector<int>v1; vector<int>v2; vector<int>v3; vector<int>v4; for(int i=0;i<n;i++) { v1.push_back(i+arr1[i]+arr2[i]); v2.push_back(i+arr1[i]-arr2[i]); v3.push_back(i-arr1[i]+arr2[i]); v4.push_back(i-arr1[i]-arr2[i]); } res = max(res,*max_element(v1.begin(),v1.end())-*min_element(v1.begin(),v1.end())); res = max(res,*max_element(v2.begin(),v2.end())-*min_element(v2.begin(),v2.end())); res = max(res,*max_element(v3.begin(),v3.end())-*min_element(v3.begin(),v3.end())); res = max(res,*max_element(v4.begin(),v4.end())-*min_element(v4.begin(),v4.end())); return res; } };
var maxAbsValExpr = function(arr1, arr2) { const l1 = [], l2 = [], l3 = [], l4 = [], res = []; for (let i = 0; i < arr1.length; i++) { l1.push(arr1[i] + arr2[i] + i) l2.push(arr1[i] - arr2[i] + i) l3.push(-arr1[i] + arr2[i] + i) l4.push(-arr1[i] - arr2[i] + i) } res.push(Math.max(...l1) - Math.min(...l1)) res.push(Math.max(...l2) - Math.min(...l2)) res.push(Math.max(...l3) - Math.min(...l3)) res.push(Math.max(...l4) - Math.min(...l4)) return Math.max(...res); };
Maximum of Absolute Value Expression
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin. &nbsp; Example 1: Input: root = [3,0,0] Output: 2 Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child. Example 2: Input: root = [0,3,0] Output: 3 Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child. &nbsp; Constraints: The number of nodes in the tree is n. 1 &lt;= n &lt;= 100 0 &lt;= Node.val &lt;= n The sum of all Node.val is n.
# 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 distributeCoins(self, root: Optional[TreeNode]) -> int: def dfs(root): if not root: return 0,0 net_left,left_walk = dfs(root.left) net_right,right_walk = dfs(root.right) # if any node has extra or deficiency in both cases there has to be a walk of abs(extra) or abs(deficiency) return net_left+net_right+(root.val-1), left_walk+right_walk+abs(net_left)+abs(net_right) return dfs(root)[1]
class Solution { int count = 0; public int helper(TreeNode root) { if(root == null) return 0; int left = helper(root.left); int right = helper(root.right); count+= Math.abs(left)+Math.abs(right); return (left+right+root.val-1); } public int distributeCoins(TreeNode root) { helper(root); return count; } }
class Solution { public: int ans = 0; int recr(TreeNode *root) { if(!root) return 0; int left = recr(root->left); int right = recr(root->right); int curr = root->val + left + right; ans += abs(curr-1); return curr-1; } int distributeCoins(TreeNode* root) { recr(root); return ans; } };
var distributeCoins = function(root) { var moves = 0; postorder(root); return moves; function postorder(node){ if(!node) return 0; const subTotal = postorder(node.left) + postorder(node.right); const result = node.val - 1 + subTotal; moves += Math.abs(result); return result; } };
Distribute Coins in Binary Tree
You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique. &nbsp; Example 1: Input: nums = [3,5] Output: 2 Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. Example 2: Input: nums = [0,0] Output: -1 Explanation: No numbers fit the criteria for x. If x = 0, there should be 0 numbers &gt;= x, but there are 2. If x = 1, there should be 1 number &gt;= x, but there are 0. If x = 2, there should be 2 numbers &gt;= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. Example 3: Input: nums = [0,4,3,0,4] Output: 3 Explanation: There are 3 values that are greater than or equal to 3. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 0 &lt;= nums[i] &lt;= 1000
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() for i in range(max(nums)+1): y=len(nums)-bisect.bisect_left(nums,i) if y==i: return i return -1
class Solution { public int specialArray(int[] nums) { int x = nums.length; int[] counts = new int[x+1]; for(int elem : nums) if(elem >= x) counts[x]++; else counts[elem]++; int res = 0; for(int i = counts.length-1; i > 0; i--) { res += counts[i]; if(res == i) return i; } return -1; } }
class Solution { public: int specialArray(vector<int>& nums) { int v[102]; memset(v, 0, sizeof v); for (const auto &n : nums) { ++v[n > 100 ? 100 : n]; } for (int i = 100; i > 0; --i) { v[i] = v[i + 1] + v[i]; if (v[i] == i) return i; } return -1; } };
var specialArray = function(nums) { const freq = new Array(1001).fill(0); for(let n of nums) freq[n]++; for(let i=1000, cnt=0; i>=0; i--){ cnt += freq[i]; if(i==cnt) return i; } return -1; };
Special Array With X Elements Greater Than or Equal X
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1). Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. Return the kth integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo &lt;= x &lt;= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. &nbsp; Example 1: Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --&gt; 6 --&gt; 3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. Example 2: Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7. &nbsp; Constraints: 1 &lt;= lo &lt;= hi &lt;= 1000 1 &lt;= k &lt;= hi - lo + 1
import heapq class Solution: def power(self,n): if n in self.dic: return self.dic[n] if n % 2: self.dic[n] = self.power(3 * n + 1) + 1 else: self.dic[n] = self.power(n // 2) + 1 return self.dic[n] def getKth(self, lo: int, hi: int, k: int) -> int: self.dic = {1:0} for i in range(lo,hi+1): self.power(i) lst = [(self.dic[i],i) for i in range(lo,hi+1)] heapq.heapify(lst) for i in range(k): ans = heapq.heappop(lst) return ans[1]
class Solution { public int getKth(int lo, int hi, int k) { int p = 0; int[][] powerArr = new int[hi - lo + 1][2]; Map<Integer, Integer> memo = new HashMap<>(); for (int i = lo; i <= hi; i++) powerArr[p++] = new int[]{i, getPower(i, memo)}; Arrays.sort(powerArr, (a1, a2) -> a1[1] - a2[1] == 0 ? a1[0] - a2[0] : a1[1] - a2[1]); return powerArr[k - 1][0]; } private int getPower(int i, Map<Integer, Integer> memo) { if (memo.containsKey(i)) return memo.get(i); if (i == 1) return 0; int power = 1 + (i % 2 == 0 ? getPower(i / 2, memo) : getPower(i * 3 + 1, memo)); memo.put(i, power); return power; } }
class Solution { public: int getPower(int num) { if (num == 1) return 0; int res = 0; if (num %2 == 0) res += getPower(num/2); else res += getPower(3*num + 1); res++; return res; } int getKth(int lo, int hi, int k) { multimap<int,int> um; for (int i = lo; i <= hi; i++) { um.insert({getPower(i), i}); } int cnt = 1; int res = 0; for (auto iter = um.begin(); iter != um.end(); iter++) { if (cnt == k) { res = iter->second; } cnt++; } return res; } };
var getKth = function(lo, hi, k) { const dp = new Map(); dp.set(1, 0); const powerVals = []; for(let num = lo; num <= hi; ++num) { powerVals.push([num, findPowerVal(num, dp)]); } const heap = new MinHeap(); heap.build(powerVals); let top; while(k--) { // O(klogn) top = heap.removeTop(); } return top[0]; }; function findPowerVal(num, dp) { if(dp.has(num)) { return dp.get(num); } let powerVal; if(num % 2 === 0) { powerVal = findPowerVal(num/2, dp) + 1; } else { powerVal = findPowerVal(3 * num + 1, dp) + 1; } dp.set(num, powerVal); return dp.get(num); } class Heap { constructor(property) { this.data = []; } size() { return this.data.length; } build(arr) { // O(n) this.data = [...arr]; for(let i = Math.floor((this.size() - 1)/2); i >= 0; --i) { this.heapify(i); } } heapify(i) { // O(logn) const left = 2 * i + 1, right = 2 * i + 2; let p = i; if(left < this.size() && this.compare(left, p)) { p = left; } if(right < this.size() && this.compare(right, p)) { p = right; } if(p !== i) { [this.data[p], this.data[i]] = [this.data[i], this.data[p]]; this.heapify(p); } } removeTop() { // O(logn) if(this.size() === 1) { return this.data.pop(); } const top = this.data[0]; [this.data[0], this.data[this.size() - 1]] = [this.data[this.size() - 1], this.data[0]]; this.data.pop(); this.heapify(0); return top; } } class MinHeap extends Heap { constructor() { super(); } compare(a, b) { return this.data[a][1] < this.data[b][1] || (this.data[a][1] === this.data[b][1] && this.data[a][0] < this.data[b][0]); } }
Sort Integers by The Power Value
You are given the root of a full binary tree with the following properties: Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. The evaluation of a node is as follows: If the node is a leaf node, the evaluation is the value of the node, i.e. True or False. Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children. &nbsp; Example 1: Input: root = [2,1,3,null,null,0,1] Output: true Explanation: The above diagram illustrates the evaluation process. The AND node evaluates to False AND True = False. The OR node evaluates to True OR False = True. The root node evaluates to True, so we return true. Example 2: Input: root = [0] Output: false Explanation: The root node is a leaf node and it evaluates to false, so we return false. &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 &lt;= Node.val &lt;= 3 Every node has either 0 or 2 children. Leaf nodes have a value of 0 or 1. Non-leaf nodes have a value of 2 or 3.
class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: def recur(node): if not node.left and not node.right: #leaf node return True if node.val == 1 else False left = recur(node.left) right = recur(node.right) if node.val == 2: #if node is or return left or right if node.val == 3: #if node is and return left and right return recur(root)
class Solution { public boolean evaluateTree(TreeNode root) { if(root.val == 1) return true; if(root.val == 0) return false; if(root.val == 2) return evaluateTree(root.left) || evaluateTree(root.right); return evaluateTree(root.left) && evaluateTree(root.right); } }
class Solution { public: bool evaluateTree(TreeNode* root) { if (!root->left and !root->right) return root->val; int l = evaluateTree(root->left); int r = evaluateTree(root->right); return (root->val == 2) ? l or r : l and r; } };
/** * @param {TreeNode} root * @return {boolean} */ var evaluateTree = function(root) { return root.val === 3 ? evaluateTree(root.left) && evaluateTree(root.right) : root.val === 2 ? evaluateTree(root.left) || evaluateTree(root.right) : root.val; };
Evaluate Boolean Binary Tree
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "". getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "". Note that each function must run in O(1) average time complexity. &nbsp; Example 1: Input ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] [[], ["hello"], ["hello"], [], [], ["leet"], [], []] Output [null, null, null, "hello", "hello", null, "hello", "leet"] Explanation AllOne allOne = new AllOne(); allOne.inc("hello"); allOne.inc("hello"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "hello" allOne.inc("leet"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "leet" &nbsp; Constraints: 1 &lt;= key.length &lt;= 10 key consists of lowercase English letters. It is guaranteed that for each call to dec, key is existing in the data structure. At most 5 * 104&nbsp;calls will be made to inc, dec, getMaxKey, and getMinKey.
from collections import defaultdict class Set(object): def __init__(self): self._dict = {} self._list = [] self._len = 0 def add(self, v): if v in self._dict: pass else: self._list.append(v) self._dict[v] = self._len self._len += 1 def __contains__(self, item): return item in self._dict def remove(self, v): if v not in self._dict: pass else: idx = self._dict[v] if idx < self._len - 1: self._list[idx] = self._list[-1] self._dict[self._list[idx]] = idx del self._dict[v] self._list.pop() self._len -= 1 def __iter__(self): return iter(self._list) def check(self): assert len(self._dict) == len(self._list) for idx, key in enumerate(self._list): assert self._dict[key] == idx def __len__(self): return self._len def __repr__(self): return f"{self._dict}\n{self._list}" class Node(object): def __init__(self, value): self.value = value self.prev = None self.next = None def set_prev(self, other_node): self.prev = other_node if other_node is not None: other_node.next = self def set_next(self, other_node): self.next = other_node if other_node is not None: other_node.prev = self def __repr__(self): return str(self.value) class SortedKeyList(object): def __init__(self): self.head = Node(value=0) self.tail = Node(value=float("inf")) self.head.set_next(self.tail) def is_empty(self): return self.head.next is self.tail def min_key(self): if self.is_empty(): return None else: return self.head.next.value def max_key(self): if self.is_empty(): return None else: return self.tail.prev.value def incr_key(self, orig_node): orig_value = orig_node.value new_value = orig_value + 1 next_node = orig_node.next if next_node.value == new_value: return self else: new_node = Node(new_value) new_node.set_prev(orig_node) new_node.set_next(next_node) return self def decr_key(self, orig_node): orig_value = orig_node.value new_value = orig_value - 1 prev_node = orig_node.prev if prev_node.value == new_value: return self else: new_node = Node(new_value) new_node.set_next(orig_node) new_node.set_prev(prev_node) return self def delete_node(self, node): prev_node = node.prev next_node = node.next prev_node.set_next(next_node) return self def __repr__(self): a = [] node = self.head.next while True: if node is self.tail: break assert node.next.prev is node assert node.prev.next is node a.append(node.value) node = node.next return str(a) class AllOne: def __init__(self): self.count_list = SortedKeyList() self.counter = defaultdict(lambda: self.count_list.head) self.keyed_by_count = defaultdict(set) def __repr__(self): return f"count_list={self.count_list}\ncounter={dict(self.counter)}\nkeyed_by_count={dict(self.keyed_by_count)}" def inc(self, key: str) -> None: orig_count_node = self.counter[key] orig_count = orig_count_node.value self.count_list.incr_key(orig_count_node) new_count_node = orig_count_node.next new_count = new_count_node.value assert new_count == orig_count + 1 self.counter[key] = new_count_node if key in self.keyed_by_count[orig_count]: self.keyed_by_count[orig_count].remove(key) self.keyed_by_count[new_count].add(key) if len(self.keyed_by_count[orig_count]) == 0: del self.keyed_by_count[orig_count] if orig_count_node.value > 0: self.count_list.delete_node(orig_count_node) def dec(self, key: str) -> None: orig_count_node = self.counter[key] orig_count = orig_count_node.value self.count_list.decr_key(orig_count_node) new_count_node = orig_count_node.prev new_count = new_count_node.value assert new_count == orig_count - 1 self.counter[key] = new_count_node if key in self.keyed_by_count[orig_count]: self.keyed_by_count[orig_count].remove(key) self.keyed_by_count[new_count].add(key) if new_count == 0: del self.counter[key] if len(self.keyed_by_count[orig_count]) == 0: del self.keyed_by_count[orig_count] self.count_list.delete_node(orig_count_node) def getMaxKey(self) -> str: max_count = self.count_list.max_key() if max_count is not None: return next(iter(self.keyed_by_count[max_count])) else: return "" def getMinKey(self) -> str: min_count = self.count_list.min_key() if min_count is not None: return next(iter(self.keyed_by_count[min_count])) else: return "" def drive(m, p): s = AllOne() naive_counter = defaultdict(int) for method, param in zip(m, p): if method in ("inc", "dec"): word = param[0] if method == "inc": s.inc(word) naive_counter[word] += 1 elif method == 'dec': s.dec(word) naive_counter[word] -= 1 if naive_counter[word] == 0: del naive_counter[word] tmp_counter = defaultdict(set) for k, v in naive_counter.items(): tmp_counter[v].add(k) sorted_keys = sorted(tmp_counter.keys()) min_key = sorted_keys[0] max_key = sorted_keys[-1] if s.getMaxKey() not in tmp_counter[max_key]: print("Oh No!!!") return s, naive_counter, tmp_counter if s.getMinKey() not in tmp_counter[min_key]: print("Oh No!!!") return s, naive_counter, tmp_counter return None, None, None if __name__ == '__main__': m = ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] p = [[], ["hello"], ["hello"], [], [], ["leet"], [], []] s, naive_counter, tmp_counter = drive(m, p)
//Intuitions get from the top answer by @AaronLin1992 class AllOne { //Thoughts //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)? //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min //to maintain some kind of ordering, the first thing we think about is arrays/lists, however, arrays/lists when insert and delete in the middle, it is O(N) operation //so instead, a linked list might work //as a result, we considering using Map(s) and LinkedList for our supporting data structures, details below private Map<String, Bucket> stringToBucket; //maps a string to bucket private Map<Integer, Bucket> countToBucket; //maps string count to bucket, note that because when we design this we can have multiple strings in a bucket, that makes it convenient so that for each count, we only need 1 bucket, thus the map data structure private BucketList bucketList; //first, we need to create a class for the LinkedList elements class Bucket { private Bucket prev; private Bucket next; private int count; //recording the count of instances private Set<String> keys; //note that we are using Set of Strings. The reason is because multiple Strings can have the same count and we want to put them in one bucket. This makes the problem easier to solve instead of putting them into different buckets. Bucket() { this.keys = new HashSet<>(); } Bucket(String key) { this(); this.count = 1; this.keys.add(key); } } //second, we need to create a linked list data structure of buckets class BucketList { private Bucket dummyHead; //the fake head before the real head //useful for getMinKey() private Bucket dummyTail; //the fake tail before the real tail //useful for getMaxKey() public BucketList() { dummyHead = new Bucket(); dummyTail = new Bucket(); dummyHead.next = dummyTail; dummyTail.prev = dummyHead; } public Bucket createNewBucket(String key) { Bucket bucket = new Bucket(key); Bucket nextBucket = dummyHead.next; dummyHead.next = bucket; bucket.prev = dummyHead; nextBucket.prev = bucket; bucket.next = nextBucket; return bucket; } public Bucket createBucketToTheRight(Bucket fromBucket, String key, int count) { //initialize Bucket toBucket = new Bucket(key); toBucket.count = count; Bucket nextBucket = fromBucket.next; fromBucket.next = toBucket; toBucket.prev = fromBucket; nextBucket.prev = toBucket; toBucket.next = nextBucket; return toBucket; } public Bucket createBucketToTheLeft(Bucket fromBucket, String key, int count) { //initialize Bucket toBucket = new Bucket(key); toBucket.count = count; Bucket prevBucket = fromBucket.prev; prevBucket.next = toBucket; toBucket.prev = prevBucket; fromBucket.prev = toBucket; toBucket.next = fromBucket; return toBucket; } public boolean clean(Bucket oldBucket) {//clean bucket if bucket does not have any keys if (!oldBucket.keys.isEmpty()) { return false; } removeBucket(oldBucket); return true; } public void removeBucket(Bucket bucket) { Bucket prevBucket = bucket.prev; Bucket nextBucket = bucket.next; prevBucket.next = nextBucket; nextBucket.prev = prevBucket; } } public AllOne() { this.stringToBucket = new HashMap<>(); this.countToBucket = new HashMap<>(); this.bucketList = new BucketList(); } public void inc(String key) { //first check if the string already present if (!stringToBucket.containsKey(key)) { //if not present Bucket bucket = null; //check if there is count of 1 bucket already if (!countToBucket.containsKey(1)) { //if does not contain count of 1 //we need to create a new bucket for count of 1 and add to the head (the minimum). Because count 1 should be the minimum exists in the bucket list bucket = bucketList.createNewBucket(key); } else { //if contains count of 1 //then we just need to add the key to the bucket bucket = countToBucket.get(1); bucket.keys.add(key); } //don't forget to update the maps stringToBucket.put(key, bucket); countToBucket.put(1, bucket); } else { //if the key alreay present //first of all we need to get the current count for the key Bucket oldBucket = stringToBucket.get(key); Bucket newBucket = null; int count = oldBucket.count; count++; //increment 1 //don't forget that we need to remove the key from existing bucket oldBucket.keys.remove(key); //now let's add the key with new count if (countToBucket.containsKey(count)) { //if there is already a bucket for this count //then just add to the set of keys newBucket = countToBucket.get(count); newBucket.keys.add(key); } else { //if there is no bucket for this count, create a new bucket, but where to place it? Ans: to the right of the old bucket newBucket = bucketList.createBucketToTheRight(oldBucket, key, count); } //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list if (bucketList.clean(oldBucket)) { countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed } //don't forget to update the maps stringToBucket.put(key, newBucket); countToBucket.putIfAbsent(count, newBucket); } } public void dec(String key) { //since it is given that "It is guaranteed that key exists in the data structure before the decrement." we don't do additional validation for key exists here Bucket oldBucket = stringToBucket.get(key); Bucket newBucket = null; int count = oldBucket.count; count--; //decrement oldBucket.keys.remove(key); //special scenario - when count == 0 if (count == 0) { stringToBucket.remove(key); } else { //now let's find a new bucket for the decremented count if (countToBucket.containsKey(count)) {//if there is already a bucket for the count newBucket = countToBucket.get(count); newBucket.keys.add(key); } else {//if there is no bucket for the count, then following similar logic as before, we need to add a bucket to the left of the existing bucket newBucket = bucketList.createBucketToTheLeft(oldBucket, key, count); } //don't forget to update the maps stringToBucket.put(key, newBucket); countToBucket.putIfAbsent(count, newBucket); } //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list if (bucketList.clean(oldBucket)) { countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed } } public String getMaxKey() { Set<String> maxSet = bucketList.dummyTail.prev.keys; return maxSet.isEmpty() ? "" : maxSet.iterator().next(); //if maxSet is empty, that means the bucketList don't have actual buckets } public String getMinKey() { Set<String> minSet = bucketList.dummyHead.next.keys; return minSet.isEmpty() ? "" : minSet.iterator().next(); //if minSet is empty, that means the bucketList don't have actual buckets } } /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */
class AllOne { public: map<int,unordered_set<string>> minmax; unordered_map<string,int> count; AllOne() { } void inc(string key) { int was = count[key]++; if(was>0) { minmax[was].erase(key); if(minmax[was].size()==0) minmax.erase(was); } minmax[was+1].insert(key); } void dec(string key) { int was = count[key]--; minmax[was].erase(key); if(minmax[was].size()==0) minmax.erase(was); if(was-1==0) { count.erase(key); }else { minmax[was-1].insert(key); } } string getMaxKey() { return minmax.size() == 0 ? "" : *minmax.rbegin()->second.begin(); } string getMinKey() { return minmax.size() == 0 ? "" : *minmax.begin()->second.begin(); } }; /** * Your AllOne object will be instantiated and called as such: * AllOne* obj = new AllOne(); * obj->inc(key); * obj->dec(key); * string param_3 = obj->getMaxKey(); * string param_4 = obj->getMinKey(); */
var AllOne = function() { this.map = new Map(); this.pre = ''; }; /** * @param {set} map * @param {function} handler * @return {map} */ AllOne.prototype.sort = function(map, handler) { return new Map([...map].sort(handler)); }; /** * @param {string} key * @return {void} */ AllOne.prototype.inc = function(key) { this.map.set(key, this.map.get(key) + 1 || 1); this.pre = 'inc'; }; /** * @param {string} key * @return {void} */ AllOne.prototype.dec = function(key) { this.map.get(key) == 1 ? this.map.delete(key) : this.map.set(key, this.map.get(key) - 1); this.pre = 'dec'; }; /** * @return {string} */ AllOne.prototype.getMaxKey = function() { if (this.pre != 'max') { this.map = this.sort(this.map, (a, b) => b[1] - a[1]); } this.pre = 'max'; return this.map.keys().next().value || ''; }; /** * @return {string} */ AllOne.prototype.getMinKey = function() { if (this.pre != 'min') { this.map = this.sort(this.map, (a, b) => a[1] - b[1]); } this.pre = 'min'; return this.map.keys().next().value || ''; };
All O`one Data Structure
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. &nbsp; Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1 &nbsp; Constraints: 1 &lt;= digits.length &lt;= 9 digits[i].length == 1 digits[i] is a digit from&nbsp;'1'&nbsp;to '9'. All the values in&nbsp;digits are unique. digits is sorted in&nbsp;non-decreasing order. 1 &lt;= n &lt;= 109
class Solution(): def atMostNGivenDigitSet(self, digits, n): cache = {} target = str(n) def helper(idx, isBoundary, isZero): if idx == len(target): return 1 if (idx, isBoundary, isZero) in cache: return cache[(idx, isBoundary, isZero)] res = 0 if isZero and idx != len(target)-1: res+= helper(idx+1, False, True) for digit in digits: if isBoundary and int(digit) > int(target[idx]): continue res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False) cache[(idx, isBoundary, isZero)] = res return res return helper(0, True, True)
class Solution { // DIGIT DP IS LOVE Integer[][][] digitdp; public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) { if (pos == num.length()) { return 1; } int maxDigit = -1; if(digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] !=null) return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0]; if (bound) { maxDigit = num.charAt(pos) - '0'; } else { maxDigit = 9; } int ans = 0; for (int i = 0; i <=maxDigit; i++) { // 0 can only be leading if(i==0 && lead){ ans += solve(num,pos+1,false,dig,lead); }else{ int res = Arrays.binarySearch(dig,i); if(res>=0){ // lead = false; // now it is not possible to 0 to be in lead any more once any other call has been made ans += solve(num, pos + 1, bound & (i == num.charAt(pos)-'0'), dig,false); } } } return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] = ans; } public int atMostNGivenDigitSet(String[] digits, int n) { String num = n + ""; Integer[] dig = new Integer[digits.length]; for(int i=0;i<dig.length;i++){ dig[i] = Integer.parseInt(digits[i]); } digitdp = new Integer[20][2][2]; return solve(num, 0, true, dig,true)-1; } }
class Solution { public: using ll = long long; int countLen(int n) { int cnt = 0; while(n) { cnt++; n /= 10; } return cnt; } vector<int>getDigits(int n) { vector<int>digits; while(n) { digits.push_back(n % 10); n /= 10; } reverse(digits.begin(), digits.end()); return digits; } int solve(int idx, bool flag, vector<int>&digits, vector<int>&number) { if(!flag) { int res = 1; for(int i = idx; i<number.size(); i++) { res *= digits.size(); } return res; } if(idx >= number.size()) return 1; int curr = 0; for(int dig: digits) { if(dig < number[idx]) { curr += solve(idx + 1, false, digits, number); } else if(dig == number[idx]) { curr += solve(idx + 1, true, digits, number); } else break; } return curr; } int atMostNGivenDigitSet(vector<string>& digits, int n) { int len = countLen(n); vector<int>nums; for(string str: digits) { nums.push_back(stoi(str)); } sort(nums.begin(), nums.end()); ll res = 0; for(int i = 1; i<len; i++) { int curr = 1; bool flag = false; for(int j = 0; j<i; j++) { flag = true; curr *= (int)digits.size(); } if(flag) res += curr; } vector<int>number = getDigits(n); res += solve(0, true, nums, number); return res; } };
var atMostNGivenDigitSet = function(digits, n) { const asString = ""+ n; let smaller = 0; let prev = 1; for (let i = asString.length - 1; i >= 0; --i) { const L = asString.length - 1 - i; const num = +asString[i]; let equal = 0; let less = 0; for (let digit of digits) { if (digit == num) { equal = 1; } if (digit > num) { break; } if (digit < num) { less++; } } prev = (less * Math.pow(digits.length, L)) + equal * prev; if (L < asString.length - 1) { smaller += Math.pow(digits.length, L + 1); } } return smaller + prev; };
Numbers At Most N Given Digit Set
You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time. &nbsp; Example 1: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 Output: true Explanation: Circle and rectangle share the point (1,0). Example 2: Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 Output: false Example 3: Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 Output: true &nbsp; Constraints: 1 &lt;= radius &lt;= 2000 -104 &lt;= xCenter, yCenter &lt;= 104 -104 &lt;= x1 &lt; x2 &lt;= 104 -104 &lt;= y1 &lt; y2 &lt;= 104
class Solution: def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool: def find(a1, a2, aCenter): if a1 <= aCenter and aCenter <= a2: return 0 elif a1 > aCenter: return a1 - aCenter else: return aCenter - a2 return (find(x1, x2, xCenter))**2 + (find(y1, y2, yCenter))**2 <= radius**2 ```
class Solution { public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2) + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius; } }
class Solution { public: bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { //nearest_x = x1 when xCenter<x1<x2 (OR) x2 when x1<x2<xCenter (OR) xCenter when x1<xCenter<x2 int nearest_x = (xCenter < x1) ? x1 : (xCenter > x2) ? x2 : xCenter; //same logic for nearest_y as in nearest_x int nearest_y = (yCenter < y1) ? y1 : (yCenter > y2) ? y2 : yCenter; int dist_x = xCenter - nearest_x, dist_y = yCenter - nearest_y; return dist_x * dist_x + dist_y * dist_y <= radius * radius; } };
var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) { const closestX = clamp(xCenter, x1, x2); const closestY = clamp(yCenter, y1, y2); const dist = (xCenter - closestX)**2 + (yCenter - closestY)**2; return dist <= radius * radius ? true : false; function clamp(val, min, max) { if (val < min) return min; if (max < val) return max; return val; } };
Circle and Rectangle Overlapping
An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: 0, 1, and 8 rotate to themselves, 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored), 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid. Given an integer n, return the number of good integers in the range [1, n]. &nbsp; Example 1: Input: n = 10 Output: 4 Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. Example 2: Input: n = 1 Output: 0 Example 3: Input: n = 2 Output: 1 &nbsp; Constraints: 1 &lt;= n &lt;= 104
class Solution: def rotatedDigits(self, n: int) -> int: d={ 0:0, 1:1, 2:5, 3:None, 4: None, 5:2, 6:9, 7:None, 8:8, 9:6 } res=0 for i in range(n+1): t=i pos=0 temp=0 status=True while t>0: r=d[t%10] #Every Digit Rotation Is Must, We Don't Have Choice To Leave It Without Rotating if r is None: status=False break temp+=((10**pos)*r) pos+=1 t=t//10 if temp!=i and status: res+=1 return res
class Solution { public int rotatedDigits(int n) { int ans=0; for(int i=1; i<=n; i++){ int k = i; boolean bool1=true; boolean bool2=false; while(k>0){ int m=k%10; if(m==3 || m==4 || m==7){ bool1=false; break; } else if(m==2 || m==5 || m==6 || m==9){ bool2=true; } k/=10; } if(bool1 && bool2){ ans++; } } return ans; } }
class Solution { public: bool isValid(int n) { bool check = false; while (n > 0) { int k = n % 10; if (k == 2 || k == 5 || k == 6 || k == 9) check = true; if (k == 3 || k == 4 || k == 7) return false; n /= 10; } return check; } int rotatedDigits(int n) { vector<int> dp(n + 1, 0); for (int i = 2; i <= n; i++) { if (isValid(i)) dp[i]++; dp[i] += dp[i - 1]; } return dp[n]; } };
/** * @param {number} n * @return {number} */ var rotatedDigits = function(n) { let count=0; for(let i=1;i<=n;i++){ let str=i.toString().split(""); let f=str.filter(s=> s!=1 && s!=0 && s!=8); if(f.length===0) continue; let g=f.filter(s=> s!=5 && s!=2 && s!=6 && s!=9); if(g.length===0) count++; } return count; };
Rotated Digits
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest. &nbsp; Example 1: Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total. Example 2: Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total. Example 3: Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits. &nbsp; Constraints: 1 &lt;= fruits.length &lt;= 105 fruits[i].length == 2 0 &lt;= startPos, positioni &lt;= 2 * 105 positioni-1 &lt; positioni for any i &gt; 0&nbsp;(0-indexed) 1 &lt;= amounti &lt;= 104 0 &lt;= k &lt;= 2 * 105
class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: arr = [0 for _ in range(2*k+1)] for pos, numOfFruit in fruits: if pos < startPos-k or pos > startPos+k: continue arr[pos-(startPos-k)] += numOfFruit left, right = sum(arr[:k+1]), sum(arr[k:]) maxSeen = max(left, right) turn = 1 # turning point for i in range(2, k+1, 2): left = left-arr[i-2]-arr[i-1]+arr[k+turn] right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn] maxSeen = max(maxSeen, left, right) turn += 1 return maxSeen
class Solution { public int maxTotalFruits(int[][] fruits, int startPos, int k) { int n = fruits.length; int posOfLastFruit = fruits[n-1][0]; int prefixArr[] = new int[posOfLastFruit + 1]; int start = Math.max(startPos - k, 0); int end = Math.min(startPos + k, prefixArr.length-1); if(startPos > posOfLastFruit) { int diff = startPos - posOfLastFruit; startPos = posOfLastFruit; k = k - diff; if(k == 0) return fruits[posOfLastFruit][1]; else if(k < 0) return 0; } for(int i = 0 ; i < n ; i++) { prefixArr[fruits[i][0]] = fruits[i][1]; } int curr = 0; for(int i = startPos-1 ; i >= start ; i--) { curr += prefixArr[i]; prefixArr[i] = curr; } curr = 0; for(int i = startPos+1 ; i <= end ; i++) { curr += prefixArr[i]; prefixArr[i] = curr; } int minimum = prefixArr[startPos]; prefixArr[startPos] = 0; int ans = 0; for(int i = start ; i < startPos ; i++) { int maxCurrPossible = prefixArr[i]; int stepsAlreadyWalked = startPos - i; int stepsRemaining = k - stepsAlreadyWalked; int endIndex = i + stepsRemaining; if(endIndex > startPos && endIndex < prefixArr.length) { maxCurrPossible += prefixArr[endIndex]; } else if(endIndex >= prefixArr.length) { maxCurrPossible += prefixArr[prefixArr.length-1]; } ans = Math.max(ans, maxCurrPossible); } for(int i = startPos+1 ; i <= end ; i++) { int maxCurrPossible = prefixArr[i]; int stepsAlreadyWalked = i - startPos; int stepsRemaining = k - stepsAlreadyWalked; int endIndex = i - stepsRemaining; if(endIndex < startPos && endIndex >= 0) { maxCurrPossible += prefixArr[endIndex]; } else if(endIndex < 0) { maxCurrPossible += prefixArr[0]; } ans = Math.max(ans, maxCurrPossible); } return ans + minimum; } }
class Solution { public: int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) { vector<int> arr; for (int i=0; i<2*k+1; ++i) { arr.push_back(0); } for (int i=0; i<fruits.size(); ++i) { if ((fruits[i][0] < startPos-k) || (fruits[i][0] > startPos+k)) continue; arr[fruits[i][0]-(startPos-k)] += fruits[i][1]; } int left = 0, right = 0; for (int i = 0; i <= k; ++i) { left += arr[i]; right += arr[k+i]; } int maxSeen = max(left, right); int L = arr.size(); int turn = 1; for (int i = 2; i < k+1; i += 2) { left = left+arr[k+turn]-arr[i-1]-arr[i-2]; right = right+arr[k-turn]-arr[L-1-(i-1)]-arr[L-1-(i-2)]; if (left > maxSeen) maxSeen = left; if (right > maxSeen) maxSeen = right; turn++; } return maxSeen; } };
/** * @param {number[][]} fruits * @param {number} startPos * @param {number} k * @return {number} */ var maxTotalFruits = function(fruits, startPos, k) { let n = Math.max(fruits[fruits.length-1][0], startPos)+1; let numFruits = new Array(n).fill(0); let sums = new Array(n).fill(0); for(let obj of fruits) { let [pos, num] = obj; numFruits[pos] = num; } sums[startPos] = numFruits[startPos] ; for(let i = startPos+1; i < n && i <= startPos + k; i++) { sums[i] = sums[i-1] + numFruits[i]; } for(let i = startPos-1; i >=0 && i >= startPos - k; i--) { sums[i] = sums[i+1] + numFruits[i]; } //console.log(sums); let output = 0; for(let leftMoves = k; leftMoves >= 0; leftMoves--) { let rightMoves = Math.max(k - 2*leftMoves, 0); let leftPos = Math.max(0, startPos - leftMoves); let rightPos = Math.min(n-1, startPos + rightMoves); let count = sums[leftPos] + sums[rightPos] - sums[startPos]; output = Math.max(output, count); } for(let rightMoves = k; rightMoves >= 0; rightMoves--) { let leftMoves = Math.max(k - 2*rightMoves, 0); let leftPos = Math.max(0, startPos - leftMoves); let rightPos = Math.min(n-1, startPos + rightMoves); let count = sums[leftPos] + sums[rightPos] - sums[startPos]; output = Math.max(output, count); } return output; };
Maximum Fruits Harvested After at Most K Steps
Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally&nbsp;surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. &nbsp; Example 1: Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] Explanation: Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. Example 2: Input: board = [["X"]] Output: [["X"]] &nbsp; Constraints: m == board.length n == board[i].length 1 &lt;= m, n &lt;= 200 board[i][j] is 'X' or 'O'.
# The question is an awesome example of multi-source bfs. # The intuition is to add the boundary to a heap if it is 'O'. # Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start # convertin all these 'O's to 'E's. # The last step is to traverse the matrix and if the element is still 'O' turn it to 'X' if it is 'E' turn it to 'O' and we get our answer. # Pro-Tip -> Try to reduce the number of append operations in python. The lesser the append operations the better is the runtime! from collections import deque class Solution: def solve(self, bb: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ heap = deque() directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] r, c = len(bb), len(bb[0]) for i in range(r): if bb[i][0] == 'O': heap.append((i, 0)) if bb[i][c - 1] == 'O': heap.append((i, c - 1)) for i in range(1, c - 1): if bb[0][i] == 'O': heap.append((0, i)) if bb[r - 1][i] == 'O': heap.append((r - 1, i)) visited = set() def isValid(nr, nc): if 0 <= nr < r and 0 <= nc < c: return True else: return False while heap: ri, ci = heap.popleft() bb[ri][ci] = 'E' for i, j in directions: nr, nc = ri + i, ci + j if isValid(nr, nc) and (nr, nc) not in visited and bb[nr][nc] == 'O': heap.append((nr, nc)) visited.add((nr, nc)) for i in range(r): for j in range(c): if bb[i][j] == 'O': bb[i][j] = 'X' if bb[i][j] == 'E': bb[i][j] = 'O'
class Solution { boolean isClosed = true; public void solve(char[][] board) { int m = board.length; int n = board[0].length; // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(board[i][j] == 'O' && (i == 0 || j == 0 || i == m-1 || j == n-1) ){ dfs(board, i, j); } } } // revert the temperoray value and also replace remaining O with X for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(board[i][j] == 'T') board[i][j] = 'O'; else if(board[i][j] == 'O') board[i][j] = 'X'; } } } public void dfs(char[][] board, int i, int j){ if(i<0 || j<0 || i>= board.length || j>=board[0].length || board[i][j] != 'O') return; board[i][j] = 'T'; // to put a temperory mark/ to mark as visited dfs(board, i, j+1); // Top dfs(board, i, j-1); // Bottom dfs(board, i+1, j); // Right dfs(board, i-1, j); // Left } }
class Solution { public: int n,m; int visited[201][201] = {0}; // Breadth First Search // Flood Fill Algorithm void bfs(vector<vector<char>>& board, int x, int y){ queue<int> q; q.push(m*x+y); visited[x][y] = 1; int curr,i,j; while(!q.empty()){ curr = q.front(); q.pop(); i = curr/m; j = curr%m; board[i][j] = 'O'; if(i > 0 && !visited[i-1][j] && board[i-1][j] == 'C'){ visited[i-1][j] = 1; q.push(m*(i-1)+j); } if(i < n-1 && !visited[i+1][j] && board[i+1][j] == 'C'){ visited[i+1][j] = 1; q.push(m*(i+1)+j); } if(j > 0 && !visited[i][j-1] && board[i][j-1] == 'C'){ visited[i][j-1] = 1; q.push(m*i+j-1); } if(j < m-1 && !visited[i][j+1] && board[i][j+1] == 'C'){ visited[i][j+1] = 1; q.push(m*i+j+1); } } } void solve(vector<vector<char>>& board) { n = board.size(); m = board[0].size(); // Marking the regions to capture // mark all the O to C for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(board[i][j] == 'O') board[i][j] = 'C'; } } // if we have found C on the outer edges, then all the connected C to it should be // converted to O as they can't be captured for(int i=0; i<m; i++){ if(board[0][i] == 'C' && !visited[0][i]) bfs(board, 0, i); if(board[n-1][i] == 'C' && !visited[n-1][i]) bfs(board, n-1, i); } for(int i=1; i<n-1; i++){ if(board[i][0] == 'C' && !visited[i][0]) bfs(board, i, 0); if(board[i][m-1] == 'C' && !visited[i][m-1]) bfs(board, i, m-1); } // capturing the regions // now remaining C can be capture for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(board[i][j] == 'C') board[i][j] = 'X'; } } } }; static const auto speedup =[](){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }();
// time O(n * m) | space O(1) // We essentially invert this question // Instead of looking whether an 'O' node is surrounded, // we check if an 'O' node is on the edge (outer layer can't be surrounded) // and check if that is connected with any other nodes 'O' nodes (top, down, left, right). // We do no care if it is not connected to an 'O' edge node and thus never dfs for it. var solve = function(board) { if (!board.length) return []; for (let i = 0; i < board.length; i++) { for (let j = 0; j < board[0].length; j++) { // Only dfs if an 'O' and on the edge if (board[i][j] === 'O' && (i === 0 || i === board.length - 1 || j === 0 || j === board[0].length - 1)) { dfs(i, j); } } } for (let i = 0; i < board.length; i++) { for (let j = 0; j < board[0].length; j++) { if (board[i][j] === 'V') { board[i][j] = 'O'; } else { board[i][j] = 'X'; } } } return board; function dfs(r, c) { if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] === 'X' || board[r][c] === 'V') { return; } board[r][c] = 'V'; dfs(r + 1, c); dfs(r - 1, c); dfs(r, c - 1); dfs(r, c + 1); } };
Surrounded Regions
Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1. &nbsp; Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: The only lucky number in the array is 2 because frequency[2] == 2. Example 2: Input: arr = [1,2,2,3,3,3] Output: 3 Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them. Example 3: Input: arr = [2,2,2,3,3] Output: -1 Explanation: There are no lucky numbers in the array. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 500 1 &lt;= arr[i] &lt;= 500
class Solution: def findLucky(self, arr: List[int]) -> int: dc = {} for i in range(len(arr)): if arr[i] not in dc: dc[arr[i]] = 1 else: dc[arr[i]] = dc[arr[i]] + 1 mx = -1 for key,value in dc.items(): if key == value: mx = max(key, mx) return mx
class Solution { public int findLucky(int[] arr) { HashMap<Integer,Integer> map = new HashMap<>(); for(int i : arr){ map.put(i, map.getOrDefault(i,0)+1); } System.out.print(map); int max = 0; for (Map.Entry<Integer, Integer> e : map.entrySet()){ int temp = 0; if(e.getKey() == (int)e.getValue()){ temp = (int)e.getKey(); } if(max < temp){ max= temp; } } if(max != 0)return max; return -1; } }
class Solution { public: int findLucky(vector<int>& arr) { // sort(arr.begin(),arr.end()); map<int,int>mp; vector<int>v; for(int i=0;i<arr.size();i++) { mp[arr[i]]++; } for(auto x:mp) { if(x.first == x.second) { v.push_back(x.first); } } int mx = -1; for(int i=0;i<v.size();i++) { mx = max(mx,v[i]); } return mx; } };
/** * @param {number[]} arr * @return {number} */ var findLucky = function(arr) { let obj = {}; arr.map((num) => { obj[num] = obj[num] + 1 || 1; }); let answer = -1; for (let key in obj) { if (Number(key) === obj[key]) answer = Math.max(answer, Number(key)); } return answer; };
Find Lucky Integer in an Array
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success. Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell. &nbsp; Example 1: Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7 Output: [4,0,3] Explanation: - 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful. - 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful. - 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful. Thus, [4,0,3] is returned. Example 2: Input: spells = [3,1,2], potions = [8,5,8], success = 16 Output: [2,0,2] Explanation: - 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful. - 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. - 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. Thus, [2,0,2] is returned. &nbsp; Constraints: n == spells.length m == potions.length 1 &lt;= n, m &lt;= 105 1 &lt;= spells[i], potions[i] &lt;= 105 1 &lt;= success &lt;= 1010
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: result = self.function(spells,potions,success) return result def function(self,arr1,arr2,success): n2 = len(arr2) arr2.sort() #Sorting Enables Us To Do Binary Search ans = [] for i in arr1: val = math.ceil(success/i) #Finding the Value Of Portion With Least Strength So That It Can Be Greater Than Success idx = bisect.bisect_left(arr2,val) #Finding The Left Most Index So That The Value Can Be Inserted res = n2-idx+1 #Calculating the remaining numbers after finding the suitable index ans.append(res-1) return ans
class Solution { public int[] successfulPairs(int[] spells, int[] potions, long success) { int n = spells.length; int m = potions.length; int[] pairs = new int[n]; Arrays.sort(potions); for (int i = 0; i < n; i++) { int spell = spells[i]; int left = 0; int right = m - 1; while (left <= right) { int mid = left + (right - left) / 2; long product = (long) spell * potions[mid]; if (product >= success) { right = mid - 1; } else { left = mid + 1; } } pairs[i] = m - left; } return pairs; } }
class Solution { public: vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) { vector<int> res; int n(size(potions)); sort(begin(potions), end(potions)); for (auto& spell : spells) { int start(0), end(n); while (start < end) { int mid = start + (end-start)/2; ((long long)spell*potions[mid] >= success) ? end = mid : start = mid+1; } res.push_back(n-start); } return res; } };
/** * @param {number[]} spells * @param {number[]} potions * @param {number} success * @return {number[]} */ var successfulPairs = function(spells, potions, success) { let res = []; potions.sort((a, b) => b-a); let map = new Map(); for(let i=0; i<spells.length; i++){ if(!map.has(spells[i])){ let s = success / spells[i]; let len = search(potions, s); res.push(len); map.set(spells[i], len); }else{ let len = map.get(spells[i]); res.push(len); } } return res; }; function search(potions, target){ let res = 0; let left = 0; let right = potions.length-1; while(left <= right){ let mid = Math.floor((left + right) / 2); if(potions[mid] < target){ right = mid - 1; }else{ left = mid + 1; res = mid + 1; } } return res; }
Successful Pairs of Spells and Potions
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 &lt;= k &lt;= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1. &nbsp; Example 1: Input: grid = ["@.a..","###.#","b.A.B"] Output: 8 Explanation: Note that the goal is to obtain all the keys not to open all the locks. Example 2: Input: grid = ["@..aA","..B#.","....b"] Output: 6 Example 3: Input: grid = ["@Aa"] Output: -1 &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 30 grid[i][j] is either an English letter, '.', '#', or '@'. The number of keys in the grid is in the range [1, 6]. Each key in the grid is unique. Each key in the grid has a matching lock.
class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: m=len(grid) n=len(grid[0]) visited=set() steps=0 q=deque([]) keyCt=0 for i in range(m): for j in range(n): if grid[i][j]=="@": q.append((i,j,'')) elif grid[i][j].islower(): keyCt+=1 while q: for _ in range(len(q)): curr_x,curr_y,keys = q.popleft() if (curr_x,curr_y,keys) in visited: continue visited.add((curr_x,curr_y,keys)) if len(keys)==keyCt: return steps for x,y in ((0,1),(1,0),(-1,0),(0,-1)): nx=curr_x+x ny=curr_y+y if nx<0 or ny<0 or nx>=m or ny>=n or grid[nx][ny]=='#' or (nx,ny,keys) in visited: continue curr=grid[nx][ny] if curr in 'abcdef' and curr not in keys: q.append((nx,ny,keys+curr)) elif curr.isupper() and curr.lower() not in keys: continue else: q.append((nx,ny,keys)) steps+=1 return -1
class Solution { private static final int[][] DIRS = new int[][]{ {1,0}, {-1,0}, {0,1}, {0,-1} }; public int shortestPathAllKeys(String[] grid) { int m = grid.length, n = grid[0].length(); int numKeys = 0, startRow = -1, startCol = -1; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { char c = grid[i].charAt(j); if( isStart(c) ) { startRow = i; startCol = j; } else if( isKey(c) ) numKeys++; } } if( startRow == -1 ) return -1; int keyMask = (1 << numKeys) - 1; State start = new State(startRow, startCol, 0); Queue<State> queue = new LinkedList(); Set<State> visited = new HashSet(); int steps = 0; queue.offer(start); visited.add(start); while( !queue.isEmpty() ) { int size = queue.size(); while( size-- > 0 ) { int i = queue.peek().i; int j = queue.peek().j; int keys = queue.peek().keys; queue.poll(); if( keys == keyMask ) return steps; for(int[] dir : DIRS) { int di = i + dir[0]; int dj = j + dir[1]; int newKeys = keys; if( di < 0 || dj < 0 || di == m || dj == n ) continue; char c = grid[di].charAt(dj); if( isWall(c) ) continue; if( isLock(c) && !isKeyPresent(keys, c) ) continue; if( isKey(c) ) newKeys |= (1 << (c - 'a')); State newState = new State(di, dj, newKeys); if( visited.add(newState) ) queue.offer(newState); } } steps++; } return -1; } private boolean isLock(char c) { return c >= 'A' && c <= 'Z'; } private boolean isKey(char c) { return c >= 'a' && c <= 'z'; } private boolean isWall(char c) { return c == '#'; } private boolean isStart(char c) { return c == '@'; } private boolean isKeyPresent(int keys, char lock) { return (keys & (1 << (lock-'A'))) != 0; } } class State { public int i, j, keys; public State(int i, int j, int keys) { this.i = i; this.j = j; this.keys = keys; } @Override public boolean equals(Object obj) { if( !(obj instanceof State) ) return false; State that = (State)obj; return i == that.i && j == that.j && keys == that.keys; } @Override public int hashCode() { int prime = 31; int hash = 1; hash = hash * prime + i; hash = hash * prime + j; hash = hash * prime + keys; return hash; } }
class Solution { int dirx[4] = {-1,1,0,0}; int diry[4] = {0,0,1,-1}; public: int shortestPathAllKeys(vector<string>& grid) { int n = grid.size(); int m = grid[0].size(); vector<vector<int>> matrix(n, vector<int>(m)); vector<int> lock(7,0); int sx, sy; int lk = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == '@') { sx = i, sy = j; matrix[i][j] = 0; } else if(grid[i][j] == '.') { matrix[i][j] = 0; //cout << grid[i][j]; } else if(grid[i][j] >= 'A' && grid[i][j] <= 'F') { matrix[i][j] = -1*((grid[i][j]-'A') + 1); lock[(grid[i][j]-'A') + 1] = (1 << (grid[i][j]-'A')); } else if(grid[i][j] == '#') matrix[i][j] = -8; else { matrix[i][j] = (1 << (grid[i][j]-'a')); lk++; } //cout << matrix[i][j] << " "; } //cout << endl; } int fnl = (1 << lk) - 1; //cout << fnl; vector<vector<int>> visited(n*m, vector<int>(fnl,1)); queue<pair<pair<int,int>,int>> q; int ans = 0; q.push({{sx,sy},0}); visited[sx*m+sy][0] = 0; while(!q.empty()) { ans++; int sz = q.size(); while(sz--) { int x = q.front().first.first; int y = q.front().first.second; int bit = q.front().second; q.pop(); for(int i = 0; i < 4; i++) { int nxtx = x + dirx[i]; int nxty = y + diry[i]; if(nxtx >= n || nxtx < 0 || nxty >= m || nxty < 0) continue; if(matrix[nxtx][nxty] == -8) continue; if(visited[nxtx*m+nxty][bit] == 0) continue; if(matrix[nxtx][nxty] < 0) { int lkidx = -1*matrix[nxtx][nxty]; if(bit&lock[lkidx]) { q.push({{nxtx,nxty},bit}); visited[nxtx*m+nxty][bit] = 0; } } else if(matrix[nxtx][nxty] == 0) { q.push({{nxtx,nxty},bit}); visited[nxtx*m+nxty][bit] = 0; continue; } else { int fbit = bit | matrix[nxtx][nxty]; if(fbit == fnl) return ans; q.push({{nxtx,nxty},fbit}); visited[nxtx*m+nxty][fbit] = 0; } } } } return -1; } };
var shortestPathAllKeys = function(grid) { const n = grid.length; const m = grid[0].length; function isKey(letter) { return ( letter.charCodeAt(0) >= 'a'.charCodeAt(0) && letter.charCodeAt(0) <= 'z'.charCodeAt(0) ); } function isLock(letter) { return ( letter.charCodeAt(0) >= 'A'.charCodeAt(0) && letter.charCodeAt(0) <= 'Z'.charCodeAt(0) ); } const dns = [ [1, 0], [0, 1], [-1, 0], [0, -1], ]; let start = { x: 0, y: 0, keys: new Set() }; let keyMap = new Map(); for (let y = 0; y < n; ++y) { for (let x = 0; x < m; ++x) { const cell = grid[y][x]; if (cell === '@') { start.x = x; start.y = y; } else if (isKey(cell)) { keyMap.set(cell, [x, y]); } } } function attemptToGetKey(x, y, keys, kx, ky) { let q = [[x, y, keys, 0]]; let v = new Set(); while (q.length) { let nextQueue = []; for (let i = 0; i < q.length; ++i) { const [x, y, keys, steps] = q[i]; if (x === kx && ky === y) { keys.add(grid[ky][kx]); return { keysAcquired: keys, movesUsed: steps }; } const locationHash = x + y * m; if (v.has(locationHash)) continue; v.add(locationHash); const cell = grid[y][x]; if (cell !== '.') { if (isLock(cell) && !keys.has(cell.toLowerCase())) { continue; } if (isKey(cell)) { keys.add(cell); } } for (const [mx, my] of dns) { const nx = x + mx; const ny = y + my; const nextHash = ny * m + nx; if (grid[ny]?.[nx] != null && grid[ny]?.[nx] !== '#') { if (!v.has(nextHash)) { q.push([nx, ny, new Set(Array.from(keys)), steps + 1]); } } } } q = nextQueue; } return { keysAcquired: null, movesUsed: 0 }; } let q = new MinPriorityQueue(); q.enqueue([start.x, start.y, start.keys], 0); while (q.size()) { const { element, priority: steps } = q.dequeue(); const [x, y, keys] = element; if (keys.size === keyMap.size) { return steps; } for (const [key, [kx, ky]] of keyMap) { if (!keys.has(key)) { let { movesUsed, keysAcquired } = attemptToGetKey(x, y, keys, kx, ky); if (movesUsed) { q.enqueue([kx, ky, keysAcquired], movesUsed + steps); } } } } return -1; }
Shortest Path to Get All Keys
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node. Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. For example, it could never contain two consecutive commas, such as "1,,3". Note:&nbsp;You are not allowed to reconstruct the tree. &nbsp; Example 1: Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Example 2: Input: preorder = "1,#" Output: false Example 3: Input: preorder = "9,#,#,1" Output: false &nbsp; Constraints: 1 &lt;= preorder.length &lt;= 104 preorder consist of integers in the range [0, 100] and '#' separated by commas ','.
class Solution: def isValidSerialization(self, preorder: str) -> bool: nodes = preorder.split(',') counter=1 for i, node in enumerate(nodes): if node != '#': counter+=1 else: if counter <= 1 and i != len(nodes) - 1: return False counter-=1 return counter == 0
class Solution { public boolean isValidSerialization(String preorder) { String[] strs = preorder.split(","); //In starting we have one vacany for root int vacancy = 1; for(String str : strs){ if(--vacancy < 0 ) return false; // whenever we encounter a new node vacancy decreases by 1 and left and right two vacancy for that node will added in total if(!str.equals("#")) vacancy += 2; } return vacancy == 0; } }
class Solution { public: bool isValidSerialization(string preorder) { stringstream s(preorder); string str; int slots=1; while(getline(s, str, ',')) { if(slots==0) return 0; if(str=="#") slots--; else slots++; } return slots==0; } };
/** * @param {string} preorder * @return {boolean} */ var isValidSerialization = function(preorder) { let balance = 1 for(const node of preorder.split(',')) if (balance > 0) if (node === '#') --balance else ++balance else return false return balance < 1 }
Verify Preorder Serialization of a Binary Tree
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. &nbsp; Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 200 1 &lt;= nums[i] &lt;= 100
class Solution: def canPartition(self, nums: List[int]) -> bool: total = sum(nums) if total % 2: return False total //= 2 leng = len(nums) dp = [[False] * (total + 1) for _ in range(leng + 1)] for i in range(leng + 1): dp[i][0] = True for i in range(1, leng + 1): for j in range(1, total + 1): dp[i][j] = dp[i-1][j] if j - nums[i-1] >= 0: dp[i][j] |= dp[i-1][j-nums[i-1]] return dp[leng][total]
class Solution { public boolean canPartition(int[] nums) { int sum = 0; for(int i=0; i<nums.length; i++){ sum = sum+nums[i]; } if(sum%2 !=0){ return false; } int[][] dp = new int[nums.length+1][sum]; for(int i=0; i<dp.length; i++){ Arrays.fill(dp[i],-1); } return helper(nums,sum/2,0,dp)>= 1? true : false; } public int helper(int[] nums, int sum, int i, int[][] dp){ if(i==nums.length && sum==0){ return 1; } if(i==nums.length){ return 0; } if(sum < 0){ return 0; } if(dp[i][sum] != -1){ return dp[i][sum]; } if(sum<nums[i]){ return dp[i][sum] = helper(nums,sum,i+1,dp); } int a = helper(nums,sum-nums[i],i+1,dp); //Take the value int b = helper(nums,sum,i+1,dp); //Not take the value if(a==1 || b==1){ // if any of the options is returning true then whole answer would be true return dp[i][sum]=1; }else{ return dp[i][sum]=0; } } }
class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; int n = nums.size(); for(int i = 0;i<n;i++) sum = sum + nums[i]; cout<<sum; if(sum % 2 == 0){ int s = sum/2; int t[n+1][s+1]; for(int i = 0; i<s+1;i++) t[0][i] = false; for(int i = 0;i<n+1;i++) t[i][0] = true; for(int i =1;i<n+1;i++){ for(int j = 1; j<s+1;j++){ if(nums[i-1] <= j) t[i][j] = t[i-1][j-nums[i-1]] || t[i-1][j]; else t[i][j] = t[i-1][j]; } } return t[n][s]; }else return false; } };
var canPartition = function(nums) { let sum = nums.reduce((prevVal, currValue) => prevVal + currValue, 0); // sum of each values if (sum % 2 !== 0) return false; // return false if odd sum let target = sum / 2; // ex.[1,5,11,5] target is half which is 11 let dp = new Set(); // add unique values dp.add(0); //intialize with 0 for (var i = nums.length - 1; i >= 0; i--) { //start from end nextDp = new Set(); for (const ele of dp.values()) { let newVal = ele + nums[i]; if(newVal === target) return true; nextDp.add(newVal); } dp = new Set([...dp, ...nextDp]); } return false; };
Partition Equal Subset Sum
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0. &nbsp; Example 1: Input: s = "QWER" Output: 0 Explanation: s is already balanced. Example 2: Input: s = "QQWE" Output: 1 Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced. Example 3: Input: s = "QQQW" Output: 2 Explanation: We can replace the first "QQ" to "ER". &nbsp; Constraints: n == s.length 4 &lt;= n &lt;= 105 n is a multiple of 4. s contains only 'Q', 'W', 'E', and 'R'.
class Solution: def balancedString(self, s): count = collections.Counter(s) res = n = len(s) if all(n/4==count[char] for char in 'QWER'): return 0 left = 0 for right, char in enumerate(s): # replace char whose index==right to check if it is balanced count[char] -= 1 # if it is balanced, window shrinks to get the smallest length of window while left <= right and all(n / 4 >= count[char] for char in 'QWER'): res = min(res, right - left + 1) count[s[left]] =count[s[left]]+ 1 left += 1 return res
class Solution { public int balancedString(String s) { int n = s.length(), ans = n, excess = 0; int[] cnt = new int[128]; cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4; for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be removed. if (excess == 0) return 0; for (int i = 0, j = 0; i < n; i++){//i = window right end, j = window left end if (--cnt[s.charAt(i)] == 0) excess--; //remove letter at index i while (excess == 0){ //if no more excess, then if (++cnt[s.charAt(j)] == 1) excess++; //we put letter at index j back ans = Math.min(i - j + 1, ans);; //and update ans accordingly j++; } } return ans; } }
class Solution { public: int balancedString(string s) { int n=s.length(); unordered_map<char,int>umap; for(auto x:s) { umap[x]++; } umap['Q']=umap['Q']-n/4>0?umap['Q']-n/4:0; umap['W']=umap['W']-n/4>0?umap['W']-n/4:0; umap['E']=umap['E']-n/4>0?umap['E']-n/4:0; umap['R']=umap['R']-n/4>0?umap['R']-n/4:0; int count=umap['Q']+umap['W']+umap['E']+umap['R']; if(count==0) return 0; int i=0,ans=INT_MAX; unordered_map<char,int>newMap; for(int j=0;j<n;j++) { newMap[s[j]]++; if(newMap[s[j]]<=umap[s[j]]) { count--; while(count==0) { newMap[s[i]]--; if(newMap[s[i]]<umap[s[i]]) { count++; ans=min(ans,j-i+1); } i++; } } } return ans; } };
var balancedString = function(s) { let output = Infinity; let map = {"Q":0, "W":0, "E":0, "R":0}; for(let letter of s){ map[letter]++; } let valueGoal = s.length / 4 let remainder = 0; let count = 4; for(let [key, val] of Object.entries(map)){ if(val > valueGoal){ remainder = remainder + (val - valueGoal); } if(val === valueGoal || val < valueGoal){ map[key] = -Infinity; count--; } } if(remainder === 0){ return 0; } let left = 0; let right = 0; while(right < s.length){ if(map[s[right]] !== -Infinity){ map[s[right]]--; if(map[s[right]] === valueGoal){ count--; } } while(count === 0){ output = Math.min(output, right - left + 1); if(map[s[left]] !== -Infinity){ map[s[left]]++; if(map[s[left]] > valueGoal){ count++; } } left++ } right++; } return output; };
Replace the Substring for Balanced String
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: -1: Your guess is higher than the number I picked (i.e. num &gt; pick). 1: Your guess is lower than the number I picked (i.e. num &lt; pick). 0: your guess is equal to the number I picked (i.e. num == pick). Return the number that I picked. &nbsp; Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1 &nbsp; Constraints: 1 &lt;= n &lt;= 231 - 1 1 &lt;= pick &lt;= n
class Solution: def guessNumber(self, n: int) -> int: l=1 h=n while l<=h: mid=(l+h)//2 x =guess(mid) if(x==0): return mid elif(x==1): l = mid+1 else: h = mid-1
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { int left = 1; int right = n; while(left < right){ int mid = ((right - left) / 2) + left; if(guess(mid) == 0) return mid; else if(guess(mid) < 0) right = mid - 1; else left = mid + 1; } return left; } }
class Solution { public: int guessNumber(int n) { int s = 1, e = n; int mid = s + (e - s)/2; while (s <= e){ if (guess(mid) == 0){ return mid; } else if (guess(mid) == -1){ e = mid - 1; } else if (guess(mid) == 1){ s = mid +1; } mid = s + (e - s)/2; } return mid; } };
/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * var guess = function(num) {} */ /** * @param {number} n * @return {number} */ var guessNumber = function(n) { let lower=1; let higher=n; while(lower<=higher){ let mid=Math.floor((lower+higher)/2); if(guess(mid)==0){ return mid; } else if(guess(mid)==-1){ higher=mid-1; } else{ lower=mid+1; } } return 0; };
Guess Number Higher or Lower
A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic: 1, 1, 2, 5, 7 You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. &nbsp; Example 1: Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5] Output: [true,false,true] Explanation: In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence. In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence. Example 2: Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10] Output: [false,true,false,false,true,true] &nbsp; Constraints: n == nums.length m == l.length m == r.length 2 &lt;= n &lt;= 500 1 &lt;= m &lt;= 500 0 &lt;= l[i] &lt; r[i] &lt; n -105 &lt;= nums[i] &lt;= 105
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: out=[] for i, j in zip(l, r): out.append(self.canMakeArithmeticProgression(nums[i:j+1])) return out def canMakeArithmeticProgression(self, arr: List[int]) -> bool: minArr = min(arr) maxArr = max(arr) # if difference between minArr and maxArr cannot be divided into equal differences, then return false if (maxArr-minArr)%(len(arr)-1)!=0: return False # consecutive difference in arithmetic progression diff = int((maxArr-minArr)/(len(arr)-1)) if diff == 0: if arr != [arr[0]]*len(arr): return False return True # array to check all numbers in A.P. are present in input array. # A.P.[minArr, minArr+d, minArr+2d, . . . . . . . maxArr] check = [1]*len(arr) for num in arr: if (num-minArr)%diff != 0: return False check[(num-minArr)//diff]=0 # if 1 is still in check array it means at least one number from A.P. is missing from input array. if 1 in check: return False return True
class Solution { public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { List<Boolean> result = new ArrayList<>(); int L = nums.length, ll = l.length,ind=0; for(int i=0;i<ll;i++){ int[] arr = new int[r[i]-l[i]+1]; ind=0; for(int k=l[i];k<=r[i];k++){ arr[ind] =nums[k]; ind++; } Arrays.sort(arr); result.add(isArithmetic(arr)); } return result; } public boolean isArithmetic(int[] nums) { int L = nums.length; boolean b = true; if(L<=2) return true; for(int i=1;i<L-1;i++){ if(nums[i]-nums[i-1]!=nums[i+1]-nums[i]) return false; } return b; } }
class Solution { public: vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) { vector<bool> ans(l.size(),false); for(int i=0;i<l.size();i++) { //if the sub array size is equal to 2 if(r[i]-l[i]+1==2) ans[i]=true; else if(isArthemetic(nums,l[i],r[i])) ans[i]=true; } return ans; } //return true if the sub array can be rearranged in a arthemetic sequence bool isArthemetic(vector<int>& nums,int start,int end) { //get the maximum and min elements int mini=INT_MAX; int maxi=INT_MIN; for(int i=start;i<=end;i++) { mini=min(nums[i],mini); maxi=max(nums[i],maxi); } //when mini==maxi it means all the elements are same in the sub array if(mini==maxi) return true; //we cant have same common difference betweeen two adjacent elements //when we arrange in arthemetic sequence if((maxi-mini)%(end-start)!=0) return false; //the diff between every two integers when we rearrange sub array int diff=(maxi-mini)/(end-start); //to check if the duplicate elemnts are present //ex- [2,4,6,6] //6 is repeating two times vector<bool> present(end-start+1,false); for(int i=start;i<=end;i++) { //we cant set a index of nums[i] if((nums[i]-mini)%diff!=0) return false; int ind=(nums[i]-mini)/diff; // same element is alreeady repeated ( 6 in the above example) if(present[ind]) return false; //mark it presence present[ind]=true; } return true; } };
/** * @param {number[]} nums * @param {number[]} l * @param {number[]} r * @return {boolean[]} */ var checkArithmeticSubarrays = function(nums, l, r) { let result = []; for(let i=0;i<l.length;i++) { let subNums = [...nums].slice(l[i], r[i]+1); subNums = subNums.sort((a,b) => a-b); let diff = subNums[1]-subNums[0]; let s = true for(let j=0;j<subNums.length-1;j++) { if(!(subNums[j+1]-subNums[j] == diff)) s = false } result.push(s) } return result };
Arithmetic Subarrays
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. &nbsp; Example 1: Input: arr = [15,88], pieces = [[88],[15]] Output: true Explanation: Concatenate [15] then [88] Example 2: Input: arr = [49,18,16], pieces = [[16,18,49]] Output: false Explanation: Even though the numbers match, we cannot reorder pieces[0]. Example 3: Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] Output: true Explanation: Concatenate [91] then [4,64] then [78] &nbsp; Constraints: 1 &lt;= pieces.length &lt;= arr.length &lt;= 100 sum(pieces[i].length) == arr.length 1 &lt;= pieces[i].length &lt;= arr.length 1 &lt;= arr[i], pieces[i][j] &lt;= 100 The integers in arr are distinct. The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: keys, ans = {}, [] for piece in pieces: keys[piece[0]] = piece for a in arr: if a in keys: ans.extend(keys[a]) return ''.join(map(str, arr)) == ''.join(map(str, ans))
class Solution { public boolean canFormArray(int[] arr, int[][] pieces) { HashMap<Integer,int[]> hm = new HashMap(); for(int[] list:pieces) hm.put(list[0],list); int index = 0; while(index<arr.length){ if(!hm.containsKey(arr[index])) return false; int[] list = hm.get(arr[index]); for(int val:list){ if(index>=arr.length || val!=arr[index]) return false; index++; } } return true; } }
class Solution { public: bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) { map<int,vector<int>> mp; // map the 1st element in pieces[i] to pieces[i] for(auto p:pieces) mp[p[0]] = p; vector<int> result; for(auto a:arr) { if(mp.find(a)!=mp.end()) result.insert(result.end(),mp[a].begin(),mp[a].end()); } return result ==arr; } };
var canFormArray = function(arr, pieces) { let total = ""; arr=arr.join(""); for (let i = 0; i < pieces.length; i++) { pieces[i] = pieces[i].join(""); total += pieces[i]; if (arr.indexOf(pieces[i]) == -1) return false; } return total.length == arr.length; };
Check Array Formation Through Concatenation
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. &nbsp; Example 1: Input: n = 27 Output: true Example 2: Input: n = 0 Output: false Example 3: Input: n = 9 Output: true &nbsp; Constraints: -231 &lt;= n &lt;= 231 - 1 &nbsp; Follow up: Could you solve it without loops/recursion?
class Solution: def isPowerOfThree(self, n: int) -> bool: return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False
class Solution { public boolean isPowerOfThree(int n) { if(n==1){ return true; } if(n<=0){ return false; } if(n%3 !=0 && n>1){ return false; } else{ return isPowerOfThree(n/3); // recurssion } } }
class Solution { public: bool isPowerOfThree(int n) { if(n<=0){return false;} if(n>pow(2, 31)-1 || n<pow(2, 31)*(-1)){return false;} return 1162261467%n==0; } };
var isPowerOfThree = function(n) { if(n === 1){return true;} if(n === 0){return false;} n/=3; if(n%3 != 0 && n != 1){ return false; }else{ let x = isPowerOfThree(n); return x; } };
Power of Three
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. &nbsp; Example 1: Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: Input: stones = [0,1,2,3,4,8,9,11] Output: false Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. &nbsp; Constraints: 2 &lt;= stones.length &lt;= 2000 0 &lt;= stones[i] &lt;= 231 - 1 stones[0] == 0 stones&nbsp;is sorted in a strictly increasing order.
class Solution: def possible(self, i, n, stones, pos, allowedJumps): if i == n - 1: return True key = tuple([i] + allowedJumps) if key in self.cache: return self.cache[key] for jump in allowedJumps: if jump > 0 and stones[i] + jump in pos: if self.possible(pos[stones[i] + jump], n, stones, pos, [jump - 1, jump, jump + 1]): self.cache[key] = True return True self.cache[key] = False return False def canCross(self, stones: List[int]) -> bool: n = len(stones) pos = {} for i, stone in enumerate(stones): pos[stone] = i self.cache = {} return self.possible(0, n, stones, pos, [1])
class Solution { static boolean flag = false; // If flag is true no more operations in recursion, directly return statement public boolean canCross(int[] stones) { int i = 0; // starting stone int k = 1; // starting jump flag = false; return canBeCrossed(stones, k, i); } public boolean canBeCrossed(int[] stones, int k, int i){ if(!flag){ // If flag is false if(stones[i] + k == stones[stones.length - 1]){ // If frog do 'k' jump from current stone lands on last stones, no more recusive calls and return true flag = true; return true; } // If frog do 'k' jump from current stone crosses last stone or not able to reach next stone //return false if((stones[i] + k > stones[stones.length - 1]) || (stones[i]+k<stones[i+1])) return false; int temp = i+1; // identify which next stone frog can reach //Find untill which stone frog can jump //So jump from current stone not greater than next possible stone exit loop while(stones[i]+k > stones[temp]) temp++; //If loop exited 2 condition possible //jump from current stone is reached next possible stone //or not //If next possible stone reached //then do all possible jumps from this stone //the current stone is 'temp' //possible jumps are 'k-1', k, 'k+1' if(stones[i]+k == stones[temp]) return (canBeCrossed(stones, k+1, temp) || canBeCrossed(stones, k, temp) || canBeCrossed(stones,k-1,temp)); //If next possible stone not reached means jump from the current stone can't reach any stone //hence return false else return false; } else return true; } }
class Solution { public: bool canCross(vector<int>& stones) { unordered_map<int,bool>mp; //to see the position where stone is present for(int i=0;i<stones.size();i++) { mp[stones[i]]=true; } int stone=1; //current stone int jump=1; //jump made int last_stone=stones[stones.size()-1]; //last stone on which frog will land to cross river map<pair<int,int>,bool>dp; return fun(mp,stone,jump,dp,last_stone); } bool fun( unordered_map<int,bool>&mp,int stone,int jump,map<pair<int,int>,bool>&dp,int &ls) { if(stone==ls) //reached last stone { return true; } if(mp.find(stone)==mp.end()) //stone is not present { return false; } if(dp.find({stone,jump})!=dp.end()) { return dp[{stone,jump}]; } bool jump1=false; bool jump2=false; bool jump3=false; if((stone+jump-1)>stone) //can take jump of k-1 units { jump1=fun(mp,stone+jump-1,jump-1,dp,ls); } if((stone+jump)>stone) //can take jump of k units { jump2=fun(mp,stone+jump,jump,dp,ls); } if((stone+jump+1)>stone) //can take jump of k+1 units { jump3=fun(mp,stone+jump+1,jump+1,dp,ls); } dp[{stone,jump}]=jump1 or jump2 or jump3; return dp[{stone,jump}]; } };
var canCross = function(stones) { let hash = {}; function dfs(idx = 0, jumpUnits = 0) { let key = `${idx}-${jumpUnits}`; if (key in hash) return hash[key]; if (idx === stones.length - 1) return true; if (idx >= stones.length) return false; let minJump = jumpUnits - 1, maxJump = jumpUnits + 1; for (let i = idx + 1; i < stones.length; i++) { let jump = stones[i] - stones[idx]; if (jump >= minJump && jump <= maxJump) { if (dfs(i, jump)) return hash[idx] = true; } else if (jump > maxJump) break; } return hash[key] = false; } return dfs(); };
Frog Jump
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. &nbsp; Example 1: Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]] Explanation: [[3,1]] is also accepted. Example 2: Input: n = 2, connections = [[0,1]] Output: [[0,1]] &nbsp; Constraints: 2 &lt;= n &lt;= 105 n - 1 &lt;= connections.length &lt;= 105 0 &lt;= ai, bi &lt;= n - 1 ai != bi There are no repeated connections.
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: dic = collections.defaultdict(list) for c in connections: u, v = c dic[u].append(v) dic[v].append(u) timer = 0 depth, lowest, parent, visited = [float("inf")]*n, [float("inf")]*n, [float("inf")]*n, [False]*n res = [] def find(u): nonlocal timer visited[u] = True depth[u], lowest[u] = timer, timer timer += 1 for v in dic[u]: if not visited[v]: parent[v] = u find(v) if lowest[v]>depth[u]: res.append([u,v]) if parent[u]!=v: lowest[u] = min(lowest[u], lowest[v]) find(0) return res
class Solution { // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) { List<Integer>[] graph = new ArrayList[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for(List<Integer> oneConnection :connections) { graph[oneConnection.get(0)].add(oneConnection.get(1)); graph[oneConnection.get(1)].add(oneConnection.get(0)); } int timer[] = new int[1]; List<List<Integer>> results = new ArrayList<>(); boolean[] visited = new boolean[n]; int []timeStampAtThatNode = new int[n]; criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode); return results; } public void criticalConnectionsUtil(List<Integer>[] graph, int parent, int node, int timer[], boolean[] visited, List<List<Integer>> results, int []timeStampAtThatNode) { visited[node] = true; timeStampAtThatNode[node] = timer[0]++; int currentTimeStamp = timeStampAtThatNode[node]; for(int oneNeighbour : graph[node]) { if(oneNeighbour == parent) continue; if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode); timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]); if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour)); } } }
class Solution { int timer = 1; public: void dfs(vector<int>adj[] , int node , int parent , vector<int>&tin , vector<int>&low , vector<int>&vis , vector<vector<int>>&ans) { vis[node] = 1; tin[node] = low[node] = timer; timer++; for(auto it:adj[node]) { if(it == parent) continue; if(vis[it] == 0) { dfs(adj , it , node , tin , low , vis , ans); low[node] = min(low[node] , low[it]); if(tin[node] < low[it]) ans.push_back({node , it}); } else { low[node] = min(low[node] , low[it]); } } } vector<vector<int>> criticalConnections(int n, vector<vector<int>>& con) { vector<int>adj[n]; for(int i = 0;i<con.size();i++) { adj[con[i][0]].push_back(con[i][1]); adj[con[i][1]].push_back(con[i][0]); } vector<vector<int>>ans; vector<int>vis(n , 0) , tin(n , 0) , low(n , 0); dfs(adj , 0 , -1 , tin , low , vis , ans); return ans; } };
var criticalConnections = function(n, connections) { // Graph Formation const graph = new Map(); connections.forEach(([a, b]) => { const aconn = graph.get(a) || []; const bconn = graph.get(b) || []; aconn.push(b), bconn.push(a); graph.set(a, aconn); graph.set(b, bconn); }); // Find Bridges const bridges = []; const visited = new Array(n).fill(false); const tin = new Array(n).fill(-1); const dis = new Array(n).fill(-1); let time = 0; const dfs = (node, parent = -1) => { visited[node] = true; ++time; tin[node] = time; dis[node] = time; const connections = graph.get(node); for(let conn of connections) { if(conn == parent) { continue; } if(visited[conn]) { dis[node] = Math.min(dis[node], tin[conn]); } else { dfs(conn, node); dis[node] = Math.min(dis[node], dis[conn]); if(dis[conn] > tin[node]) { bridges.push([node, conn]); } } }; } dfs(0); return bridges; };
Critical Connections in a Network
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. &nbsp; Example 1: Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 Output: 7 Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. Example 2: Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 Output: 10 Explanation: Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. Example 3: Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 Output: 9 Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. &nbsp; Constraints: 1 &lt;= k &lt;= events.length 1 &lt;= k * events.length &lt;= 106 1 &lt;= startDayi &lt;= endDayi &lt;= 109 1 &lt;= valuei &lt;= 106
import bisect from functools import lru_cache class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: if k == 1: # optimization for TLE test case 57/67 return max([event[2] for event in events]) events.sort() event_starts = [event[0] for event in events] # enables binary search @lru_cache(None) def dp(i, j): if j == 0: # out of turns return 0 if i >= len(events): # end of events array return 0 max_score = events[i][2] # get minimum index where start day is greater than current end day next_index_minimum = bisect.bisect_left(event_starts, events[i][1] + 1) # check each possibility from the minimum next index until end of the array for k in range(next_index_minimum, len(events)): max_score = max(max_score, events[i][2] + dp(k, j - 1)) # check if we can get a better score if we skip this index altogether max_score = max(max_score, dp(i + 1, j)) return max_score return dp(0, k)
class Solution { public int maxValue(int[][] events, int k) { Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0])); return maxValue(events, 0, k, 0, new int[k+1][events.length]); } private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEndDay, int[][] dp) { // Return 0 if no events are left or maximum choice is reached if (index >= events.length || remainingEvents == 0) return 0; // An Event cannot be picked if the previous event has not completed before current event if (lastEventEndDay >= events[index][0]) return maxValue(events, index+1, remainingEvents, lastEventEndDay, dp); // Return the value if the solution is already available if (dp[remainingEvents][index] != 0) return dp[remainingEvents][index]; // There are 2 choices that we can make, // SKIP this meeting or PICK this meeting return dp[remainingEvents][index] = Math.max( maxValue(events, index+1, remainingEvents, lastEventEndDay, dp), // skip maxValue(events, index+1, remainingEvents-1, events[index][1], dp) + events[index][2] // pick ); } }
class Solution { public: int ans; unordered_map<int,unordered_map<int,unordered_map<int,int>>> dp; int Solve(vector<vector<int>>& events, int start, int n, int k, int endtime){ if(k == 0 || start == n){ return 0; } if(dp.find(start) != dp.end() && dp[start].find(k) != dp[start].end() && dp[start][k].find(endtime) != dp[start][k].end()){ return dp[start][k][endtime]; } int t1 = 0; if(events[start][0] > endtime){ t1 = events[start][2] + Solve(events, start+1, n, k-1, events[start][1]); } int t2 = Solve(events,start+1,n,k,endtime); dp[start][k][endtime] = max(t1,t2); // cout<< dp[start][k][endtime]<<endl; return dp[start][k][endtime]; } int maxValue(vector<vector<int>>& events, int k) { dp.clear(); // sort according to start time sort(events.begin(), events.end(),[](vector<int> &a,vector<int> &b){ return a[0] < b[0]; }); return Solve(events,0,events.size(),k,0); } };
/** * @param {number[][]} events * @param {number} k * @return {number} */ var maxValue = function(events, k) { events = events.sort((a, b) => a[1] - b[1]); const n = events.length; var ans = 0; var dp = Array.from(Array(k+1), () => new Array(n).fill(0)); for(let i = 0; i < n; i++) { dp[1][i] = Math.max((i ? dp[1][i-1] :0), events[i][2]); ans = Math.max(dp[1][i], ans); } function binarySearch(l, r, target) { var pos = -1; while(l <= r) { const mid = Math.floor((l+r)/2); if (events[mid][1] < target) { pos = mid; l = mid+1; } else r = mid-1; } return pos; } for(let i = 0; i < n; i++) { const j = binarySearch(0, i-1, events[i][0]); for(let l = 2; l <= k; l++) { dp[l][i] = Math.max(( j >= 0 ? dp[l-1][j] + events[i][2] : 0), (i ? dp[l][i-1] : 0)); ans = Math.max(dp[l][i], ans); } } return ans; };
Maximum Number of Events That Can Be Attended II
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center). randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y]. &nbsp; Example 1: Input ["Solution", "randPoint", "randPoint", "randPoint"] [[1.0, 0.0, 0.0], [], [], []] Output [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] Explanation Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return [-0.02493, -0.38077] solution.randPoint(); // return [0.82314, 0.38945] solution.randPoint(); // return [0.36572, 0.17248] &nbsp; Constraints: 0 &lt;&nbsp;radius &lt;= 108 -107 &lt;= x_center, y_center &lt;= 107 At most 3 * 104 calls will be made to randPoint.
class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.rad = radius self.xc = x_center self.yc = y_center def randPoint(self) -> List[float]: while True: xg=self.xc+random.uniform(-1, 1)*self.rad*2 yg=self.yc+random.uniform(-1, 1)*self.rad*2 if (xg-self.xc)**2 + (yg-self.yc)**2 <= self.rad**2: return [xg, yg] # Your Solution object will be instantiated and called as such: # obj = Solution(radius, x_center, y_center) # param_1 = obj.randPoint()
class Solution { double radius; double x_center; double y_center; Random r=new Random(); public Solution(double radius, double x_center, double y_center) { this.radius=radius; this.x_center=x_center; this.y_center=y_center; } public double[] randPoint() { double angle=r.nextDouble(Math.PI*2); //For probability is inversely proportional to radius, we use sqrt of random number. double rad=Math.sqrt(r.nextDouble())*radius; double[] ret=new double[2]; ret[0]=rad*Math.cos(angle)+x_center; ret[1]=rad*Math.sin(angle)+y_center; return ret; } }
class Solution { public: double r,x,y; Solution(double radius, double x_center, double y_center) { r = radius; x = x_center; y = y_center; } vector<double> randPoint() { double x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r); double y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r); while(solve(x_r,y_r,x,y)>=r*r) { x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r); y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r); } return {x_r,y_r}; } double solve(double x_r,double y_r,double x,double y) { return (x-x_r)*(x-x_r) + (y-y_r)*(y-y_r); } };
/** * @param {number} radius * @param {number} x_center * @param {number} y_center */ var Solution = function(radius, x_center, y_center) { this.radius = radius; this.x_center = x_center; this.y_center = y_center; }; /** * @return {number[]} */ Solution.prototype.randPoint = function() { const randomX = randRange(this.x_center + this.radius, this.x_center - this.radius); const randomY = randRange(this.y_center + this.radius, this.y_center - this.radius); const distanceInSquares = Math.pow(randomX - this.x_center, 2) + Math.pow(randomY - this.y_center, 2); const isOutOfTheCircle = distanceInSquares > Math.pow(this.radius, 2); if (isOutOfTheCircle)) { return this.randPoint(); } return [randomX, randomY]; }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(radius, x_center, y_center) * var param_1 = obj.randPoint() */ function randRange(maximum, minimum) { return Math.random() * (maximum - minimum) + minimum; }
Generate Random Point in a Circle
You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters. &nbsp; Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3. Example 2: Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6. Example 3: Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5. &nbsp; Constraints: 1 &lt;= text.length &lt;= 2 * 104 text consist of lowercase English characters only.
class Solution: def maxRepOpt1(self, text: str) -> int: char_groups = [] for char, group in groupby(text): group_len = len(list(group)) char_groups.append((char, group_len)) char_count = Counter(text) longest_substr_len = 1 # Each char itself is substring of len 1 # Scenario-1: Get the longest substr length by just adding one more char to each group for char, group_len in char_groups: # NOTE: If the total count of the char across full string is < group_len+1, # make sure to take the total count only # # It means we don't have any extra char occurrence which we can add to the current group group_len_w_one_addition = min(group_len+1, char_count[char]) longest_substr_len = max(longest_substr_len, group_len_w_one_addition) # Scenario-2: # If there are two groups of same char, separated by a group of different char with length=1: # 1) We can either swap that one char in the middle with the same char as those two groups # Ex: 'aaa b aaa c a' # - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index # - So after swapping, it will become 'aaa a aaa c b' # - hence longest substr len of same char 'a' = 7 # # 2) We can merge the two groups # Ex: 'aaa b aaa' # -> here there are two groups of char 'a' with len = 3 each. # -> they are separated by a group of char 'b' with len = 1 # -> hence, we can merge both groups of char 'a' - so that longest substr len = 6 # -> basically, swap the 'b' with 'a' at very last index # -> the final string will look like 'aaaaaa b' # # We will take max length we can get from above two options. # # Since we need to check the group prior to curr_idx "i" and also next to curr_idx "i"; # we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive for i in range(1, len(char_groups)-1): prev_group_char, prev_group_len = char_groups[i-1] curr_group_char, curr_group_len = char_groups[i] next_group_char, next_group_len = char_groups[i+1] if curr_group_len != 1 or prev_group_char != next_group_char: continue len_after_swapping = min(prev_group_len + next_group_len + 1, char_count[next_group_char]) longest_substr_len = max(longest_substr_len, len_after_swapping) return longest_substr_len
class Solution { public int maxRepOpt1(String s) { int[] count = new int[26]; int[] left = new int[s.length()]; int[] right = new int[s.length()]; int max =0; // Left Array Containing Length Of Subarray Having Equal Characters Till That Index for(int i=0;i<s.length();i++){ count[s.charAt(i) -'a']++; if(i> 0){ if(s.charAt(i) == s.charAt(i-1)){ left[i] = left[i-1]+1; }else{ left[i] = 1; } }else{ left[i] =1; } max = Math.max(max,left[i]); } // Right Array Containing Length Of Subarray Having Equal Characters Till That Index for(int i=s.length()-1;i>=0;i--){ if(i < s.length()-1){ if(s.charAt(i+1) == s.charAt(i)){ right[i] = right[i+1] +1; }else{ right[i] =1; } }else{ right[i] = 1; } } // Count The Length Of SubString Having Maximum Length When A Character Is Swapped for(int i=1 ; i<s.length()-1 ; i++){ if(s.charAt(i-1) == s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)){ if(count[s.charAt(i-1) -'a'] == left[i-1] + right[i+1]){ max = Math.max(max , left[i-1] + right[i+1]); }else{ max = Math.max(max,left[i-1] + right[i+1]+1); } }else{ if(count[s.charAt(i) -'a'] == left[i]){ max = Math.max(max,left[i]); } else{ max = Math.max(max,left[i]+1); } } } if(count[s.charAt(s.length()-1)-'a']!=left[s.length()-1]) { max = Math.max(max, left[s.length()-1]+1); } return max; } }
class Solution { public: int maxRepOpt1(string text) { vector<pair<int, int>> intervals[26]; // a: [st, ed], ..... for(int i = 0; i < text.size();){ int st = i, ed = i; while(i < text.size() && text[i] == text[st]){ ed = i; i++; } intervals[text[st] - 'a'].push_back({st, ed}); } int ans = 0; for(int i = 0; i < 26; i++){ for(int j = 0; j < intervals[i].size(); j++){ // 单个的最大值 int len1 = intervals[i][j].second - intervals[i][j].first + 1; if(intervals[i].size() > 1) len1++; ans = max(ans, len1); // 合并 // [1, 2] [4, 6] if(j+1 < intervals[i].size() && intervals[i][j].second + 2 == intervals[i][j+1].first){ int len2 = intervals[i][j].second - intervals[i][j].first + 1 + intervals[i][j+1].second - intervals[i][j+1].first + 1; if(intervals[i].size() > 2){ // 一定有一个愿意牺牲 len2++; } ans = max(ans, len2); } } } return ans; } }; /** abababababac */
/** * @param {string} text * @return {number} */ const getLast = (ar)=> ar[ar.length-1]; var maxRepOpt1 = function(text) { let freq = {}; // compute frequency map for(let i=0;i<text.length;i++){ let e=text[i]; !freq[e] && (freq[e]=0); freq[e]++; } let segments = []; segments.push({ v:text[0], c:1 }); let max = 1; for(let i=1;i<text.length;i++){ let e = text[i]; let last = getLast(segments); if(last.v == e){ last.c++; max = Math.max(max,last.c); }else{ segments.push({v:e,c:1}); } } for(let i=0,len=segments.length;i<len;i++){ let {v,c} = segments[i]; if(freq[v] > c){ // x x a , a x x , x a x max = Math.max(max,c+1); } if(i+2<len && v==segments[i+2].v){ // x a x a x a x a x x a x a let sum = c+segments[i+2].c; if(segments[i+1].c == 1){ if(freq[v] > sum){ max = Math.max(max,1+sum); }else{ max = Math.max(max,sum); } } } } return max; };
Swap For Longest Repeated Character Substring
You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 &lt;= i &lt; n and set the value of arr at index i to x. You may repeat this procedure as many times as needed. Return true if it is possible to construct the target array from arr, otherwise, return false. &nbsp; Example 1: Input: target = [9,3,5] Output: true Explanation: Start with arr = [1, 1, 1] [1, 1, 1], sum = 3 choose index 1 [1, 3, 1], sum = 5 choose index 2 [1, 3, 5], sum = 9 choose index 0 [9, 3, 5] Done Example 2: Input: target = [1,1,1,2] Output: false Explanation: Impossible to create target array from [1,1,1,1]. Example 3: Input: target = [8,5] Output: true &nbsp; Constraints: n == target.length 1 &lt;= n &lt;= 5 * 104 1 &lt;= target[i] &lt;= 109
class Solution: def isPossible(self, target: List[int]) -> bool: if len(target) == 1: return target == [1] res = sum(target) heap = [-elem for elem in target] heapify(heap) while heap[0]<-1: maximum = -heappop(heap) res -= maximum if res == 1: return True x = maximum % res if x == 0 or (x != 1 and x == maximum): return False res += x heappush(heap,-x) return True
class Solution { public boolean isPossible(int[] target) { if(target.length==1) return target[0]==1; PriorityQueue<Integer> que = new PriorityQueue<Integer>(Collections.reverseOrder()); int totsum = 0; for(int i=0;i<target.length;i++){ que.add(target[i]); totsum += target[i]; } while(que.peek()!=1){ int max = que.remove(); int rem = totsum-max; int maxprev = max % rem; totsum = rem+maxprev; if(rem==1) return true; if(maxprev == 0 || maxprev == max){ return false; } else { que.add(maxprev); } } return true; } }
class Solution { public: bool isPossible(vector<int>& target) { //Priority queue for storing all the nums in taget in decreasing order. priority_queue<int> pq; long long sum = 0; //for storing total sum for(auto num : target){ //adding the nums in pq and sum pq.push(num); sum+=num; } //iterating untill all elements in pq become 1 (in turn pq.top() will also become 1); while(pq.top() != 1){ sum -= pq.top(); //removing the greatest element as it was last upadted when converting [1,1,1...] array to target. So we are left with sum of other elements. //when there are elements greeter than 1 then sum of other elements can not be 0 or sum can not be greater than top element because sum + x(any number>0) is pq.top(). if(sum == 0 || sum >= pq.top()) return false; //if we delete all copies of sum from pq.top() we get an old element. int old = pq.top() % sum; //all old elements were > 0 so it can not be 0 unless sum is 1 (This is only possible if array has only 2 elements) if(sum != 1 && old == 0) return false; pq.pop(); //Deleting greatest element pq.push(old); //Adding old element to restore array. sum += old; //Updating sum } //if all elements are 1 then return true return true; } };
var isPossible = function(target) { let max=0 let index=-1 for(let i=target.length-1;i>=0;i--){ if(target[i]>max){ max=target[i] index=i } } if(max===1)return true // if max itself is 1 return true let total=0 for(let i=0;i<target.length;i++){ if(i!==index){ total+=target[i] } } // If total=1,it means only one element was remaining apart from max and its value is 1 return true // eg target=[10,1] we started with [1,1] so next steps would be [2,1]->[3,1]->...[10,1] we can make sure it leads to target if(total===1)return true; // max should be greater than remaining nums sum OR if total is 0 it would lead to infinite loop( num%0 === NaN) so return false if(max<=total||total===0)return false; max=max%total; if(max<1)return false; // it should not be less than 1 target[index]=max; return isPossible(target) };
Construct Target Array With Multiple Sums
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. &nbsp; Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. &nbsp; Constraints: 1 &lt;= n &lt;= 104
class Solution: def __init__(self): self.perSq = [] def numSquares(self, n): # finding perfect squares up to n i = 1 while i*i <= n: self.perSq.append(i*i) i += 1 return self.lengths(n) # algorithm to find sum from perfect squares def outcomes(self, n, current): rem = n nums = [] while sum(nums) != n: if current < len(self.perSq)*-1: current = self.perSq[0] val = self.perSq[current] if rem < val: current -= 1 continue else: nums.append(val) rem -= val if (rem > 0) and (rem % val == 0): nums.append(val) rem -= val return len(nums) # algorithm to find sum with least possible numbers def lengths(self, n): data = [] for i in range(-1, -1*(len(self.perSq)+1), -1): data.append(self.outcomes(n, i)) return min(data)
class Solution { public int numSquares(int n) { ArrayList<Integer> perfect_squares = new ArrayList<>(); int i=1; while(i*i <= n){ perfect_squares.add(i*i); i++; } Integer[][] dp = new Integer[n+1][perfect_squares.size()+1]; int answer = helper(n , perfect_squares , perfect_squares.size()-1,dp); return answer; } public int helper(int n , ArrayList<Integer> coins ,int i,Integer[][] dp){ if(n == 0){ return 0; } if(i<0){ return 999999; // I'm not taking INT_MAX here, since int variables will overflow with (1 + INT_MAX) // just take any number greater than constraint ( 10^4) } if(dp[n][i] != null){ return dp[n][i]; } int nottake = 0 + helper(n , coins, i-1,dp); int take = 9999999; if(coins.get(i) <= n){ take = 1 + helper(n-coins.get(i),coins,i,dp ); } dp[n][i] = Math.min(nottake,take); return dp[n][i]; } }
class Solution { public: int numSquares(int n) { vector<int> perfectSq; for(int i = 1; i*i <= n; ++i){ perfectSq.push_back(i*i); } int m = perfectSq.size(); vector<vector<int>> dp( m+1, vector<int>(n+1, 0)); dp[0][0] = 0; for( int i = 1; i <= n; ++i ) dp[0][i] = INT_MAX; for(int i = 1; i <= m; ++i){ for(int j = 1; j <= n; ++j){ if( j < perfectSq[i-1]){ dp[i][j] = dp[i-1][j]; } else{ dp[i][j] = min( dp[i-1][j], dp[i][ j - perfectSq[i-1] ] + 1); } } } return dp[m][n]; } };
var numSquares = function(n) { let dp = new Array(n+1).fill(Infinity); dp[0] = 0; for(let i=1; i <= n; i++){ for(let k=1; k*k <= i; k++){ dp[i] = Math.min(dp[i],dp[i - (k*k)] + 1); } } return dp[n]; };
Perfect Squares
Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed). &nbsp; Example 1: Input: nums = [3,1] Output: 2 Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3: - [3] - [3,1] Example 2: Input: nums = [2,2,2] Output: 7 Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets. Example 3: Input: nums = [3,2,1,5] Output: 6 Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7: - [3,5] - [3,1,5] - [3,2,5] - [3,2,1,5] - [2,5] - [2,1,5] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 16 1 &lt;= nums[i] &lt;= 105
class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: def dfs(i,val): if maxBit == val : return 1<<(len(nums)-i) if i == len(nums): return 0 return dfs(i+1,val|nums[i]) + dfs(i+1,val) maxBit = 0 for i in nums: maxBit |= i return dfs(0,0)
class Solution { public int countMaxOrSubsets(int[] nums) { subsets(nums, 0, 0); return count; } int count = 0; int maxOR = 0; private void subsets(int[] arr, int vidx, int OR){ if(vidx == arr.length){ if(OR == maxOR){ count ++; }else if(OR > maxOR){ count = 1; maxOR = OR; } return; } // include subsets(arr, vidx+1, OR | arr[vidx]); // exclude subsets(arr, vidx+1, OR); } }
class Solution { public: int countMaxOrSubsets(vector<int>& nums) { int i,j,max_possible_or=0,n=nums.size(),ans=0; //maximum possible or=or of all number in array for(i=0;i<n;i++) { max_possible_or=nums[i]|max_possible_or; } //checking all subset for(i=1;i<(1<<n);i++) { int p=0; for(j=0;j<n;j++) { if(i&(1<<j)) { p=p|nums[j]; } } //if xor of given subset is equal to maximum possible or if(p==max_possible_or) { ans++; } } return ans; } };
/** * @param {number[]} nums * @return {number} */ var countMaxOrSubsets = function(nums) { let n = nums.length; let len = Math.pow(2, n); let ans = 0; let hash = {}; for (let i = 0; i < len; i++) { let tmp = 0; for (let j = 0; j < n; j++) { if(i & (1 << j)) { tmp |= nums[j]; } } if (hash[tmp]) { hash[tmp] += 1; } else { hash[tmp] = 1; } ans = Math.max(ans, tmp); } return hash[ans]; };
Count Number of Maximum Bitwise-OR Subsets
Given an integer array nums, find three numbers whose product is maximum and return the maximum product. &nbsp; Example 1: Input: nums = [1,2,3] Output: 6 Example 2: Input: nums = [1,2,3,4] Output: 24 Example 3: Input: nums = [-1,-2,-3] Output: -6 &nbsp; Constraints: 3 &lt;= nums.length &lt;=&nbsp;104 -1000 &lt;= nums[i] &lt;= 1000
class Solution: def maximumProduct(self, nums: List[int]) -> int: # TC = O(NlogN) because sorting the array # SC = O(1); no extra space needed; sorting was done in place. # sorting the array in descending order nums.sort(reverse = True) # maximum product can only occur for: # 1. positive no * positive no * positive no # 2. negative no * negative no * positive no # one negative and two positives and all negatives wont give max product # case where all numbers in the array are negative # eg : [-4,-3,-2,-1] is covered in all positives return max(nums[0]*nums[1]*nums[2],nums[-1]*nums[-2]*nums[0])
class Solution { public int maximumProduct(int[] nums) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE; for (int n: nums) { if (n <= min1) { min2 = min1; min1 = n; } else if (n <= min2) { // n lies between min1 and min2 min2 = n; } if (n >= max1) { // n is greater than max1, max2 and max3 max3 = max2; max2 = max1; max1 = n; } else if (n >= max2) { // n lies betweeen max1 and max2 max3 = max2; max2 = n; } else if (n >= max3) { // n lies betwen max2 and max3 max3 = n; } } return Math.max(min1 * min2 * max1, max1 * max2 * max3); } }
class Solution { public: int maximumProduct(vector<int>& nums) { int min1 = INT_MAX , min2 = INT_MAX; // Both have the maximum value that is +infinte int max1 = INT_MIN, max2 = INT_MIN , max3 = INT_MIN; //All these have the minimum value that is -infinte //now finding all these value above declared. for(int i = 0 ; i < nums.size() ; i++) { if(nums[i] > max1 ) { max3 = max2 ; max2 = max1; max1 = nums[i]; } else if(nums[i] > max2) { max3 = max2 ; max2 = nums[i] ; } else if(nums[i] > max3) { max3 = nums[i] ; } if(nums[i] < min1) { min2 = min1 ; min1 = nums[i] ; } else if(nums[i] < min2) { min2 = nums[i]; } } return max(min1*min2*max1 , max1*max2*max3); } };
var maximumProduct = function(nums) { nums.sort((a, b) => a-b) var lastNumber = nums.length - 1 var midNumber = nums.length - 2 var firstNumber = nums.length - 3 var total = nums[lastNumber] * nums[midNumber] * nums[firstNumber] return total };
Maximum Product of Three Numbers
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. &nbsp; Example 1: Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7]. &nbsp; Constraints: 0 &lt;= val &lt;= 109 At most 2 * 104 calls will be made to push and pop. It is guaranteed that there will be at least one element in the stack before calling pop.
class FreqStack: def __init__(self): self.cnt = {} self.maxcount = 0 self.stack = {} def push(self, val: int) -> None: count = self.cnt.get(val,0)+1 self.cnt[val] = count if count>self.maxcount: self.maxcount = count self.stack[count] = [] self.stack[count].append(val) def pop(self) -> int: res = self.stack[self.maxcount].pop() self.cnt[res]-=1 if not self.stack[self.maxcount]: self.maxcount-=1 return res # Your FreqStack object will be instantiated and called as such: # obj = FreqStack() # obj.push(val) # param_2 = obj.pop()
class Node{ int data, freq, time; Node(int data, int freq, int time){ this.data=data; this.freq=freq; this.time=time; } } class CompareNode implements Comparator<Node>{ @Override public int compare(Node a, Node b){ if(a.freq-b.freq==0){ return b.time-a.time; } return b.freq-a.freq; } } class FreqStack { PriorityQueue<Node> pq; Map<Integer,Node> map; int c=0; public FreqStack(){ pq=new PriorityQueue<>(new CompareNode()); map=new HashMap<>(); } public void push(int val){ c++; int freq=1; if(map.containsKey(val)){ freq+=map.get(val).freq; } map.put(val, new Node(val, freq, c)); pq.add(new Node(val,freq,c++)); } public int pop() { Node r=pq.remove(); Node a=map.get(r.data); a.freq--; return r.data; } }
class FreqStack { public: unordered_map<int,int> ump; unordered_map<int,stack<int>> ump_st; int cap=1; FreqStack() { ump.clear(); ump_st.clear(); } void push(int val) { //increasing the count if(ump.find(val)!=ump.end()) { ump[val]++; } else { ump[val]=1; } //update the highest level if(cap<ump[val]) { cap = ump[val]; } //push the elements in the stack where it belongs as per height ump_st[ump[val]].push(val); } int pop() { int val = ump_st[cap].top(); ump_st[cap].pop(); if(ump_st[cap].size()==0) { cap--; } ump[val]--; if(ump[val]==0) { ump.erase(val); } return val; } };
var FreqStack = function() { //hashMap to keep track of the values being repeated this.frequencyMap = {}; //List map to keep track of the sequence of the value being entered this.listMap = {}; //Max Frequency variable to keep track of the max frequency this.maxValueFrequency = 0; }; /** * @param {number} val * @return {void} */ FreqStack.prototype.push = function(val) { //if the hashMap doesn't have value being pushed then make a entry to it with 1 else increament by 1 this.frequencyMap[val] = this.frequencyMap[val] ? this.frequencyMap[val]+1 : 1; //get the frequency of the value being pushed const currentValueFrequency = this.frequencyMap[val]; //check if the current frequency is max or itself this.maxValueFrequency = Math.max(this.maxValueFrequency, currentValueFrequency); //if current value frequency is not in the listmap then make a new entry else push it if(!this.listMap[currentValueFrequency]) this.listMap[currentValueFrequency] =[val]; else this.listMap[currentValueFrequency].push(val); }; /** * @return {number} */ FreqStack.prototype.pop = function() { //make a temporary list of the max value frequency const tempList = this.listMap[this.maxValueFrequency]; //get the last element from the temporary list const top = tempList[tempList.length - 1]; //remove the item from the list tempList.pop(); //update the list this.listMap[this.maxValueFrequency] = tempList; //if the popped item exist in the frequecy map then decrease it by 1 if(this.frequencyMap[top]) this.frequencyMap[top]--; //if the max value frequency in the listmap is blank then reduce the maxValueFrequency; if(this.listMap[this.maxValueFrequency].length === 0) this.maxValueFrequency--; //return the max value frequency with proper order if it is same return top; }; //Time O(Log n) // for both Push and Pop //Space O(n) for storing all the values in the hashMap and listMap
Maximum Frequency Stack
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. &nbsp; Example 1: Input: start = 10, goal = 7 Output: 3 Explanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps: - Flip the first bit from the right: 1010 -&gt; 1011. - Flip the third bit from the right: 1011 -&gt; 1111. - Flip the fourth bit from the right: 1111 -&gt; 0111. It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3. Example 2: Input: start = 3, goal = 4 Output: 3 Explanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps: - Flip the first bit from the right: 011 -&gt; 010. - Flip the second bit from the right: 010 -&gt; 000. - Flip the third bit from the right: 000 -&gt; 100. It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3. &nbsp; Constraints: 0 &lt;= start, goal &lt;= 109
class Solution: def minBitFlips(self, s: int, g: int) -> int: count = 0 while s or g: if s%2 != g%2: count+=1 s, g = s//2, g//2 return count
class Solution { public static int minBitFlips(int a1, int a2) { int n = (a1 ^ a2); int res = 0; while (n != 0) { res++; n &= (n - 1); } return res; } }
class Solution { public: int minBitFlips(int start, int goal) { return __builtin_popcount(start^goal); } };
var minBitFlips = function(start, goal) { return (start^goal).toString(2).split("0").join("").length; };
Minimum Bit Flips to Convert Number
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course. You must find the minimum number of months needed to complete all the courses following these rules: You may start taking a course at any time if the prerequisites are met. Any number of courses can be taken at the same time. Return the minimum number of months needed to complete all the courses. Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph). &nbsp; Example 1: Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5] Output: 8 Explanation: The figure above represents the given graph and the time required to complete each course. We start course 1 and course 2 simultaneously at month 0. Course 1 takes 3 months and course 2 takes 2 months to complete respectively. Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months. Example 2: Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5] Output: 12 Explanation: The figure above represents the given graph and the time required to complete each course. You can start courses 1, 2, and 3 at month 0. You can complete them after 1, 2, and 3 months respectively. Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months. Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months. Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. &nbsp; Constraints: 1 &lt;= n &lt;= 5 * 104 0 &lt;= relations.length &lt;= min(n * (n - 1) / 2, 5 * 104) relations[j].length == 2 1 &lt;= prevCoursej, nextCoursej &lt;= n prevCoursej != nextCoursej All the pairs [prevCoursej, nextCoursej] are unique. time.length == n 1 &lt;= time[i] &lt;= 104 The given graph is a directed acyclic graph.
class Solution: def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: in_degree=defaultdict(int) graph=defaultdict(list) latest=[0]*(n+1) for u,v in relations: graph[u].append(v) in_degree[v]+=1 q=[] for i in range(1,n+1): if in_degree[i]==0: latest[i]=time[i-1] q.append(i) while q: node=q.pop() t0=latest[node] for nei in graph[node]: t=time[nei-1] latest[nei]=max(latest[nei],t0+t) in_degree[nei]-=1 if in_degree[nei]==0: q.append(nei) return max(latest)
class Solution { public int minimumTime(int n, int[][] relations, int[] time) { List<Integer> adj[] = new ArrayList[n]; int indegree[] = new int[n]; int completionTime[] = new int[n]; for(int i=0; i<n; i++) adj[i] = new ArrayList<>(); for(int relation[]: relations){ int u = relation[0]-1, v = relation[1]-1; adj[u].add(v); indegree[v]++; } Queue<Integer> q = new LinkedList<>(); for(int i=0; i<n; i++){ if(indegree[i] == 0){ // if no prerequisite add it to queue completionTime[i] = time[i]; q.add(i); } } while(!q.isEmpty()){ int u = q.poll(); for(int v: adj[u]){ completionTime[v] = Math.max(completionTime[v], completionTime[u] + time[v]); if(--indegree[v] == 0){ // when all prerequisite are complete add the next course q.add(v); } } } int res=0; for(int x: completionTime) res = Math.max(res, x); return res; } }
class Solution { public: int minimumTime(int n, vector<vector<int>>& relations, vector<int>& time) { vector<vector<int>> adjList(n); vector<int> inDegree(n),cTime(n,0); for(auto &r:relations) { // Create adjacency list and in degree count vectors. adjList[r[0]-1].push_back(r[1]-1); inDegree[r[1]-1]++; } queue<pair<int,int>> q; for(int i=0;i<n;i++) // Get all nodes with in-degree=0 and store add them to the queue. if(!inDegree[i]) q.push({i,0}); while(!q.empty()) { auto [node,t]=q.front(); // Process node `node`. q.pop(); // Completion time of the current node the time when the processing started `t` // (Max time at which prerequisutes completed) + the time taken to process it `time[node]`. int completionTime=t+time[node]; cTime[node]=completionTime; // Store the final completion time of the node `node`. for(int &n:adjList[node]) { // Update the intermediate completion time of the child node `n`. // This means that node `n` would start processing at least at `cTime[n]`. cTime[n]=max(cTime[n],completionTime); if(!--inDegree[n]) // Add the node with in-degree=0 to the queue. q.push({n,cTime[n]}); } } // Return the maximum time it took for a node/course to complete as our result. return *max_element(cTime.begin(),cTime.end()); } };
/** * @param {number} n * @param {number[][]} relations * @param {number[]} time * @return {number} */ var minimumTime = function(n, relations, time) { /* Approach: We can create reverse edges for relation. &nbsp; &nbsp; Then longest path(by weightage of time for each node) from the node will be the minimum time to finish that course(node) &nbsp; &nbsp; Now we can use simple DFS to find the longest path for each node. &nbsp; &nbsp; The node containing the longest path will be course to finish the last.We can also use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again.&nbsp; */ let edges={}; for(let i=0;i<relations.length;i++){ if(edges[relations[i][1]]===undefined){ edges[relations[i][1]] = []; } edges[relations[i][1]].push(relations[i][0]); } let max=0,timeRequired,memo={}; for(let i=1;i<=n;i++){ timeRequired = longestPath(i); max = Math.max(max,timeRequired); } return max; function longestPath(node){ if(memo[node]!==undefined){ return memo[node]; } let len,max=0; if(edges[node]!==undefined){ for(let i=0;i<edges[node].length;i++){ len = longestPath(edges[node][i]); max = Math.max(max,len); } } memo[node] = time[node-1]+max;//use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again return memo[node]; } };
Parallel Courses III
Given an array of integers arr. We want to select three indices i, j and k where (0 &lt;= i &lt; j &lt;= k &lt; arr.length). Let's define a and b as follows: a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k] Note that ^ denotes the bitwise-xor operation. Return the number of triplets (i, j and k) Where a == b. &nbsp; Example 1: Input: arr = [2,3,1,6,7] Output: 4 Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4) Example 2: Input: arr = [1,1,1,1,1] Output: 10 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 300 1 &lt;= arr[i] &lt;= 108
class Solution: def countTriplets(self, arr: List[int]) -> int: s = [0] n = len(arr) if n <= 1: return 0 for i in range(n): s.append(s[-1]^arr[i]) # a = s[i] ^ s[j], b = s[j] ^ s[k+1] count = defaultdict(int) # a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0 # <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1]) # <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1] res = 0 # len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k for i in range(n-1): for k in range(i+1, n): if s[i] == s[k+1]: res += (k-i) return res
class Solution { public int countTriplets(int[] arr) { int count=0; for(int i=0;i<arr.length;i++){ int val=0; val=val^arr[i]; for(int k=i+1;k<arr.length;k++){ val=val ^ arr[k]; if(val==0) count+=k-i; } } return count; } }
class TrieNode { public: int numOfIndex; int sumOfIndex; TrieNode* child[2]; TrieNode() : numOfIndex(0), sumOfIndex(0) { child[0] = NULL; child[1] = NULL; } }; class Solution { public: void addNumber(TrieNode* root, int num, int idx){ for( int i = 31; i >= 0; i--){ int bit = 1 & (num >> i) ; if ( root->child[bit] == NULL){ root->child[bit] = new TrieNode(); } root = root->child[bit]; } root->sumOfIndex += idx; root->numOfIndex++; } int calculateIndexPair(TrieNode* root, int num, int idx){ for( int i = 31; i >= 0; i--){ int bit = 1 & (num >> i); if (root->child[bit] == NULL){ return 0; } root = root->child[bit]; } return (((root->numOfIndex) * idx) - (root->sumOfIndex)); } int countTriplets(vector<int>& arr) { long long ans=0; int XOR = 0; TrieNode* root = new TrieNode(); for ( int i = 0 ; i < arr.size(); i++){ addNumber(root, XOR, i); XOR ^= arr[i]; ans = (ans + calculateIndexPair(root, XOR, i)) % 1000000007; } return ans; } };
/** * @param {number[]} arr * @return {number} */ var countTriplets = function(arr) { let count = 0 for(let i=0;i<arr.length;i++){ let xor = arr[i] for(let j=i+1;j<arr.length;j++){ xor ^= arr[j] if(xor == 0){ count += (j-i) } } } return count };
Count Triplets That Can Form Two Arrays of Equal XOR
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following: An integer x - Record a new score of x. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score. Return the sum of all the scores on the record. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: ops = ["5","2","C","D","+"] Output: 30 Explanation: "5" - Add 5 to the record, record is now [5]. "2" - Add 2 to the record, record is now [5, 2]. "C" - Invalidate and remove the previous score, record is now [5]. "D" - Add 2 * 5 = 10 to the record, record is now [5, 10]. "+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15]. The total sum is 5 + 10 + 15 = 30. Example 2: Input: ops = ["5","-2","4","C","D","9","+","+"] Output: 27 Explanation: "5" - Add 5 to the record, record is now [5]. "-2" - Add -2 to the record, record is now [5, -2]. "4" - Add 4 to the record, record is now [5, -2, 4]. "C" - Invalidate and remove the previous score, record is now [5, -2]. "D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4]. "9" - Add 9 to the record, record is now [5, -2, -4, 9]. "+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5]. "+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14]. The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. Example 3: Input: ops = ["1","C"] Output: 0 Explanation: "1" - Add 1 to the record, record is now [1]. "C" - Invalidate and remove the previous score, record is now []. Since the record is empty, the total sum is 0. &nbsp; Constraints: 1 &lt;= ops.length &lt;= 1000 ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104]. For operation "+", there will always be at least two previous scores on the record. For operations "C" and "D", there will always be at least one previous score on the record.
class Solution: def calPoints(self, ops: List[str]) -> int: temp = [] for i in ops: if i!="C" and i!="D" and i!="+": temp.append(int(i)) elif i=="C": temp.remove(temp[len(temp)-1]) elif i=="D": temp.append(2*temp[len(temp)-1]) elif i=="+": temp.append(temp[len(temp)-1]+temp[len(temp)-2]) return sum(temp)
class Solution { public int calPoints(String[] ops) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < ops.length; i++){ switch(ops[i]){ case "C": list.remove(list.size() - 1); break; case "D": list.add(list.get(list.size() - 1) * 2); break; case "+": list.add(list.get(list.size() - 1) + list.get(list.size() - 2)); break; default: list.add(Integer.valueOf(ops[i])); break; } } int finalScore = 0; for(Integer score: list) finalScore += score; return finalScore; } }
class Solution { public: int calPoints(vector<string>& ops) { stack<int>st; int n = ops.size(); for(int i=0;i<n;i++){ if(ops[i] == "C"){ st.pop(); } else if (ops[i] =="D"){ st.push(st.top() * 2); } else if(ops[i] =="+"){ int temp = st.top(); st.pop(); int temp2 = st.top(); st.push(temp); st.push(temp+temp2); } else{ st.push(stoi(ops[i])); } } int res = 0; while(!st.empty()){ res += st.top(); st.pop(); } return res; } };
//Plus sign in the below algo confirms that the data type we are getting is integer. So, instead of adding it as a string, the data type will be added as integer var calPoints = function(ops) { let stack = []; for(let i = 0; i < ops.length; i++){ if(ops[i] === "C") stack.pop(); else if(ops[i] === "D") stack.push((+stack[stack.length - 1]) * 2); //we have to take stack.length to get the element of stack. We cannot take i for getting the element of stack as i refers to ops and it wont give the index of previous element in stack else if(ops[i] ==="+") stack.push((+stack[stack.length - 1]) + (+stack[stack.length - 2])); else stack.push(+ops[i]); } let sum = 0; for(let i = 0; i < stack.length; i++){ sum = sum + stack[i]; } return sum; };
Baseball Game
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. &nbsp; Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330" &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 0 &lt;= nums[i] &lt;= 109
from functools import cmp_to_key class Solution: def largestNumber(self, nums: List[int]) -> str: nums = list(map(str, nums)) nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0)))) res = "".join(nums) return res if int(res) else "0"
class Solution { public String largestNumber(int[] nums) { String[] arr=new String[nums.length]; for(int i=0;i<nums.length;i++){ arr[i]=Integer.toString(nums[i]); } Arrays.sort(arr,(a,b)->(b+a).compareTo(a+b)); if(arr[0].equals("0")) return "0"; StringBuilder builder=new StringBuilder(); for(String item:arr){ builder.append(item); } return builder.toString(); } }
class Solution { public: string largestNumber(vector<int>& nums) { sort(nums.begin(),nums.end(),[&](int a,int b){ string order1 = to_string(a)+to_string(b); string order2 = to_string(b)+to_string(a); return order1>order2; }); string ans = ""; for(int i = 0;i<nums.size();i++){ if(nums[0]==0) return "0"; ans += to_string(nums[i]); } return ans; } };
var largestNumber = function(nums) { var arr=[] nums.forEach((item)=>{ arr.push(item.toString()); }) arr.sort((a,b)=>(b+a).localeCompare(a+b)); var ret="" if(arr[0]=="0") return "0"; arr.forEach((item)=>{ ret+=item; }) return ret; };
Largest Number
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. &nbsp; Example 1: Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] Output: ["cats and dog","cat sand dog"] Example 2: Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: [] &nbsp; Constraints: 1 &lt;= s.length &lt;= 20 1 &lt;= wordDict.length &lt;= 1000 1 &lt;= wordDict[i].length &lt;= 10 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique.
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ dic = defaultdict(list) for w in wordDict: dic[w[0]].append(w) result = [] def recursion(idx , ans): if idx >= len(s): result.append(" ".join(ans)) return for w in dic[s[idx]]: if s[idx : idx+len(w)] == w: ans.append(w) recursion(idx+len(w), ans) ans.pop() return recursion(0, []) return result
class Solution { List<String> res = new ArrayList<>(); String s; int index = 0; Set<String> set = new HashSet<>(); public List<String> wordBreak(String s, List<String> wordDict) { this.s = s; for (String word: wordDict) set.add(word); backtrack(""); return res; } public void backtrack(String sentence) { if (index == s.length()) { res.add(sentence.trim()); return; } int indexCopy = index; for (int i = index + 1; i <= s.length(); i++) { String str = s.substring(index, i); if (set.contains(str)) { index = i; backtrack(sentence + " " + str); index = indexCopy; } } return; } }
class Solution { public: void helper(string s, unordered_set<string>& dict,int start, int index,string current,vector<string>& ans){ if(start==s.size()){ ans.push_back(current); return; } if(index==s.size()) return; string sub=s.substr(start,index-start+1); if(dict.count(sub)>0){ string recursion; if(current.size()==0) recursion=sub; else recursion=current+" "+sub; helper(s,dict,index+1,index+1,recursion,ans); } helper(s,dict,start,index+1,current,ans); return; } vector<string> wordBreak(string s, vector<string>& wordDict) { unordered_set<string> dict; for(int i=0;i<wordDict.size();i++){ dict.insert(wordDict[i]); } vector<string> ans; helper(s,dict,0,0,"",ans); return ans; } };
var wordBreak = function(s, wordDict) { const n = s.length; const result = []; const findValidSentences = (currentString = '', remainingString = s, currentIndex = 0) => { if(currentIndex === remainingString.length) { if(wordDict.includes(remainingString)) { result.push(`${currentString} ${remainingString}`.trim()) } return result; } const newWord = remainingString.slice(0, currentIndex); if(wordDict.includes(newWord)) { const newCurrentString = `${currentString} ${newWord}`; const newRemainingString = remainingString.slice(currentIndex); findValidSentences(newCurrentString, newRemainingString, 0); } return findValidSentences(currentString, remainingString, currentIndex + 1); } return findValidSentences(); };
Word Break II
You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 &lt;= i &lt; n - 1. Return the number of valid splits in nums. &nbsp; Example 1: Input: nums = [10,4,-8,7] Output: 2 Explanation: There are three ways of splitting nums into two non-empty parts: - Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 &gt;= 3, i = 0 is a valid split. - Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 &gt;= -1, i = 1 is a valid split. - Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 &lt; 7, i = 2 is not a valid split. Thus, the number of valid splits in nums is 2. Example 2: Input: nums = [2,3,1,0] Output: 2 Explanation: There are two valid splits in nums: - Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 &gt;= 1, i = 1 is a valid split. - Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 &gt;= 0, i = 2 is a valid split. &nbsp; Constraints: 2 &lt;= nums.length &lt;= 105 -105 &lt;= nums[i] &lt;= 105
class Solution: def waysToSplitArray(self, nums: List[int]) -> int: prefix_sum = [nums[0]] n = len(nums) for i in range(1, n): prefix_sum.append(nums[i] + prefix_sum[-1]) count = 0 for i in range(n-1): if prefix_sum[i] >= prefix_sum[n-1] - prefix_sum[i]: count += 1 return count
class Solution { public int waysToSplitArray(int[] nums) { long sum = 0; for(int i : nums){ sum+=i; } int sol = 0; long localSum = 0; for(int i=0; i<nums.length-1;i++){ localSum += nums[i]; if(localSum >= sum-localSum){ sol++; } } return sol; } }
class Solution { public: int waysToSplitArray(vector<int>& nums) { long long sumFromBack(0), sumFromFront(0); for (auto& i : nums) sumFromBack += i; int n(size(nums)), res(0); for (auto i=0; i<n-1; i++) { sumFromFront += nums[i]; // sum of the first i + 1 elements sumFromBack -= nums[i]; // sum of the last n - i - 1 elements. if (sumFromFront >= sumFromBack) res++; } return res; } };
/** * @param {number[]} nums * @return {number} */ var waysToSplitArray = function(nums) { let result = 0; let letsum = 0; let rightsum = nums.reduce((a,b)=> a+b); let end = nums.length-1; for (let i = 0;i<end;i++) { letsum+=nums[i]; rightsum-=nums[i]; if (letsum>=rightsum) { result++; } } return result; };
Number of Ways to Split Array
You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti &lt;= x &lt;= endi. &nbsp; Example 1: Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5 Output: true Explanation: Every integer between 2 and 5 is covered: - 2 is covered by the first range. - 3 and 4 are covered by the second range. - 5 is covered by the third range. Example 2: Input: ranges = [[1,10],[10,20]], left = 21, right = 21 Output: false Explanation: 21 is not covered by any range. &nbsp; Constraints: 1 &lt;= ranges.length &lt;= 50 1 &lt;= starti &lt;= endi &lt;= 50 1 &lt;= left &lt;= right &lt;= 50
class Solution: def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: t=[0]*(60) for i in ranges: t[i[0]]+=1 t[i[1]+1]-=1 for i in range(1,len(t)): t[i] += t[i-1] return min(t[left:right+1])>=1
class Solution { public boolean isCovered(int[][] ranges, int left, int right) { boolean flag = false; for (int i=left; i<=right; i++) { for (int[] arr: ranges) { if (i >= arr[0] && i <= arr[1]) { flag = true; break; } } if (!flag) return false; flag = false; } return true; } }
class Solution { public: bool isCovered(vector<vector<int>>& ranges, int left, int right) { int n = ranges.size(); sort(ranges.begin(), ranges.end()); if(left < ranges[0][0]) //BASE CASE return false; bool ans = false; for(int i = 0; i < n; i++){ if(left>=ranges[i][0] && left<=ranges[i][1]){ left = ranges[i][1]+1; } if(left > right){ ans = true; break; } } return ans; } };
var isCovered = function(ranges, left, right) { var map=new Map() for(let i=left;i<=right;i++){ map.set(i,0) } for(let range of ranges){ for(let i=range[0];i<=range[1];i++){ map.set(i,1) } } // console.log(map) for(let key of map.keys()){ if(map.get(key)===0) return false } return true };
Check if All the Integers in a Range Are Covered
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). &nbsp; Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 &nbsp; Constraints: -231 &lt;= x &lt;= 231 - 1
import bisect class Solution: def reverse(self, x: int) -> int: flag = 0 if x<0: x = abs(x) flag = 1 l = [i for i in str(x)] l.reverse() ret = ''.join(l) ret = int(ret) if flag == 1: ret = ret*-1 if ((ret >= (-(2**31))) and (ret<=((2**31)-1))): return ret else: return 0
class Solution { public int reverse(int x) { long reverse = 0; while (x != 0) { int digit = x % 10; reverse = reverse * 10 + digit; x = x / 10; } if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0; return (int) reverse; } }
class Solution { public: int reverse(int x) { long res = 0; while (abs(x) > 0) { res = (res + x % 10) * 10; x /= 10; } x < 0 ? res = res / 10 * -1 : res = res / 10; if (res < INT32_MIN || res > INT32_MAX) { res = 0; } return res; } };
var reverse = function(x) { let val = Math.abs(x) let res = 0 while(val !=0){ res = (res*10) + val %10 val = Math.floor(val/10) } if(x < 0)res = 0 - res return (res > ((2**31)-1) || res < (-2)**31) ? 0 : res };
Reverse Integer
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts. &nbsp; Example 1: Input: n = 7, cuts = [1,3,4,5] Output: 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). Example 2: Input: n = 9, cuts = [5,6,1,4,2] Output: 22 Explanation: If you try the given cuts ordering the cost will be 25. There are much ordering with total cost &lt;= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible. &nbsp; Constraints: 2 &lt;= n &lt;= 106 1 &lt;= cuts.length &lt;= min(n - 1, 100) 1 &lt;= cuts[i] &lt;= n - 1 All the integers in cuts array are distinct.
class Solution: def minCost(self, n: int, cuts: List[int]) -> int: cuts = [0] + sorted(cuts) + [n] k = len(cuts) dp = [[float('inf')] * k for _ in range(k)] for l in range(1, k + 1): for beg in range(k - l): end = beg + l if l == 1: dp[beg][end] = 0 continue for i in range(beg + 1, end): currcost = cuts[end] - cuts[beg] currcost += dp[beg][i] + dp[i][end] dp[beg][end] = min(dp[beg][end], currcost) return dp[0][k - 1]
class Solution { public int minCost(int n, int[] cuts) { int len = cuts.length; Arrays.sort(cuts); int[] arr = new int[len+2]; for(int i = 1 ; i <= len ; i++) arr[i] = cuts[i-1]; arr[0] = 0; arr[len+1] = n; int[][] dp = new int[len+1][len+1]; for(int i = 0 ; i <= len ; i++) for(int j = 0 ; j <= len ; j++) dp[i][j] = -1; return cut(arr , 1 , len , dp); } int cut(int[] cuts , int i , int j , int[][] dp){ if(i > j) return 0; if(dp[i][j] != -1) return dp[i][j]; int mini = Integer.MAX_VALUE; for(int k = i ; k <= j ; k++){ int cost = cuts[j+1]-cuts[i-1] + cut(cuts , i , k-1 , dp) + cut(cuts , k+1 , j , dp); mini = Math.min(cost , mini); } return dp[i][j] = mini; } }
class Solution { public: long cutMin(int i, int j, vector<int>&c, vector<vector<int>>&dp) { if(i>j) return 0; if(dp[i][j]!=-1) return dp[i][j]; long mini = INT_MAX; for(int ind=i;ind<=j;ind++) { long cost = c[j+1]-c[i-1]+cutMin(i,ind-1,c,dp)+cutMin(ind+1,j,c,dp); mini = min(mini,cost); } return dp[i][j] = mini; } int minCost(int n, vector<int>& cuts) { int c = cuts.size(); cuts.push_back(0); cuts.push_back(n); sort(cuts.begin(),cuts.end()); vector<vector<int>>dp(c+1,vector<int>(c+1,-1)); return cutMin(1,c,cuts,dp); } };
var minCost = function(n, cuts) { cuts = cuts.sort((a, b) => a - b); let map = new Map(); // Use cutIdx to track the idx of the cut position in the cuts array function dfs(start, end, cutIdx) { let key = `${start}-${end}`; if (map.has(key)) return map.get(key); let min = Infinity for (let i = cutIdx; i < cuts.length; i++) { let cut = cuts[i]; if (cut <= start) continue; if (cut < end) { let len = end - start; let left = dfs(start, cut, 0); let right = dfs(cut, end, i + 1); min = Math.min(min, len + left + right); } else break; } if (min === Infinity) { map.set(key, 0); return 0; } else { map.set(key, min); return min; } } return dfs(0, n, 0); };
Minimum Cost to Cut a Stick
Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. &nbsp; Example 1: Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. Example 2: Input: root = [1,2] Output: 1 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. -100 &lt;= Node.val &lt;= 100
class Solution: """ Top Down recursion approach: it is sub optimal """ def __init__(self): self.max_diameter = 0 def diameter(self, root): if root is None: return 0 return self.max_depth(root.left) + self.max_depth(root.right) def max_depth(self, root): if root is None: return 0 return 1 + max(self.max_depth(root.left), self.max_depth(root.right)) def func(self, root): if root is not None: diameter = self.diameter(root) if self.max_diameter < diameter: self.max_diameter = diameter self.diameterOfBinaryTree(root.left) self.diameterOfBinaryTree(root.right) def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self.func(root) return self.max_diameter """ Better Approach: I can try to approach this problem using bottom up recursion """ def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self.diameter = 0 def fun(root): if root is None: return 0 left = fun(root.left) right = fun(root.right) if left + right > self.diameter: self.diameter = left + right return max(left, right) + 1 fun(root) return self.diameter
class Solution { // Declare Global Variable ans to 0 int ans = 0; // Depth First Search Function public int dfs(TreeNode root) { if(root == null) return 0; // recursive call for left height int lh = dfs(root.left); // recursive call for right height int rh = dfs(root.right); // update ans ans = Math.max(ans, lh + rh); // return max value return Math.max(lh, rh) + 1; } // Diameter of Binary Tree Function public int diameterOfBinaryTree(TreeNode root) { // Call dfs Function dfs(root); return ans; } } // Output - /* Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. */ // Time & Space Complexity - /* Time - O(n) Space - O(n) */
class Solution { public: int diameterOfBinaryTree(TreeNode* root) { int diameter = 0; height(root, diameter); return diameter; } private: int height(TreeNode* node, int& diameter) { if (!node) { return 0; } int lh = height(node->left, diameter); int rh = height(node->right, diameter); diameter = max(diameter, lh + rh); return 1 + max(lh, rh); } };
function fastDiameter(node) { if(node == null) { let pair = new Array(2).fill(0) pair[0] = 0 pair[1] = 0 return pair } let leftPair = fastDiameter(node.left) let rightPair = fastDiameter(node.right) let leftDiameter = leftPair[0] let rightDiameter = rightPair[0] let height = leftPair[1] + rightPair[1] + 1 let maxDiameter = Math.max(leftDiameter,rightDiameter,height) let maxHeight = Math.max(leftPair[1],rightPair[1]) + 1 return [maxDiameter,maxHeight] } // diameter --> number of edges between two end nodes var diameterOfBinaryTree = function(root) { let pair = fastDiameter(root) return pair[0]-1 };
Diameter of Binary Tree
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. &nbsp; Example 1: Input: s = "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: s = "cccaaa" Output: "aaaccc" Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: s = "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. &nbsp; Constraints: 1 &lt;= s.length &lt;= 5 * 105 s consists of uppercase and lowercase English letters and digits.
class Solution: def frequencySort(self, s: str) -> str: di = Counter(s) #it wont strike immediately that this is a heap kind of question. heap = [] heapq.heapify(heap) for key,val in di.items(): heapq.heappush(heap,(-1*val,key)) # n = len(s) res = "" # print(heap) while(len(heap)): val,ch = heapq.heappop(heap) res+=(ch*(-1*val)) return res
class Solution { public String frequencySort(String s) { HashMap<Character,Integer> hm1=new HashMap<>(); TreeMap<Integer,ArrayList<Character>> hm2=new TreeMap<>(Collections.reverseOrder()); for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(hm1.containsKey(c)) { hm1.put(c,hm1.get(c) + 1); } else { hm1.put(c,1); } } for(char c : hm1.keySet()) { if(hm2.containsKey(hm1.get(c))) { ArrayList<Character> temp=hm2.get(hm1.get(c)); temp.add(c); hm2.put(hm1.get(c),temp); } else { ArrayList<Character> temp=new ArrayList<>(); temp.add(c); hm2.put(hm1.get(c),temp); } } StringBuilder sb=new StringBuilder(""); for(int x :hm2.keySet()) { ArrayList<Character> temp=hm2.get(x); for(char c: temp) { for(int i=0;i<x;i++){ sb.append(c); } } } return sb.toString(); } }
class Solution { public: string frequencySort(string s) { unordered_map<char,int>mp; for(int i=0;i<s.length();i++) //get the frequency of every char of the string { mp[s[i]]++; } priority_queue<pair<int,char>>pq; //store the freq and char pair in max heap for(auto it=mp.begin();it!=mp.end();it++) { pq.push({it->second,it->first}); } string str=""; int val; while(!pq.empty()) { val=pq.top().first; //append the char frequency times while(val--) { str.push_back(pq.top().second); } pq.pop(); } return str; } };
var frequencySort = function(s) { let obj = {} for(const i of s){ obj[i] = (obj[i] || 0) +1 } let sorted = Object.entries(obj).sort((a,b)=> b[1]-a[1]) return sorted.map((e)=> e[0].repeat(e[1])).join('') };
Sort Characters By Frequency
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character &nbsp; Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -&gt; rorse (replace 'h' with 'r') rorse -&gt; rose (remove 'r') rose -&gt; ros (remove 'e') Example 2: Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -&gt; inention (remove 't') inention -&gt; enention (replace 'i' with 'e') enention -&gt; exention (replace 'n' with 'x') exention -&gt; exection (replace 'n' with 'c') exection -&gt; execution (insert 'u') &nbsp; Constraints: 0 &lt;= word1.length, word2.length &lt;= 500 word1 and word2 consist of lowercase English letters.
from functools import cache class Solution: def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) @cache def dp(i, j): if i == 0: return j if j == 0: return i l1, l2 = word1[i - 1], word2[j - 1] if l1 != l2: return 1 + min( dp(i, j - 1), # Delete / insert j dp(i - 1, j), # Delete / insert i dp(i - 1, j - 1) # Replace i or j ) return dp(i - 1, j - 1) return dp(m, n)
class Solution { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int dp[][] = new int[m][n]; for(int i=0 ; i<m ; i++){ for(int j=0 ; j<n ; j++){ dp[i][j] = -1; } } return solve(word1, word2 , m-1, n-1 ,dp); } public int solve(String str1, String str2, int m , int n , int dp[][]){ if(m<0){ return n+1; } if(n<0){ return m+1; } if(dp[m][n] != -1){ return dp[m][n]; } if(str1.charAt(m) == str2.charAt(n)){ return solve(str1, str2 , m-1, n-1 ,dp); } else{ int min = Math.min(solve(str1, str2, m-1 ,n ,dp), solve(str1, str2, m ,n-1 , dp)); dp[m][n] = 1+Math.min(min, solve(str1, str2, m-1, n-1, dp)); } return dp[m][n]; } }
class Solution { public: int minDistance(string word1, string word2) { int m = word1.size(), n = word2.size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 1; i <= m; i++) { dp[i][0] = i; } for (int j = 1; j <= n; j++) { dp[0][j] = j; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1; } } } return dp[m][n]; } };
var minDistance = function(word1, word2) { const m = word1.length; const n = word2.length; const memo = new Array(m).fill().map(() => new Array(n)); const dfs = (i = m - 1, j = n - 1) => { if(i < 0 && j < 0) return 0; if(i < 0 && j >= 0) return j + 1; if(i >= 0 && j < 0) return i + 1; if(memo[i][j] !== undefined) return memo[i][j]; if(word1[i] === word2[j]) { return memo[i][j] = dfs(i - 1, j - 1); } return memo[i][j] = 1 + Math.min(...[ dfs(i, j - 1), dfs(i - 1, j), dfs(i - 1, j - 1) ]); } return dfs(); };
Edit Distance
Given a&nbsp;square&nbsp;matrix&nbsp;mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. &nbsp; Example 1: Input: mat = [[1,2,3], &nbsp; [4,5,6], &nbsp; [7,8,9]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2: Input: mat = [[1,1,1,1], &nbsp; [1,1,1,1], &nbsp; [1,1,1,1], &nbsp; [1,1,1,1]] Output: 8 Example 3: Input: mat = [[5]] Output: 5 &nbsp; Constraints: n == mat.length == mat[i].length 1 &lt;= n &lt;= 100 1 &lt;= mat[i][j] &lt;= 100
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: n = len(mat) mid = n // 2 summation = 0 for i in range(n): # primary diagonal summation += mat[i][i] # secondary diagonal summation += mat[n-1-i][i] if n % 2 == 1: # remove center element (repeated) on odd side-length case summation -= mat[mid][mid] return summation
class Solution { public int diagonalSum(int[][] mat) { int sum1 = 0; int sum2 = 0; int n = mat.length; for(int i = 0 ; i < n ; i++) { sum1 += mat[i][i]; sum2 += mat[i][n-i-1]; } int res = sum1 + sum2; if(n%2 != 0) { res -= mat[n/2][n/2]; } return res; } }
class Solution { public: int diagonalSum(vector<vector<int>>& mat) { int n = mat.size() ; int ans = 0 ; for(int i = 0 ; i < n ; i++){ ans = ans + mat[i][i] + mat[i][n - i - 1] ; } ans = (n & 1) ? ans - mat[n/2][n/2] : ans ;//if n is odd then we have to subtract mat[n/2][n/2] from the ans because we add it twice earlier. return ans ; } };
var diagonalSum = function(mat) { return mat.reduce((acc, matrix, i)=>{ const matrixlength = matrix.length-1; return acc += (i !== matrixlength-i) ? matrix[i]+ matrix[matrixlength-i] : matrix[i]; },0) }; /* */
Matrix Diagonal Sum
A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. &nbsp; Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 -231 &lt;= nums[i] &lt;= 231 - 1 nums[i] != nums[i + 1] for all valid i.
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ nums = [-2**32]+nums+[-2**32] l,r = 0,len(nums)-1 while l <=r: m = (l+r)//2 # we find the target: if nums[m] > nums[m-1] and nums[m] > nums[m+1]: return m -1 else: if nums[m] <nums[m+1]: l = m + 1 else: r = m - 1 return -1
class Solution { public int findPeakElement(int[] nums) { int start = 0; int end = nums.length - 1; while(start < end){ int mid = start + (end - start) / 2; if(nums[mid] > nums[mid + 1]){ //It means that we are in decreasing part of the array end = mid; } else{ //It means that we are in increasing part of the array start = mid + 1; } } return start; } }
class Solution { public: int findPeakElement(vector<int>& nums) { int peak = 0; for(int i=1; i<nums.size(); i++) { if(nums[i]>nums[i-1]) peak = i; } return peak; } };
/** * @param {number[]} nums * @return {number} */ var findPeakElement = function(nums) { if(nums.length === 1) return 0; const recursion = (startIndex, endIndex) => { const midIndex = Math.floor((startIndex + endIndex)/2); if (startIndex === endIndex) return startIndex; if (startIndex + 1 === endIndex) { return nums[endIndex] >= nums [startIndex] ? endIndex : startIndex; } if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return midIndex; if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] < nums[midIndex+1]) return recursion(midIndex + 1, endIndex); if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return recursion(startIndex, midIndex - 1); if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] < nums[midIndex+1]) return nums[midIndex-1] > nums[midIndex+1] ? recursion(startIndex, midIndex - 1) : recursion(midIndex + 1, endIndex); } return recursion(0, nums.length - 1); };
Find Peak Element
You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. &nbsp; Example 1: Input: s = "aacaba" Output: 2 Explanation: There are 5 ways to split "aacaba" and 2 of them are good. ("a", "acaba") Left string and right string contains 1 and 3 different letters respectively. ("aa", "caba") Left string and right string contains 1 and 3 different letters respectively. ("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split). ("aacab", "a") Left string and right string contains 3 and 1 different letters respectively. Example 2: Input: s = "abcd" Output: 1 Explanation: Split the string as follows ("ab", "cd"). &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s consists of only lowercase English letters.
class Solution: def numSplits(self, s: str) -> int: one = set() two = set() dic = {} for i in s: dic[i] = dic.get(i, 0) + 1 two.add(i) tot = 0 for i in s: one.add(i) dic[i] -= 1 if dic[i] == 0: two.remove(i) if len(one) == len(two): tot += 1 return tot
class Solution { public int numSplits(String s) { int a[] = new int[26]; int b[] = new int[26]; int ds1=0,ds2=0; int count=0; for(int i=0;i<s.length();i++) { b[s.charAt(i)-97]++; if(b[s.charAt(i)-97] == 1) ds2++; } for(int i=0;i<s.length();i++) { a[s.charAt(i)-97]++; b[s.charAt(i)-97]--; if(b[s.charAt(i)-97] == 0) ds2--; if(a[s.charAt(i)-97] == 1) ds1++; if(ds1 == ds2) count++; } return count; } }
class Solution { public: int numSplits(string s) { int n=s.size(); vector<int>left(26,0); vector<int>right(26,0); int left_count=0,right_count=0; int splits=0; for(auto &it:s){ right[it-'a']++; if(right[it-'a']==1)right_count++; } for(auto &it:s){ left[it-'a']++; right[it-'a']--; if(left[it-'a']==1)left_count++; if(right[it-'a']==0)right_count--; if(left_count==right_count) splits++; } return splits; } };
var numSplits = function(s) { let n = s.length; let preFix = new Array(n) , suFix = new Array(n); let preSet = new Set(); let suSet = new Set(); for(let i=0; i<n ; i++){ preSet.add(s[i]); suSet.add(s[n-1-i]); preFix[i]= preSet.size; suFix[n-1-i]= suSet.size; } let goodWays=0; for(let i=0; i<n-1; i++){ if(preFix[i]===suFix[i+1]) goodWays++; } return goodWays; };
Number of Good Ways to Split a String
Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 &lt;= i &lt; j &lt; nums.length and low &lt;= (nums[i] XOR nums[j]) &lt;= high. &nbsp; Example 1: Input: nums = [1,4,2,7], low = 2, high = 6 Output: 6 Explanation: All nice pairs (i, j) are as follows: - (0, 1): nums[0] XOR nums[1] = 5 - (0, 2): nums[0] XOR nums[2] = 3 - (0, 3): nums[0] XOR nums[3] = 6 - (1, 2): nums[1] XOR nums[2] = 6 - (1, 3): nums[1] XOR nums[3] = 3 - (2, 3): nums[2] XOR nums[3] = 5 Example 2: Input: nums = [9,8,4,2,1], low = 5, high = 14 Output: 8 Explanation: All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums[0] XOR nums[2] = 13 &nbsp; - (0, 3): nums[0] XOR nums[3] = 11 &nbsp; - (0, 4): nums[0] XOR nums[4] = 8 &nbsp; - (1, 2): nums[1] XOR nums[2] = 12 &nbsp; - (1, 3): nums[1] XOR nums[3] = 10 &nbsp; - (1, 4): nums[1] XOR nums[4] = 9 &nbsp; - (2, 3): nums[2] XOR nums[3] = 6 &nbsp; - (2, 4): nums[2] XOR nums[4] = 5 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 1 &lt;= nums[i] &lt;= 2 * 104 1 &lt;= low &lt;= high &lt;= 2 * 104
from collections import defaultdict class TrieNode: def __init__(self): self.nodes = defaultdict(TrieNode) self.cnt = 0 class Trie: def __init__(self): self.root = TrieNode() def insert(self, val): cur = self.root for i in reversed(range(15)): bit = val >> i & 1 cur.nodes[bit].cnt += 1 cur = cur.nodes[bit] def count(self, val, high): res = 0 cur = self.root for i in reversed(range(15)): if not cur: break bit = val >> i & 1 cmp = high >> i & 1 if cmp: res += cur.nodes[bit].cnt cur = cur.nodes[1^bit] else: cur = cur.nodes[bit] return res class Solution: def countPairs(self, nums: List[int], low: int, high: int) -> int: trie = Trie() res = 0 for num in nums: res += trie.count(num, high + 1) - trie.count(num, low) trie.insert(num) return res
class Solution { public int countPairs(int[] nums, int low, int high) { Trie trie=new Trie(); int cnt=0; for(int i=nums.length-1;i>=0;i--){ // count all the element whose xor is less the low int cnt1=trie.maxXor(nums[i],low); // count all the element whose xor is less the high+1 int cnt2=trie.maxXor(nums[i],high+1); trie.add(nums[i]); cnt+=cnt2-cnt1; } return cnt; } } class Trie{ private Node root; Trie(){ root=new Node(); } public void add(int x){ Node cur=root; for(int i=31;i>=0;i--){ int bit=(x>>i)&1; if(!cur.contains(bit)){ cur.put(bit); } cur.inc(bit); cur=cur.get(bit); } } public int maxXor(int x,int limit){ int low_cnt=0; Node cur=root; for(int i=31;i>=0 && cur!=null;i--){ int bit=(x>>i)&(1); int req=(limit>>i)&1; if(req==1){ if(cur.contains(bit)){ low_cnt+=cur.get(bit).cnt; } cur=cur.get(1-bit); }else{ cur=cur.get(bit); } } return low_cnt; } } class Node{ private Node links[]; int cnt; Node(){ links=new Node[2]; cnt=0; } public void put(int bit){ links[bit]=new Node(); } public Node get(int bit){ return links[bit]; } public boolean contains(int bit){ return links[bit]!=null; } public void inc(int bit){ links[bit].cnt++; } }
struct Node { Node* arr[2]; int count = 0; bool contains(int bitNo) { return arr[bitNo] != NULL; } void put(int bitNo, Node* newNode) { arr[bitNo] = newNode; } Node* getNext(int bitNo) { return arr[bitNo]; } int getCount(int bitNo) { return arr[bitNo]->count; } void setCount(int bitNo) { arr[bitNo]->count++; } }; class Solution { public: Node* root = new Node(); void insert(int num) { Node* temp = root; for(int bit=15; bit>=0; bit--) { int bitVal = (bool)(num & (1<<bit)); if(!temp->contains(bitVal)) { temp->put(bitVal, new Node()); } temp->setCount(bitVal); temp = temp->getNext(bitVal); } } int getPairs(int num, int k) { Node* temp = root; int cntPairs = 0; for(int bit=15; bit>=0 && temp; bit--) { int bit_num = (bool)(num & (1<<bit)); int bit_k = (bool)(k & (1<<bit)); if(bit_k) { if(temp->contains(bit_num)) { cntPairs += temp->getCount(bit_num); } if(temp->contains(1 - bit_num)) { temp = temp->getNext(1 - bit_num); } else break; } else if(temp->contains(bit_num)) { temp = temp->getNext(bit_num); } else { break; } } return cntPairs; } int countPairs(vector<int>& nums, int low, int high) { int n = nums.size(); int cnt = 0; for(int i=0; i<n; i++) { cnt += getPairs(nums[i], high+1) - getPairs(nums[i], low); insert(nums[i]); } return cnt; } };
var countPairs = function(nums, low, high) { function insert(num){ var node = root; for(i = 14; i>=0; i--) { var bit = (num >> i) & 1; if(!node.children[bit]) { node.children[bit] = new TrieNode(); } node.children[bit].cnt += 1; node = node.children[bit]; } } function countSmallerNums(num, limit) { var cnt = 0; // count pairs with num strictly smaller than limit var node = root; for(i = 14; i>=0 && node; i--) { var lbit = (limit>>i) & 1; var nbit = (num >> i) & 1; if(lbit===1) { // we can decrease on 1 bit if(node.children[nbit]) { cnt += node.children[nbit].cnt; } // go to another way to find next bit count node = node.children[1-nbit]; } else { // cannot increase the lbit === 0, // find the same Nbit to XOR to be '0' node = node.children[nbit]; } } return cnt; } // starts here var root = new TrieNode(); var res =0; for(var num of nums) { res += countSmallerNums(num, high+1) - countSmallerNums(num, low); insert(num); } return res; }; class TrieNode{ constructor() { this.cnt = 0; this.children = new Array(2).fill(null); } }
Count Pairs With XOR in a Range
A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val. Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine: If a is empty, return null. Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i]. The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]). The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]). Return root. Note that we were not given a directly, only a root node root = Construct(a). Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b). &nbsp; Example 1: Input: root = [4,1,3,null,null,2], val = 5 Output: [5,4,null,1,3,null,null,2] Explanation: a = [1,4,2,3], b = [1,4,2,3,5] Example 2: Input: root = [5,2,4,null,1], val = 3 Output: [5,2,4,null,1,null,3] Explanation: a = [2,1,5,4], b = [2,1,5,4,3] Example 3: Input: root = [5,2,3,null,1], val = 4 Output: [5,2,4,null,1,3] Explanation: a = [2,1,5,3], b = [2,1,5,3,4] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 100]. 1 &lt;= Node.val &lt;= 100 All the values of the tree are unique. 1 &lt;= val &lt;= 100
class Solution: """ approach: given a, we can get the inorder traversal of it, then append val to it and then construct the tree back """ def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: inorder_list = [] def inorder(root): if not root: return inorder(root.left) inorder_list.append(root.val) inorder(root.right) inorder(root) inorder_list.append(val) def get_maximum(val_list): max_index = -1 max_val = -1 for i, val in enumerate(val_list): if val > max_val: max_val = val max_index = i return max_index, max_val def create_tree(val_list): if not len(val_list): return None index, val = get_maximum(val_list) node = TreeNode(val) node.left = create_tree(val_list[:index]) node.right = create_tree(val_list[index+1:]) return node b = create_tree(inorder_list) return b
class Solution { public TreeNode insertIntoMaxTree(TreeNode root, int val) { if (root==null) return new TreeNode(val); if (val > root.val) { TreeNode newRoot = new TreeNode(val); newRoot.left = root; return newRoot; } root.right = insertIntoMaxTree(root.right, val); return root; } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void insertIntoMaxTreeRec(TreeNode* root,TreeNode* newNode)//o(logn) { if(!root) return; if(root->right&&root->right->val<newNode->val) { newNode->left=root->right; root->right=newNode; return; } if(!root->right) {root->right=newNode; return;} insertIntoMaxTreeRec( root->right, newNode); } TreeNode* insertIntoMaxTree(TreeNode* root, int val) { TreeNode* curr=new TreeNode(val); if(root->val<val) { curr->left=root; root=curr; }else { insertIntoMaxTreeRec( root, curr); } return root; } };
/** * @param {TreeNode} root * @param {number} val * @return {TreeNode} */ var insertIntoMaxTree = function(root, val) { // get new node var node = new TreeNode(val); // no root if(!root) { return node; } // upward derivation if val larger then root if(val > root.val) { return node.left = root, node; } // downward derivation root.right = insertIntoMaxTree(root.right, val); // root construct return root; };
Maximum Binary Tree II
Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i &gt; 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, the first four strings in the above sequence are: S1 = "0" S2 = "011" S3 = "0111001" S4 = "011100110110001" Return the kth bit in Sn. It is guaranteed that k is valid for the given n. &nbsp; Example 1: Input: n = 3, k = 1 Output: "0" Explanation: S3 is "0111001". The 1st bit is "0". Example 2: Input: n = 4, k = 11 Output: "1" Explanation: S4 is "011100110110001". The 11th bit is "1". &nbsp; Constraints: 1 &lt;= n &lt;= 20 1 &lt;= k &lt;= 2n - 1
class Solution: def findKthBit(self, n: int, k: int) -> str: i, s, hash_map = 1, '0', {'1': '0', '0': '1'} for i in range(1, n): s = s + '1' + ''.join((hash_map[i] for i in s))[::-1] return s[k-1]
class Solution { private String invert(String s){ char [] array=s.toCharArray(); for(int i=0;i<s.length();i++){ if(array[i]=='1'){ array[i]='0'; } else{ array[i]='1'; } } return new String(array); } private String reverse(String s){ StringBuilder str=new StringBuilder(s); return str.reverse().toString(); } private String func(int i){ if(i==0){ return "0"; } return func(i-1)+"1"+reverse(invert(func(i-1))); } public char findKthBit(int n, int k) { String s=func(n-1); return s.charAt(k-1); } }
class Solution { public: string Reverse(string s){ for(int i=0;i<s.length()/2;i++){ swap(s[i],s[s.length()-1-i]); } return s; } string invert(string s){ for(int i=0;i<s.length();i++){ if(s[i]=='1') s[i]='0'; else s[i]='1'; } return s; } string S(int n) { if(n==1){ return "0"; } return S(n-1) + "1" + Reverse(invert(S(n-1))); } char findKthBit(int n, int k) { if(n==1) return '0'; string s = S(n-1) + "1" + Reverse(invert(S(n-1))); return s[k-1]; } };
var findKthBit = function(n, k) { return recursivelyGenerate(n-1)[k-1]; } function recursivelyGenerate(bitLength, memo=new Array(bitLength+1)){ if(bitLength===0) return "0"; if(memo[bitLength]) return memo[bitLength]; const save = recursivelyGenerate(bitLength-1); memo[bitLength] = save + '1' + reverseInvert(save); return memo[bitLength]; } function reverseInvert(s){ return s.split("").map(a=>a==='0'?'1':'0').reverse().join(""); }
Find Kth Bit in Nth Binary String
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. You can move according to these rules: In 1 second, you can either: move vertically by one&nbsp;unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points that appear later in the order, but these do not count as visits. &nbsp; Example 1: Input: points = [[1,1],[3,4],[-1,0]] Output: 7 Explanation: One optimal path is [1,1] -&gt; [2,2] -&gt; [3,3] -&gt; [3,4] -&gt; [2,3] -&gt; [1,2] -&gt; [0,1] -&gt; [-1,0] Time from [1,1] to [3,4] = 3 seconds Time from [3,4] to [-1,0] = 4 seconds Total time = 7 seconds Example 2: Input: points = [[3,2],[-2,2]] Output: 5 &nbsp; Constraints: points.length == n 1 &lt;= n&nbsp;&lt;= 100 points[i].length == 2 -1000&nbsp;&lt;= points[i][0], points[i][1]&nbsp;&lt;= 1000
class Solution: def minTimeToVisitAllPoints(self, points): res = 0 n = len(points) for i in range(n-1): dx = abs(points[i+1][0]-points[i][0]) dy = abs(points[i+1][1]-points[i][1]) res+= max(dx,dy) return res obj = Solution() print(obj.minTimeToVisitAllPoints([[1,1],[3,4],[-1,0]]))
class Solution { public int minTimeToVisitAllPoints(int[][] points) { int max = 0, x, y; for(int i = 0; i < points.length - 1; i++){ for(int j = 0; j < points[i].length - 1; j++){ x = Math.abs(points[i][j] - points[i+1][j]); y = Math.abs(points[i][j+1] - points[i+1][j+1]); max += Math.max(x,y); } } return max; } }
class Solution { public: int minTimeToVisitAllPoints(vector<vector<int>>& points) { vector<int>sk; int x,y,maxy=0; for(int i=0;i<points.size()-1;i++){ for(int j=0;j<points[i].size()-1;j++){ x=abs(points[i][j]-points[i+1][j]); y=abs(points[i][j+1]-points[i+1][j+1]); maxy+=std::max(x,y); } } return maxy; } };
/** * @param {number[][]} points * @return {number} */ var minTimeToVisitAllPoints = function(points) { let sum = 0; for(let i=1; i<points.length; i++){ sum += Math.max(Math.abs(points[i][0] - points[i-1][0]) , Math.abs(points[i][1] - points[i-1][1])); } return sum; };
Minimum Time Visiting All Points
You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: The greatest common divisor of any adjacent values in the sequence is equal to 1. There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) &gt; 2. Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7. Two sequences are considered distinct if at least one element is different. &nbsp; Example 1: Input: n = 4 Output: 184 Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc. Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6). (1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed). (1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3. There are a total of 184 distinct sequences possible, so we return 184. Example 2: Input: n = 2 Output: 22 Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2). Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1. There are a total of 22 distinct sequences possible, so we return 22. &nbsp; Constraints: 1 &lt;= n &lt;= 104
mod=1000000007 @cache def func(n,prev,pp): if n==0: return 1 ans=0 for i in range(1,7): if prev==-1: ans+=func(n-1,i,prev) ans=ans%mod elif pp==-1: if(math.gcd(i,prev)==1 and i!=prev): ans+=func(n-1,i,prev) ans=ans%mod else: if(math.gcd(i,prev)==1 and i!=prev and i!=pp): ans+=func(n-1,i,prev) ans=ans%mod return ans; class Solution: def distinctSequences(self, n: int) -> int: return func(n,-1,-1)
class Solution { static long[][] dp; public int distinctSequences(int n) { if(n==1) return 6; int mod = 1_000_000_007; dp =new long[][] { {0,1,1,1,1,1}, {1,0,1,0,1,0}, {1,1,0,1,1,0}, {1,0,1,0,1,0}, {1,1,1,1,0,1}, {1,0,0,0,1,0} }; for(int i=2;i<n;i++){ long[][] temp = new long[6][6]; for(int j=0;j<6;j++){ for(int k=0;k<6;k++){ long total = 0; if(dp[j][k] == 0) continue; for(int l=0;l<6;l++){ total = (total + ((l==k)?0:dp[l][j]))%mod; } temp[j][k] = total; } } dp = temp; } long result = 0; for(int i=0;i<6;i++){ for(int j=0;j<6;j++){ result = (result + dp[i][j])%mod; } } return (int)(result); } }
class Solution { private: int mod = 1e9+7; int f(int ind,int prev1,int prev2,int n){ //Base Case if(ind == n) return 1; int ans = 0; for(int i = 1;i <= 6;i++) //Exploring all possible values if(prev1 != i && prev2 != i && (prev1 == 0 || __gcd(prev1,i) == 1)) ans = (ans + f(ind+1,i,prev1,n))%mod; return ans; } public: int distinctSequences(int n) { return f(0,0,0,n); } };
var distinctSequences = function(n) { // 3D DP [n + 1][7][7] => rollIdx, prev, prevPrev const dp = Array.from({ length: n + 1}, () => { return new Array(7).fill(0).map(() => new Array(7).fill(0)); }); const gcd = (a, b) => { if(a < b) [b, a] = [a, b]; while(b) { let temp = b; b = a % b; a = temp; } return a; } const ds = (n, p = 0, pp = 0) => { if(n == 0) return 1; if(dp[n][p][pp] == 0) { for(let i = 1; i <= 6; i++) { if((i != p && i != pp) && (p == 0 || gcd(p, i) == 1)) { dp[n][p][pp] = (dp[n][p][pp] + ds(n - 1, i, p)) % 1000000007; } } } return dp[n][p][pp]; } return ds(n); };
Number of Distinct Roll Sequences
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7. &nbsp; Example 1: Input: n = 1 Output: 12 Explanation: There are 12 possible way to paint the grid as shown. Example 2: Input: n = 5000 Output: 30228214 &nbsp; Constraints: n == grid.length 1 &lt;= n &lt;= 5000
class Solution: def numOfWays(self, n: int) -> int: two_c_options = 6 tot_options = 12 for i in range(n-1): temp = tot_options tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4) two_c_options = (two_c_options * 3) + ((temp - two_c_options) * 2) tot_options = tot_options % (1000000007) return tot_options
class Solution { int MOD = 1000000007; int[][] states = {{0,1,0},{1,0,1},{2,0,1}, {0,1,2},{1,0,2},{2,0,2}, {0,2,0},{1,2,0},{2,1,0}, {0,2,1},{1,2,1},{2,1,2}}; HashMap<Integer, List<Integer>> nextMap = new HashMap<>(); Long[][] memo; public int numOfWays(int n) { if(n == 0) return 0; // Graph for(int prev = 0; prev < 12; prev++){ List<Integer> nexts = new ArrayList<>(); for(int next = 0; next < 12; next++){ if(next == prev) continue; boolean flag = true; for(int i = 0; i < 3; i++){ if(states[prev][i] == states[next][i]){ flag = false; break; } } if(flag) nexts.add(next); } nextMap.put(prev, nexts); } //DFS memo = new Long[12][n]; long ways = 0; for(int i = 0; i < 12; i++){ ways += dfs(i, n-1); ways %= MOD; } return (int)(ways); } long dfs(int prev, int n){ if(n == 0) return 1; if(memo[prev][n] != null) return memo[prev][n]; long ways = 0; List<Integer> nexts = nextMap.get(prev); for(int next : nexts){ ways += dfs(next, n-1); ways %= MOD; } memo[prev][n] = ways; return ways; } }
class Solution { public: int numOfWays(int n) { int mod=1e9+7; long long c2=6,c3=6; for(int i=2;i<=n;i++){ long long temp=c3; c3=(2*c3+2*c2)%mod; c2=(2*temp+3*c2)%mod; } return (c2+c3)%mod; } };
/** * @param {number} n * @return {number} */ var numOfWays = function(n) { const mod = Math.pow(10, 9) + 7; const dp212 = [6]; const dp123 = [6]; for (let i = 1; i < n; i++) { // two sides same dp212[i] = (dp212[i - 1] * (5 - 2) + dp123[i - 1] * (6 - 2 - 1 - 1)) % mod; // three different colors dp123[i] = (dp123[i - 1] * (5 - 1 - 1 - 1) + dp212[i - 1] * (6 - 2 - 2)) % mod; } return (dp212[n - 1] + dp123[n - 1]) % mod; };
Number of Ways to Paint N × 3 Grid
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1. &nbsp; Example 1: Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 Output: 2 Example 2: Input: times = [[1,2,1]], n = 2, k = 1 Output: 1 Example 3: Input: times = [[1,2,1]], n = 2, k = 2 Output: -1 &nbsp; Constraints: 1 &lt;= k &lt;= n &lt;= 100 1 &lt;= times.length &lt;= 6000 times[i].length == 3 1 &lt;= ui, vi &lt;= n ui != vi 0 &lt;= wi &lt;= 100 All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
import heapq class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: adjlist = [[] for _ in range(n+1)] for src, dst, weight in times: adjlist[src].append((dst, weight)) visited = [-1]*(n+1) captured =[-1]*(n+1) priority_queue = [(0,k)] nums = 0 total_dist = 0 while priority_queue: dst, node = heapq.heappop(priority_queue) if captured[node] != -1: continue captured[node] = dst nums += 1 total_dist = dst for nbr,wt in adjlist[node]: if captured[nbr] == -1: heapq.heappush(priority_queue,(captured[node]+wt, nbr)) if nums == n: return total_dist else: return -1
class Solution { HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>(); public int networkDelayTime(int[][] times, int n, int k) { for (int i = 1; i <= n; i++) { map.put(i, new HashMap<>()); } for (int i = 0; i < times.length; i++) { map.get(times[i][0]).put(times[i][1], times[i][2]); } int ans = BFS(k, n); return ans == 1000 ? -1 : ans; } public int BFS(int k, int n) { LinkedList<Integer> queue = new LinkedList<>(); int[] timeReach = new int[n + 1]; Arrays.fill(timeReach, 1000); timeReach[0] = 0; timeReach[k] = 0; queue.add(k); while (!queue.isEmpty()) { int rv = queue.remove(); for (int nbrs : map.get(rv).keySet()) { int t = map.get(rv).get(nbrs) + timeReach[rv]; if (t < timeReach[nbrs]) { timeReach[nbrs] = t; queue.add(nbrs); } } } int time = 0; for (int i : timeReach) { time = Math.max(i, time); } return time; } }
class cmp{ public: bool operator()(pair<int,int> &a,pair<int,int> &b) { return a.second>b.second; } }; class Solution { public: int networkDelayTime(vector<vector<int>>& times, int n, int k) { vector<pair<int,int>> a[n]; for(auto it:times) { a[it[0]-1].push_back({it[1]-1,it[2]}); } priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> pq; vector<int> dist(n,1e7); pq.push({k-1,0}); vector<int> vis(n,0); while(pq.size()) { auto curr = pq.top(); pq.pop(); int v = curr.first; int w = curr.second; if(vis[v])continue; vis[v] = 1; dist[v] = w; for(auto it:a[v]) { if(vis[it.first]==0) { pq.push({it.first,it.second + w}); } } } int mx = INT_MIN; for(auto it:dist) mx = max(mx,it); if(mx>=1e7)return -1; return mx; } };
/** * @param {number[][]} times * @param {number} n * @param {number} k * @return {number} */ let visited,edges,dijkastra_arr,min_heap const MAX_VALUE=Math.pow(10,6); const dijkastra=(source)=>{ visited[source]=true; min_heap.pop(); let nei=edges[source]||[]; // if(!nei.length)return; for(let i=0;i<nei.length;i++){ let[src,dst,t]=nei[i]; if(visited[dst])continue; let time_till_src=dijkastra_arr[src]; if(time_till_src>=MAX_VALUE)continue; let time_till_dst=time_till_src+t; dijkastra_arr[dst]=Math.min(dijkastra_arr[dst],time_till_dst); } min_heap.sort((a,b)=>{ return dijkastra_arr[b]-dijkastra_arr[a]; }); if(min_heap.length && dijkastra_arr[min_heap[min_heap.length-1]]<MAX_VALUE) dijkastra(min_heap[min_heap.length-1]); } var networkDelayTime = function(times, n, k) { visited=[]; edges={}; dijkastra_arr=[]; min_heap=[]; for(let i=0;i<times.length;i++){ if(!edges[times[i][0]])edges[times[i][0]]=[]; edges[times[i][0]].push(times[i]); } // console.log(edges,"edges") for(let i=0;i<=n;i++){ if(i===0){//cz numbes are starting from One visited[i]=true; dijkastra_arr[i]=-1; min_heap[i]=i; }else{ min_heap[i]=i; dijkastra_arr[i]=MAX_VALUE; visited[i]=false; } } dijkastra_arr[k]=0; min_heap.sort((a,b)=>{ return dijkastra_arr[b]-dijkastra_arr[a]; }); min_heap.pop();//For removing zeroth entry; dijkastra(k); let max_time=0; if(min_heap.length)return -1; for(let i=0;i<dijkastra_arr.length;i++){ max_time=Math.max(dijkastra_arr[i],max_time); } return max_time; };
Network Delay Time
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. &nbsp; Example 1: Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Example 2: Input: head = [1,1,1,2,3] Output: [2,3] &nbsp; Constraints: The number of nodes in the list is in the range [0, 300]. -100 &lt;= Node.val &lt;= 100 The list is guaranteed to be sorted in ascending order.
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: if (not head): return None result = tail = ListNode(-1) while(head): curr = head head = head.next hasDup = False while(head) and (curr.val == head.val): hasDup = True headNext = head.next head = None head = headNext if (hasDup == False): tail.next = curr tail = tail.next tail.next = None return result.next
class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) return head; ListNode temp = head; int last = -1; int[]array = new int[201]; // zero == index 100 // one == index 101; // -100 == index 0; while (temp != null){ array[temp.val + 100]++; temp = temp.next; } for (int i = 0; i < 201; i++){ if (array[i] == 1){ last = i; } } if (last == -1) return null; temp = head; for (int i = 0; i < 201; i++){ if (array[i] == 1){ temp.val = i - 100; if (i == last){ temp.next = null; break; } temp=temp.next; } } temp.next = null; return head; } }```
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* k=new ListNode(); ListNode *root=k,*cur=head; while(cur!=NULL) { ListNode *t=cur; while(t->next!=NULL && t->next->val==t->val) t=t->next; if(t==cur) { if(root==NULL) root->val=t->val; else { ListNode* p=new ListNode(t->val); root->next=p; root=root->next; } } cur=t->next; } return k->next; } };
var deleteDuplicates = function(head) { let map = new Map() let result = new ListNode(-1) let newCurr = result let curr = head while(head){ if(map.has(head.val)){ map.set(head.val, 2) }else{ newArr.push(head.val) map.set(head.val, 1) } head = head.next } while(curr){ if(map.get(curr.val) !== 2){ newCurr.next = new ListNode(curr.val) newCurr = newCurr.next } curr = curr.next } return result.next };
Remove Duplicates from Sorted List II
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. &nbsp; Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3] Example 2: Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3] &nbsp; Constraints: n == graph.length 1 &lt;= n &lt;= 12 0 &lt;= graph[i].length &lt;&nbsp;n graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. The input graph is always connected.
class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: n = len(graph) dist = [[inf]*n for _ in range(n)] for i, x in enumerate(graph): dist[i][i] = 0 for ii in x: dist[i][ii] = 1 # floyd-warshall for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) @cache def fn(x, mask): if mask == 0: return 0 ans = inf for i in range(n): if mask & (1 << i): ans = min(ans, dist[x][i] + fn(i, mask ^ (1<<i))) return ans return min(fn(x, (1 << n)-1) for x in range(n))
class Solution { class Pair { int i; int path; public Pair(int i, int path) { this.i = i; this.path = path; } } public int shortestPathLength(int[][] graph) { /* For each node currentNode, steps as key, visited as value boolean[currentNode][steps] */ int n = graph.length; // 111....1, 1<< n - 1 int allVisited = (1 << n) - 1; boolean[][] visited = new boolean[n][1 << n]; Queue<Pair> q = new LinkedList<>(); for (int i = 0; i < n; i++) { if (1 << i == allVisited) return 0; visited[i][1 << i] = true; q.offer(new Pair(i, 1 << i)); } int step = 0; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { Pair p = q.poll(); int[] edges = graph[p.i]; for(int t: edges) { int path = p.path | (1 << t); if (path == allVisited) return step + 1; if (!visited[t][path]) { visited[t][path] = true; q.offer(new Pair(t, path)); } } } step++; } return step; } }
class Solution { public: int shortestPathLength(vector<vector<int>>& graph) { int n = graph.size(); string mask = ""; string eq = ""; for(int i=0; i<n; i++){ mask += '0'; eq += '1'; } queue<pair<int,string>>q; set<pair<int,string>>s; for(int i=0; i<n; i++){ string temp = mask; temp[i] = '1'; q.push({i,temp}); s.insert({i,temp}); } int c = 0; int flag = 0; while(!q.empty()){ int size = q.size(); for(int i=0; i<size; i++){ auto top = q.front(); q.pop(); if(top.second == eq) return c; for(auto p: graph[top.first]){ string temp1 = top.second; temp1[p] = '1'; if(s.count({p,temp1}) == 0){ q.push({p,temp1}); s.insert({p,temp1}); } } } c++; cout<<"c is "<<c; } return -1; } };
/** * @param {number[][]} graph * @return {number} */ var shortestPathLength = function(graph) { const n = graph.length; const allVisited = (1 << n) - 1; const queue = []; const visited = new Set(); for (let i = 0; i < n; i++) { queue.push([1 << i, i, 0]); visited.add((1 << i) * 16 + i); } while (queue.length > 0) { const [mask, node, dist] = queue.shift(); if (mask === allVisited) { return dist; } for (const neighbor of graph[node]) { const newMask = mask | (1 << neighbor); const hashValue = newMask * 16 + neighbor; if (!visited.has(hashValue)) { visited.add(hashValue); queue.push([newMask, neighbor, dist + 1]); } } } return -1; }
Shortest Path Visiting All Nodes
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. &nbsp; Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1]. Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5 &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 1000 0 &lt;= nums1[i], nums2[i] &lt;= 100
class Solution: def findLength(self, nums1: List[int], nums2: List[int]) -> int: dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)] max_len = 0 for row in range(len(nums2)): for col in range(len(nums1)): if nums2[row] == nums1[col]: dp[row][col] = 1 + dp[row - 1][col - 1] max_len = max(max_len,dp[row][col]) else: dp[row][col] = 0 return max_len
class Solution { public int findLength(int[] nums1, int[] nums2) { int n= nums1.length , m = nums2.length; int[][] dp = new int [n+1][m+1]; // for(int [] d: dp)Arrays.fill(d,-1); int ans =0; for(int i =n-1;i>=0;i--){ for(int j = m-1 ;j>=0;j--){ if(nums1[i]==nums2[j]){ dp[i][j] = dp[i+1][j+1]+1; if(ans<dp[i][j])ans = dp[i][j]; } } } return ans; } }
class Solution { public: int findLength(vector<int>& nums1, vector<int>& nums2) { int n1 = nums1.size(); int n2 = nums2.size(); //moving num2 on num1 int ptr2 = 0; int cnt = 0; int largest = INT_MIN; for(int i=0;i<n1;i++) { cnt = 0; for(int j=i,ptr2=0;j<n1 && ptr2<n2;j++,ptr2++) { if(nums1[j]==nums2[ptr2]) { cnt++; } else { cnt = 0; } largest = max(largest,cnt); } } //moving num1 on num2 ptr2 = 0; cnt = 0; for(int i=0;i<n2;i++) { cnt = 0; for(int j=i,ptr2=0;j<n2 && ptr2<n1;j++,ptr2++) { if(nums2[j]==nums1[ptr2]) { cnt++; } else { cnt = 0; } largest = max(largest,cnt); } } return largest; } };
var findLength = function(nums1, nums2) { let dp = new Array(nums1.length+1).fill(0).map( () => new Array(nums2.length+1).fill(0) ) let max = 0; for (let i = 0; i < nums1.length; i++) { for (let j = 0; j < nums2.length; j++) { if (nums1[i] != nums2[j]) { continue; } dp[i+1][j+1] = dp[i][j]+1; max = Math.max(max, dp[i+1][j+1]); } } return max; };
Maximum Length of Repeated Subarray
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score. &nbsp; Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. &nbsp; Constraints: 1 &lt;= stoneValue.length &lt;= 5 * 104 -1000 &lt;= stoneValue[i] &lt;= 1000
class Solution(object): def stoneGameIII(self, stoneValue): """ :type stoneValue: List[int] :rtype: str """ n = len(stoneValue) suffixSum = [0 for _ in range(n+1)] dp = [0 for _ in range(n+1)] for i in range(n-1, -1, -1): suffixSum[i] = suffixSum[i+1] + stoneValue[i] for i in range(n-1, -1, -1): dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1] for k in range(i+1, min(n, i+3)): dp[i] = max(dp[i], suffixSum[i] - dp[k+1]) if dp[0]*2 == suffixSum[0]: return "Tie" elif dp[0]*2 > suffixSum[0]: return "Alice" else: return "Bob"
class Solution { Integer[] dp; public String stoneGameIII(int[] stoneValue) { dp = new Integer[stoneValue.length + 1]; Arrays.fill(dp, null); int ans = stoneGameIII(0, stoneValue); if (ans == 0) return "Tie"; else if (ans > 0) return "Alice"; else return "Bob"; } public int stoneGameIII(int l, int[] s) { if (l >= s.length) return 0; if (dp[l] != null) return dp[l]; int ans; ans = Integer.MIN_VALUE; if (l < s.length) { ans = Math.max(ans, s[l] - stoneGameIII(l + 1, s)); } if (l + 1 < s.length) { ans = Math.max(ans, s[l] + s[l + 1] -stoneGameIII(l + 2, s)); } if (l + 2 < s.length) { ans = Math.max(ans, s[l] + s[l + 1] +s[l + 2] -stoneGameIII(l + 3, s)); } return dp[l] = ans; } }
class Solution { public: int dp[50001][2][2]; int playGame(vector<int>& stones, bool alice, bool bob, int i) { if (i >= stones.size()) return 0; int ans; int sum = 0; if (dp[i][alice][bob] != -1) return dp[i][alice][bob]; if (alice) { ans = INT_MIN; for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) { sum += stones[idx]; ans = max(ans, sum + playGame(stones, false, true, idx + 1)); } } if (bob) { ans = INT_MAX; for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) { sum += stones[idx]; ans = min(ans, playGame(stones, true, false, idx + 1)); } } return dp[i][alice][bob] = ans; } string stoneGameIII(vector<int>& stoneValue) { memset(dp, -1, sizeof dp); int totalScore = 0; for (auto i : stoneValue) totalScore += i; int aliceScore = playGame(stoneValue, true, false, 0); if (totalScore - aliceScore > aliceScore) return "Bob"; else if (totalScore - aliceScore < aliceScore) return "Alice"; else return "Tie"; } };
var stoneGameIII = function(stoneValue) { let len = stoneValue.length-1 let bestMoves = [0,0,0] bestMoves[len%3] = stoneValue[len] for(let i = len-1; i >= 0 ; i--){ let turn = stoneValue[i] let option1 = turn - bestMoves[(i+1)%3] turn += stoneValue[i+1] ||0 let option2 = turn - bestMoves[(i+2)%3] turn += stoneValue[i+2] || 0 let option3 = turn - bestMoves[i %3] let best = Math.max(option1,option2,option3) bestMoves[i%3] = best } return bestMoves[0] > 0 ? "Alice" : bestMoves[0] !== 0 ? "Bob" : "Tie" };
Stone Game III
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: num = "52" Output: "5" Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. Example 2: Input: num = "4206" Output: "" Explanation: There are no odd numbers in "4206". Example 3: Input: num = "35427" Output: "35427" Explanation: "35427" is already an odd number. &nbsp; Constraints: 1 &lt;= num.length &lt;= 105 num only consists of digits and does not contain any leading zeros.
class Solution: def largestOddNumber(self, num: str) -> str: indx = -1 n = len(num) for i in range(n): if int(num[i])%2 == 1: indx = i if indx == -1: return "" return num[:indx+1]
class Solution { public String largestOddNumber(String num) { for (int i = num.length() - 1; i > -1; i--) { if (num.charAt(i) % 2 == 1) return num.substring(0,i+1); } return ""; } }
class Solution { public: string largestOddNumber(string num) { // Length of the given string int len = num.size(); // We initialize an empty string for the result string res = ""; // We start searching digits from the very right to left because we want to find the first odd digit // Which will be the last digit of our biggest odd number for (int i = len - 1; i >= 0; i--) { // Here we just convert char to an integer in C++ // We can also do the reverse operation by adding '0' to an int to get char from an int int isOdd = num[i] - '0'; // We check if the current digit is odd, if so this is the position we want to find if (isOdd % 2 == 1) { // Since we have found the correct spot, let's create our result string // We can basically extract the part starting from 0th index to right most odd digit's index // Like this: // 0123456 -> indices // 1246878 -> digits // ^....^ -> The part we extracted [0 to 5] res = num.substr(0, i + 1); // i+1 is length of substring // Because we know this would be the largest substring as we are starting from last // We can terminate the loop and return the result break; } } return res; } };
var largestOddNumber = function(num) { for (let i = num.length - 1; i >= 0; i--) { // +num[i] converts string into number like parseInt(num[i]) if ((+num[i]) % 2) { return num.slice(0, i + 1); } } return ''; };
Largest Odd Number in String
Given a matrix&nbsp;and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 &lt;= x &lt;= x2 and y1 &lt;= y &lt;= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate&nbsp;that is different: for example, if x1 != x1'. &nbsp; Example 1: Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4 Explanation: The four 1x1 submatrices that only contain 0. Example 2: Input: matrix = [[1,-1],[-1,1]], target = 0 Output: 5 Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. Example 3: Input: matrix = [[904]], target = 0 Output: 0 &nbsp; Constraints: 1 &lt;= matrix.length &lt;= 100 1 &lt;= matrix[0].length &lt;= 100 -1000 &lt;= matrix[i] &lt;= 1000 -10^8 &lt;= target &lt;= 10^8
class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: m, n = len(matrix), len(matrix[0]) matrix_sums = [[0 for _ in range(n)] for _ in range(m)] # Calculate all the submatrices sum with the transition formula we found for row in range(m): for col in range(n): # first cell if row == 0 and col == 0: matrix_sums[row][col] = matrix[row][col] # Rows and columns are like prefix sums, without intersection elif row == 0: matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col-1] elif col == 0: matrix_sums[row][col] = matrix[row][col] + matrix_sums[row-1][col] # current sum is the sum of the matrix above, to the left and subtract the intersection else: matrix_sums[row][col] = matrix[row][col] \ + (matrix_sums[row][col-1]) \ + (matrix_sums[row-1][col]) \ - (matrix_sums[row-1][col-1]) ans = 0 # Generate all submatrices for y1 in range(m): for x1 in range(n): for y2 in range(y1, m): for x2 in range(x1, n): # calculate sum in O(1) submatrix_total = matrix_sums[y2][x2] \ - (matrix_sums[y2][x1-1] if x1-1 >= 0 else 0) \ - (matrix_sums[y1-1][x2] if y1-1 >= 0 else 0) \ + (matrix_sums[y1-1][x1-1] if y1-1 >= 0 and x1-1 >= 0 else 0) if submatrix_total == target: ans += 1 return ans
class Solution { public int numSubmatrixSumTarget(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; int[] summedArray = new int[n]; int ans = 0; for(int i = 0; i < m; i++){ //starting row Arrays.fill(summedArray, 0); for(int j = i; j < m; j++){ //ending row for(int k = 0; k < n; k++){ // column summedArray[k] += matrix[j][k]; } ans += subarraySum(summedArray, target); } } return ans; } public int subarraySum(int[] nums, int k) { //map<sum, freq> Map<Integer, Integer> map = new HashMap<>(); int count = 0; map.put(0,1); int sum = 0; for(int num : nums){ sum += num; int diff = sum - k; if(map.containsKey(diff)){ count += map.get(diff); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return count; } }
class Solution { public: int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { int n=matrix.size(),m=matrix[0].size(),count=0; vector<vector<int>>temp(n+1,vector<int>(m)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ temp[i+1][j]=temp[i][j]+matrix[i][j]; } } for(int i=0;i<n;i++){ for(int j=i+1;j<=n;j++){ for(int k=0;k<m;k++){ int sum=0; for(int l=k;l<m;l++){ sum+=temp[j][l]-temp[i][l]; if(sum==target){ // cout<<j<<" "<<i<<" "<<k<<endl; count++; } } } } } return count; } };
var numSubmatrixSumTarget = function(matrix, target) { let result = 0; for (let i = 0; i < matrix.length; i++) { for (let j = 1; j < matrix[0].length; j++) { matrix[i][j] = matrix[i][j] + matrix[i][j-1] } } for (let i = 0; i < matrix[0].length; i++) { for (let j = i; j < matrix[0].length; j++) { let dict = {}; let cur = 0; dict[0] = 1; for (let k = 0; k < matrix.length; k++) { cur += matrix[k][j] - ((i > 0)?(matrix[k][i - 1]):0); result += ((dict[cur - target] == undefined)?0:dict[cur - target]); dict[cur] = ((dict[cur] == undefined)?0:dict[cur])+1; } } } return result; };
Number of Submatrices That Sum to Target
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. &nbsp; Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] &nbsp; Constraints: 1 &lt;= numCourses &lt;= 2000 0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 &lt;= ai, bi &lt; numCourses ai != bi All the pairs [ai, bi] are distinct.
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: d = {i:[] for i in range(numCourses)} for crs, prereq in prerequisites: d[crs].append(prereq) visit, cycle = set(), set() output = [] def dfs(crs): if crs in cycle: return False if crs in visit: return True cycle.add(crs) for nei in d[crs]: if not dfs(nei): return False cycle.remove(crs) visit.add(crs) output.append(crs) return True for crs in range(numCourses): if not dfs(crs): return [] return output
class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { Map<Integer, Set<Integer>> graph = new HashMap<>(); int[] inDegree = new int[numCourses]; for (int i = 0; i < numCourses; i++) { graph.put(i, new HashSet<Integer>()); } for (int[] pair : prerequisites) { graph.get(pair[1]).add(pair[0]); inDegree[pair[0]]++; } // BFS - Kahn's Algorithm - Topological Sort Queue<Integer> bfsContainer = new LinkedList<>(); for (int i = 0; i < numCourses; i++) { if (inDegree[i] == 0) { bfsContainer.add(i); } } int count = 0; int[] ans = new int[numCourses]; while (!bfsContainer.isEmpty()) { int curr = bfsContainer.poll(); ans[count++] = curr; for (Integer num : graph.get(curr)) { inDegree[num]--; if (inDegree[num] == 0) { bfsContainer.add(num); } } } if (count < numCourses) { return new int[] {}; } else { return ans; } } }
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { map<int, vector<int>>adj; vector<int> indegree(numCourses,0); vector<int>res; for(int i=0;i<prerequisites.size();i++){ adj[prerequisites[i][1]].push_back(prerequisites[i][0]); indegree[prerequisites[i][0]]++; } queue<int> q; for(int i=0;i<numCourses;i++){ if(indegree[i]==0) q.push(i); } while(!q.empty()){ int x=q.front(); q.pop(); res.push_back(x); for(auto u:adj[x]){ indegree[u]--; if(indegree[u]==0){ q.push(u); } } } if(res.size()==numCourses) return res; return {}; } };
/** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */ var findOrder = function(numCourses, prerequisites) { let visiting = new Set(); const visited = new Set(); const adjList = new Map(); const result = []; // Generate scaffold of adjacency list // initialized with no prereqs for (let i = 0; i < numCourses; i++) { adjList.set(i, []); } // Fill adjacency list with course prereqs // Key is the course // Value is any course prereqs for (const item of prerequisites) { const [course, prereq] = item; adjList.get(course).push(prereq); } const dfs = (node) => { // We've already traversed down this path before // and determined that it isn't cyclical if (visited.has(node)) return true; // Visiting keeps track of what we've seen // during this current traversal and determines // if we have a cycle. if (visiting.has(node)) return false; // Mark this node as part of the current traversal visiting.add(node); // Get all adjacent nodes to traverse // traverse them in a loop looking for cycles const children = adjList.get(node); for (const child of children) { if (!dfs(child)) return false; } // Ensures we don't re-traverse already traversed nodes since // we've already determined they contain no cycles. visited.add(node); // Add this node to the result stack to return at the end result.push(node); return true; } for (const node of adjList.keys()) { if(!dfs(node)) return []; } return result; };
Course Schedule II
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a &lt;= b) denotes the set of real numbers x with a &lt;= x &lt;= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. &nbsp; Example 1: Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] Example 2: Input: firstList = [[1,3],[5,9]], secondList = [] Output: [] &nbsp; Constraints: 0 &lt;= firstList.length, secondList.length &lt;= 1000 firstList.length + secondList.length &gt;= 1 0 &lt;= starti &lt; endi &lt;= 109 endi &lt; starti+1 0 &lt;= startj &lt; endj &lt;= 109 endj &lt; startj+1
from collections import deque class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: answer = [] if len(firstList) == 0 or len(secondList) == 0: return answer first_queue= deque(firstList) second_queue = deque(secondList ) first = first_queue.popleft() second = second_queue.popleft() while first_queue or second_queue: if first[1] < second[0]: if len(first_queue): first = first_queue.popleft() continue break if second[1] < first[0]: if len(second_queue) > 0: second = second_queue.popleft() continue break if first[0] <= second[0] and second[0] <= first[1]: if first[1] <= second[1]: answer.append([second[0], first[1]]) if len(first_queue) > 0: first = first_queue.popleft() continue break else: answer.append(second) if len(second_queue) > 0: second = second_queue.popleft() continue break if second[0] <= first[0] and first[0] <= second[1]: if second[1] <= first[1]: answer.append([first[0], second[1]]) if len(second_queue) > 0: second = second_queue.popleft() continue break else: answer.append(first) if len(first_queue) > 0: first = first_queue.popleft() continue break if first[0] <= second[0] and second[0] <= first[1]: if first[1] <= second[1]: if len(answer) > 0: if answer[-1] != [second[0], first[1]]: answer.append([second[0], first[1]]) elif not answer: answer.append([second[0], first[1]]) else: if len(answer) > 0: if answer[-1] != second: answer.append(second) elif not answer: answer.append(second) elif second[0] <= first[0] and first[0] <= second[1]: if second[1] <= first[1]: if len(answer) > 0: if answer[-1] != [first[0], second[1]]: answer.append([first[0], second[1]]) elif not answer: answer.append([first[0], second[1]]) else: if len(answer) > 0: if answer[-1] != first: answer.append(first) elif not answer: answer.append(first) return answer
class Solution { public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { int i = 0; int j = 0; List<int[]> ans = new ArrayList<>(); while(i<firstList.length && j<secondList.length){ int a[] = firstList[i]; int b[] = secondList[j]; if(b[0]<=a[1] && b[0]>=a[0]) ans.add(new int[]{b[0], Math.min(a[1], b[1])}); else if(a[0]<=b[1] && a[0]>=b[0]) ans.add(new int[]{a[0], Math.min(a[1], b[1])}); if(a[1]<=b[1]) i++; else j++; } int res[][] = new int[ans.size()][2]; for(i=0;i<ans.size();i++){ res[i] = ans.get(i); } return res; } }
class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) { vector<vector<int>> result; int i = 0; int j = 0; while(i < firstList.size() && j < secondList.size()){ if((firstList[i][0] >= secondList[j][0] && firstList[i][0] <= secondList[j][1])||(secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1]) ){ //there is an overlap result.push_back( {max(firstList[i][0], secondList[j][0]), min(firstList[i][1], secondList[j][1])}); } if(firstList[i][1] < secondList[j][1]){ i++; } else{ j++; } } return result; } };
var intervalIntersection = function(firstList, secondList) { //if a overlap b - a.start >= b.start && a.start <= b.end //if b overlap a - b.start >= a.start && b.start <= a.end //handle empty edge cases if(firstList.length === 0 || secondList.length === 0){ return []; } let merged = []; let i =0; let j = 0; while(i<firstList.length && j < secondList.length){ let a_overlap_b = firstList[i][0] >= secondList[j][0] && firstList[i][0] <= secondList[j][1]; let b_overlap_a = secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1]; if(a_overlap_b || b_overlap_a){ let start = Math.max(firstList[i][0], secondList[j][0]); let end = Math.min(firstList[i][1], secondList[j][1]); merged.push([start, end]); } if(firstList[i][1] < secondList[j][1]){ i++; }else { j++; } } return merged; };
Interval List Intersections
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it. &nbsp; Example 1: Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) Example 2: Input: root = [1,null,2,3,4,null,null,5,6] Output: 90 Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6) &nbsp; Constraints: The number of nodes in the tree is in the range [2, 5 * 104]. 1 &lt;= Node.val &lt;= 104
class Solution: def maxProduct(self, root: Optional[TreeNode]) -> int: def findTotalSum(node, totalSum): if node is None: return totalSum totalSum = findTotalSum(node.left,totalSum) totalSum += node.val totalSum = findTotalSum(node.right,totalSum) return totalSum def dfs(node,maxProd,totalSum): if node is None: return maxProd,0 if not node.left and not node.right: return maxProd,node.val maxProd, lSum = dfs(node.left,maxProd,totalSum) maxProd, rSum = dfs(node.right,maxProd,totalSum) subTreeSum = lSum+rSum+node.val maxProd = max(maxProd,(totalSum-lSum)*lSum,(totalSum-rSum)*rSum,(totalSum-subTreeSum)*subTreeSum) return maxProd, subTreeSum totalSum = findTotalSum(root, 0) product,_ = dfs(root,1,totalSum) return product % (pow(10,9)+7)
class Solution { public void findMaxSum(TreeNode node,long sum[]){ if(node==null) return ; findMaxSum(node.left,sum); findMaxSum(node.right,sum); sum[0]+=node.val; } public long findProd(TreeNode node,long sum[],long []max){ if(node==null) return 0; long left=findProd(node.left, sum, max); long right=findProd(node.right,sum,max); long val=left+right+node.val; max[0]=Math.max(max[0],val*(sum[0]-val)); return val; } public int maxProduct(TreeNode root) { long max[]=new long[1]; long sum[]=new long[1]; findMaxSum(root,sum); long n= findProd(root,sum,max); return (int)(max[0]%((int)1e9+7)); } }
class Solution { public: int mod = 1e9+7; unordered_map<TreeNode*,pair<long long int,long long int>> mp; long long int helper(TreeNode* root){ if(!root) return 0; long long int ls = 0,rs = 0; if(root->left) ls = helper(root->left); if(root->right) rs = helper(root->right); mp[root] = {ls,rs}; return ls+rs+root->val; } long long int ans = 0; void helper2(TreeNode* root,long long int adon){ if(root == NULL) return; long long int x = root->val + adon; ans = max(ans,max((x+mp[root].first)*mp[root].second,(x+mp[root].second)*mp[root].first)); helper2(root->left,x+mp[root].second); helper2(root->right,x+mp[root].first); } int maxProduct(TreeNode* root) { long long int x = helper(root); helper2(root,0); return ans%mod; } };
var maxProduct = function(root) { const lefteRightSumMap = new Map(); function getLeftRightSumMap(node) { if (node === null) return 0; let leftSum = getLeftRightSumMap(node.left); let rightSum = getLeftRightSumMap(node.right); lefteRightSumMap.set(node, {leftSum, rightSum}); return leftSum + rightSum + node.val; } getLeftRightSumMap(root); let maxProduct = -Infinity; function getMaxProductDFS(node, parentSum) { if (node === null) return; const {leftSum, rightSum} = lefteRightSumMap.get(node); // cut left edge maxProduct = Math.max(maxProduct, leftSum * (parentSum + node.val + rightSum)); // cut right edge maxProduct = Math.max(maxProduct, rightSum * (parentSum + node.val + leftSum)); getMaxProductDFS(node.left, parentSum + node.val + rightSum); getMaxProductDFS(node.right, parentSum + node.val + leftSum); } getMaxProductDFS(root, 0); return maxProduct % (Math.pow(10, 9) + 7); };
Maximum Product of Splitted Binary Tree
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. &nbsp; Example 1: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: Input: head = [0] Output: 0 &nbsp; Constraints: The Linked List is not empty. Number of nodes will not exceed 30. Each node's value is either 0 or 1.
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: res = 0 po = 0 stack = [] node = head while node: stack.append(node.val) node = node.next res = 0 for i in reversed(stack): res += i*(2**po) po += 1 return res
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public int getDecimalValue(ListNode head) { head = reverse(head); int ans = 0; int pow = 0; ListNode temp = head; while(temp != null){ ans = ans + temp.val * (int) Math.pow(2,pow++); temp = temp.next; } return ans; } public ListNode reverse(ListNode head){ ListNode prev = null; ListNode pres = head; ListNode Next = pres.next; while(pres != null){ pres.next = prev; prev = pres; pres = Next; if(Next != null){ Next = Next.next; } } head = prev; return head; } }
class Solution { public: int getDecimalValue(ListNode* head) { ListNode* temp = head; int count = 0; while(temp->next != NULL){ count++; temp = temp->next; } temp = head; int ans = 0; while(count != -1){ ans += temp->val * pow(2,count); count--; temp = temp->next; } return ans; } };
var getDecimalValue = function(head) { let str = "" while(head){ str += head.val head = head.next } return parseInt(str,2) //To convert binary into Integer
Convert Binary Number in a Linked List to Integer
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. &nbsp; Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 nums[i] is either 0 or 1.
class Solution: def longestSubarray(self, nums: List[int]) -> int: n = len(nums) pre, suf = [1]*n, [1]*n if nums[0] == 0:pre[0] = 0 if nums[-1] == 0:suf[-1] = 0 for i in range(1, n): if nums[i] == 1 and nums[i-1] == 1: pre[i] = pre[i-1] + 1 elif nums[i] == 0: pre[i] = 0 for i in range(n-2, -1, -1): if nums[i] == 1 and nums[i+1] == 1: suf[i] = suf[i+1] + 1 elif nums[i] == 0: suf[i] = 0 ans = 0 for i in range(n): if i == 0: ans = max(ans, suf[i+1]) elif i == n-1: ans = max(ans, pre[i-1]) else: ans = max(ans, pre[i-1] + suf[i+1]) return ans
class Solution { public int longestSubarray(int[] nums) { List<Integer> groups = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) groups.add(nums[i]); if (nums[i] == 1) { int count = 0; while (i < nums.length && nums[i] == 1) { count++; i++; } groups.add(count); if (i < nums.length && nums[i] == 0) groups.add(0); } } int max = 0; if (groups.size() == 1) { return groups.get(0) - 1; } for (int i = 0; i < groups.size(); i++) { if (i < groups.size() - 2) { max = Math.max(max, groups.get(i) + groups.get(i+2)); } else { max = Math.max(max, groups.get(i)); } } return max; } }
class Solution { public: int longestSubarray(vector<int>& nums) { int x=0,y=0,cnt=0; for(int i=0;i<nums.size();i++){ if(nums[i]==1){ x++; } else if(nums[i]==0){ cnt=max(cnt,x+y); y=x; x=0; } if(i==nums.size()-1){ cnt=max(cnt,x+y); } } if(cnt==nums.size())return cnt-1; return cnt; } };
var longestSubarray = function(nums) { let l = 0, r = 0; let longest = 0; // Keep track of the idx where the last zero was seen let zeroIdx = null; while (r < nums.length) { // If we encounter a zero if (nums[r] === 0) { // If this is the first zero encountered, then set the zeroIdx to the current r index if (zeroIdx === null) zeroIdx = r; else { // If we've already encountered a zero, then set the l index to the zeroIdx + 1, // effectively removing that zero from the subarray l = zeroIdx + 1; // Then update the zeroIdx to the current r index // This way there will be, at most, one zero in the subarray at all times zeroIdx = r; } } longest = Math.max(longest, r - l); r++; } return longest; };
Longest Subarray of 1's After Deleting One Element
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 &lt;= i1 &lt; i2 &lt; ... &lt; ik &lt;= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 &lt;= i &lt; seq.length - 1). &nbsp; Example 1: Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5]. &nbsp; Constraints: 2 &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt;= 500
class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: dp = [[1]*1001 for i in range(len(nums))] for i in range(len(nums)): for j in range(i+1,len(nums)): d = nums[j] - nums[i] + 500 dp[j][d] = max(dp[i][d]+1,dp[j][d]) return max([max(i) for i in dp])
class Solution { public int longestArithSeqLength(int[] nums) { int n = nums.length; int longest = 0; Map<Integer, Integer>[] dp = new HashMap[n]; for (int i = 0; i < n; i++) { dp[i] = new HashMap<>(); for (int j = 0; j < i; j++) { int diff = nums[i] - nums[j]; dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1); longest = Math.max(longest, dp[i].get(diff)); } } return longest; } }
class Solution { public: int longestArithSeqLength(vector<int>& nums) { int n=size(nums); int ans=1; vector<vector<int>> dp(n,vector<int>(1005,1)); for(int i=1;i<n;i++) for(int j=0;j<i;j++) ans=max(ans, dp[i][nums[i]-nums[j]+500]= 1+dp[j][nums[i]-nums[j] +500]); return ans; } };
var longestArithSeqLength = function(nums) { if (nums === null || nums.length === 0) { return 0; } let diffMap = new Array(nums.length).fill(0).map(() => new Map()); let maxLen = 1; for (let i = 0; i < nums.length; i++) { for (let j = 0; j < i; j++) { let diff = nums[i] - nums[j]; // if prev element has an ongoing arithmetic sequence with the same common difference // we simply add 1 to the length of that ongoing sequence, hence diffMap[j].get(diff) + 1 // else, we start a new arithmetic sequence, initial length is 2 diffMap[i].set(diff, diffMap[j].get(diff) + 1 || 2); maxLen = Math.max(maxLen, diffMap[i].get(diff)); } } return maxLen; // T.C: O(N^2) // S.C: O(N^2) };
Longest Arithmetic Subsequence
An integer interval [a, b] (for integers a &lt; b) is a set of all consecutive integers from a to b, including a and b. Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two. &nbsp; Example 1: Input: intervals = [[1,3],[1,4],[2,5],[3,5]] Output: 3 Explanation: Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval. Also, there isn't a smaller size set that fulfills the above condition. Thus, we output the size of this set, which is 3. Example 2: Input: intervals = [[1,2],[2,3],[2,4],[4,5]] Output: 5 Explanation: An example of a minimum sized set is {1, 2, 3, 4, 5}. &nbsp; Constraints: 1 &lt;= intervals.length &lt;= 3000 intervals[i].length == 2 0 &lt;= ai &lt;&nbsp;bi &lt;= 108
class Solution: def intersectionSizeTwo(self, intervals: List[List[int]]) -> int: ans = [] for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): if not ans or ans[-2] < x: if ans and x <= ans[-1]: ans.append(y) else: ans.extend([y-1, y]) return len(ans)
//Time Complexity O(Nlog(N)) - N is the number of intervals //Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed class Solution { public int intersectionSizeTwo(int[][] intervals) { //corner case: can intervals be null or empty? No //First, sort the intervals by end, then by reverse order start Arrays.sort(intervals, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { if (a[1] == b[1]) { return b[0] - a[0]; } return a[1] - b[1]; } }); //Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request List<Integer> list = new ArrayList<>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition //add last two nums within the range list.add(intervals[0][1] - 1); list.add(intervals[0][1]); for (int i = 1; i < intervals.length; i++) { int lastOne = list.get(list.size() - 1); int lastTwo = list.get(list.size() - 2); int[] interval = intervals[i]; int start = interval[0]; int end = interval[1]; //if overlaps at least 2 if (lastOne >= start && lastTwo >= start) { continue; } else if (lastOne >= start) { //if overlaps 1 list.add(end); } else { //if not overlapping list.add(end - 1); list.add(end); } } return list.size(); } }
class Solution { public: // sort wrt. end value static bool compare(vector<int>& a, vector<int>& b) { if(a[1] == b[1]) return a[0] < b[0]; else return a[1] < b[1]; } int intersectionSizeTwo(vector<vector<int>>& intervals) { int n = intervals.size(); // sort the array sort(intervals.begin(), intervals.end(), compare); vector<int> res; res.push_back(intervals[0][1] - 1); res.push_back(intervals[0][1]); for(int i = 1; i < n; i++) { int start = intervals[i][0]; int end = intervals[i][1]; if(start > res.back()) { res.push_back(end - 1); res.push_back(end); } else if(start == res.back()) { res.push_back(end); } else if(start > res[res.size() - 2]) { res.push_back(end); } } return res.size(); } };
/** * @param {number[][]} intervals * @return {number} */ var intersectionSizeTwo = function(intervals) { const sortedIntervals = intervals.sort(sortEndsThenStarts) let currentTail = [] let answer = 0 sortedIntervals.forEach(interval => { const start = interval[0] const end = interval[1] const startPoint = currentTail[0] const lastPoint = currentTail[1] if (!currentTail.length || lastPoint < start){ currentTail = [end -1, end] answer += 2 } else if ( startPoint < start){ currentTail = [currentTail[1], end] answer += 1 } }) return answer }; function sortEndsThenStarts(intervalA, intervalB){ return intervalA[1] < intervalB[1] ? -1 : 1 }
Set Intersection Size At Least Two
Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child. &nbsp; Example 1: Input: root = [1,2,3] Output: 1 Explanation: Tilt of node 2 : |0-0| = 0 (no children) Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3) Sum of every tilt : 0 + 0 + 1 = 1 Example 2: Input: root = [4,2,9,3,5,null,7] Output: 15 Explanation: Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 5 : |0-0| = 0 (no children) Tilt of node 7 : |0-0| = 0 (no children) Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5) Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7) Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16) Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 Example 3: Input: root = [21,7,14,1,1,2,2,3,3] Output: 9 &nbsp; Constraints: The number of nodes in the tree is in the range [0, 104]. -1000 &lt;= Node.val &lt;= 1000
# 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 findTilt(self, root: Optional[TreeNode]) -> int: res = [0] def tilt_helper(root,res): if not root: return 0 left = tilt_helper(root.left,res) right = tilt_helper(root.right,res) res[0] += abs(left-right) return left + right + root.val tilt_helper(root,res) return res[0]
class Solution { int max = 0; public int findTilt(TreeNode root) { loop(root); return max; } public int loop(TreeNode root){ if(root==null) return 0; int left = loop(root.left); int right = loop(root.right); max+= Math.abs(left-right); return root.val+left+right; } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: /* We will take help of recursion Each function call will return the sum of subtree with root as current root and the tilt sum will be updated in the variable passed as reference */ int getTiltSum(TreeNode* root, int &tiltSum){ if(root == NULL){ return 0; } if(root->left == NULL and root->right == NULL){ // If we have a leaf tiltSum+=0; // Add nothing to tilt sum return root->val; // return its value as sum } int leftSubTreeSum = getTiltSum(root->left, tiltSum); // Sum of all nodes in left int rightSubTreeSum = getTiltSum(root->right, tiltSum); // and right subtrees tiltSum += abs(leftSubTreeSum - rightSubTreeSum); // Update the tilt sum // return the sum of left Subtree + right subtree + current node as the sum of the return (root->val + leftSubTreeSum + rightSubTreeSum); // subtree with root as current node. } int findTilt(TreeNode* root) { // variable to be passed as refrence and store the result int tiltSum = 0; getTiltSum(root, tiltSum); return tiltSum; } };
var findTilt = function(root) { function helper(node, acc) { if (node === null) { return 0; } const left = helper(node.left, acc); const right = helper(node.right, acc); acc.sum += Math.abs(left - right); return left + node.val + right; } let acc = { sum: 0 }; helper(root, acc); return acc.sum; };
Binary Tree Tilt
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0). &nbsp; Example 1: Input: grid = [[0,2],[1,3]] Output: 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. Example 2: Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] Output: 16 Explanation: The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. &nbsp; Constraints: n == grid.length n == grid[i].length 1 &lt;= n &lt;= 50 0 &lt;= grid[i][j] &lt;&nbsp;n2 Each value grid[i][j] is unique.
class DSU(object): def __init__(self, N): self.par = list(range(N)) self.rnk = [0] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return False elif self.rnk[xr] < self.rnk[yr]: self.par[xr] = yr elif self.rnk[xr] > self.rnk[yr]: self.par[yr] = xr else: self.par[yr] = xr self.rnk[xr] += 1 return True class Solution: def swimInWater(self, grid): d, N = {}, len(grid) for i,j in product(range(N), range(N)): d[grid[i][j]] = (i, j) dsu = DSU(N*N) grid = [[0] * N for _ in range(N)] neib_list = [[0,1],[0,-1],[1,0],[-1,0]] for i in range(N*N): x, y = d[i] grid[x][y] = 1 for dx, dy in neib_list: if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1: dsu.union((x+dx)*N + y + dy, x*N + y) if dsu.find(0) == dsu.find(N*N-1): return i
class Solution { public int swimInWater(int[][] grid) { int len = grid.length; Map<Integer, int[]> reverseMap = new HashMap<>(); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { reverseMap.put(grid[i][j], new int[] { i, j }); } } int left = grid[0][0]; // answer cannot be less than value of starting position int right = len * len - 1; int ans = right; while (left <= right) { int mid = left + (right - left) / 2; if (canSwim(grid, reverseMap, mid, len)) { ans = mid; right = mid - 1; } else { left = mid + 1; } } return ans; } boolean canSwim(int[][] grid, Map<Integer, int[]> reverseIndex, int ans, int len) { int[] x_diff = { 1, -1, 0, 0 }; int[] y_diff = { 0, 0, 1, -1 }; // BFS Queue<int[]> container = new LinkedList<>(); container.add(new int[] { 0, 0 }); boolean[][] visited = new boolean[grid.length][grid[0].length]; visited[0][0] = true; while (!container.isEmpty()) { int[] curr = container.poll(); int currVal = grid[curr[0]][curr[1]]; for (int i = 0; i < 4; i++) { int newX = curr[0] + x_diff[i]; int newY = curr[1] + y_diff[i]; if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) { if (newX == grid.length-1 && newY == grid[0].length-1) { return true; } visited[newX][newY] = true; container.add(new int[] { newX, newY }); } } } return false; } boolean isValidCell(int[][] grid, int x, int y, int ans) { // check boundary and if grid elevation is greater than evaluated answer return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans); } }
class Solution { public: int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; bool valid(int x,int y,int n) { return ((x>=0&&x<n)&&(y>=0&&y<n)); } int swimInWater(vector<vector<int>>& grid) { int n=grid.size(); int time[n][n]; bool vis[n][n]; for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { time[i][j]=1e9; vis[i][j]=false; } } time[0][0]=grid[0][0]; priority_queue<tuple<int,int,int>> q; q.push({-time[0][0],0,0}); while(!q.empty()) { tuple<int,int,int> node=q.top(); q.pop(); int x=get<1>(node),y=get<2>(node); if(vis[x][y])continue; vis[x][y]=true; for(int i=0;i<4;++i) { int xc=x+dir[i][0],yc=y+dir[i][1]; if(!valid(xc,yc,n))continue; if(time[x][y]<grid[xc][yc]) { time[xc][yc]=grid[xc][yc]; q.push({-time[xc][yc],xc,yc}); } else { if(time[xc][yc]>time[x][y]) { time[xc][yc]=time[x][y]; q.push({-time[xc][yc],xc,yc}); } } } } return time[n-1][n-1]; } }; // Time: O(N*N+N*NLOG(N*N)) // Space: O(N*N)
const moves = [[1,0],[0,1],[-1,0],[0,-1]] var swimInWater = function(grid) { let pq = new MinPriorityQueue(), N = grid.length - 1, ans = grid[0][0], i = 0, j = 0 while (i < N || j < N) { for (let [a,b] of moves) { let ia = i + a, jb = j + b if (ia < 0 || ia > N || jb < 0 || jb > N || grid[ia][jb] > 2500) continue pq.enqueue((grid[ia][jb] << 12) + (ia << 6) + jb) grid[ia][jb] = 3000 } let next = pq.dequeue().element ans = Math.max(ans, next >> 12) i = (next >> 6) & ((1 << 6) - 1) j = next & ((1 << 6) - 1) } return ans };
Swim in Rising Water
We define the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string p, return the number of unique non-empty substrings of p are present in s. &nbsp; Example 1: Input: p = "a" Output: 1 Explanation: Only the substring "a" of p is in s. Example 2: Input: p = "cac" Output: 2 Explanation: There are two substrings ("a", "c") of p in s. Example 3: Input: p = "zab" Output: 6 Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of p in s. &nbsp; Constraints: 1 &lt;= p.length &lt;= 105 p consists of lowercase English letters.
def get_next(char): x = ord(char)-ord('a') x = (x+1)%26 return chr(ord('a') + x) class Solution: def findSubstringInWraproundString(self, p: str) -> int: i = 0 n = len(p) map_ = collections.defaultdict(int) while i<n: start = i prev_val = p[i] while i+1<n and get_next(prev_val) == p[i+1]: prev_val = p[i+1] i+=1 while start <= i: curr_val = i-start+1 map_[p[start]] = max(map_[p[start]], curr_val) start += 1 i+=1 return sum(map_.values())
// One Pass Counting Solution // 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring. // 2. counts to track the longest continuos subtring starting with current character. // Time complexity: O(N) // Space complexity: O(1) class Solution { public int findSubstringInWraproundString(String p) { final int N = p.length(); int res = 0, len = 1; int[] counts = new int[26]; for (int i = 0; i < N; i++) { char ch = p.charAt(i); if (i > 0 && (ch - p.charAt(i-1) == 1 || ch - p.charAt(i-1) == -25)) { len++; } else { len = 1; } int idx = ch - 'a'; counts[idx] = Math.max(counts[idx], len); } for (int count : counts) { res += count; } return res; } }
class Solution { public: int findSubstringInWraproundString(string p) { unordered_map<char, int> mp; // if the characters are not contiguous and also check whether after 'z' I am getting 'a'. If so, reset the streak to 1 // else streak++ int streak = 0; for (int i = 0; i < p.size(); i++) { // contiguous if (i and (p[i] - p[i - 1] == 1)) streak++; // z...a case else if (i and (p[i] == 'a' and p[i - 1] == 'z')) streak++; else streak = 1; mp[p[i]] = max(mp[p[i]], streak); } // why sum? cuz there might be multiple substrings when the streak's broken for one int ans = 0; for (auto x : mp) { ans += x.second; } return ans; } };
var findSubstringInWraproundString = function(p) { const dp = Array(26).fill(0); const origin = 'a'.charCodeAt(0); let count = 0; for (let index = 0; index < p.length; index++) { const code = p.charCodeAt(index); const preCode = p.charCodeAt(index - 1); const pos = code - origin; count = code - preCode === 1 || preCode - code === 25 ? count + 1 : 1; dp[pos] = Math.max(count, dp[pos]); } return dp.reduce((total, count) => total + count); };
Unique Substrings in Wraparound String
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity. &nbsp; Example 1: Input ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] Output [null, null, null, 1, null, -1, null, -1, 3, 4] Explanation LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 &nbsp; Constraints: 1 &lt;= capacity &lt;= 3000 0 &lt;= key &lt;= 104 0 &lt;= value &lt;= 105 At most 2 * 105 calls will be made to get and put.
class LRUCache { int N; list<int> pages; unordered_map<int, pair<int, list<int>::iterator>> cache; public: LRUCache(int capacity) : N(capacity) { } int get(int key) { if (cache.find(key) != cache.end()) { pages.erase(cache[key].second); pages.push_front(key); cache[key].second = pages.begin(); return cache[key].first; } return -1; } void put(int key, int value) { if (cache.find(key) != cache.end()) { pages.erase(cache[key].second); } else { if (pages.size() == N) { int lru = pages.back(); cache.erase(lru); pages.pop_back(); } } pages.push_front(key); cache[key] = {value, pages.begin()}; } };
class LRUCache { // Declare Node class for Doubly Linked List class Node{ int key,value;// to store key and value Node next,prev; // Next and Previous Pointers Node(int k, int v){ key=k; value=v; } } Node head=new Node(-1,-1); // Default values Node tail=new Node(-1,-1); Map<Integer,Node>mp; // to store key and Node int cap; public LRUCache(int capacity) { // initializing in constructor cap=capacity; head.next=tail; tail.prev=head; mp=new HashMap<Integer,Node>(); } public int get(int key) { // if map contains the specific key if(mp.containsKey(key)){ Node existing=mp.get(key); del(existing); ins(existing);// reinserting to keep key after the head pointer and to update LRU list return existing.value; } //otherwise return -1; } public void put(int key, int value) { // if map contains the key if(mp.containsKey(key)){ Node existing=mp.get(key); // remove from the map and delete from the LRU list mp.remove(key); del(existing); } // if map size is equal to spcified capacity of the LRU list if(mp.size()==cap){ // remove from the map and delete from the LRU list mp.remove(tail.prev.key); del(tail.prev); } Node newNode = new Node(key,value); ins(newNode); mp.put(key,head.next); } public void ins(Node newNode){ //Insert always after the head of the linkedList Node temp=head.next; head.next=newNode; newNode.prev=head; newNode.next=temp; temp.prev=newNode; } public void del(Node newNode){ //Remove the specified node using previous and next pointers Node pr=newNode.prev; Node nx=newNode.next; pr.next=nx; nx.prev=pr; } }
class LRUCache { public: int mx; class node{ public: node *prev,*next; int key,val; node(int k,int v){ key=k,val=v; } }; unordered_map<int,node*> mp; node *head=new node(-1,-1); node *tail=new node(-1,-1); LRUCache(int capacity) { mx=capacity; mp.reserve(1024); mp.max_load_factor(0.25); head->next=tail;tail->prev=head; } void addnode(node *temp){ node *temp1=head->next; head->next=temp;temp->prev=head; temp->next=temp1;temp1->prev=temp; } void deletenode(node *temp){ node *temp1=temp->prev; node *temp2=temp->next; temp1->next=temp2; temp2->prev=temp1; } int get(int key) { if(mp.find(key)!=mp.end()){ node *temp=mp[key]; int res=temp->val; mp.erase(key); deletenode(temp); addnode(temp); mp[key]=head->next; return res; } return -1; } void put(int key, int value) { if(mp.find(key)!=mp.end()){ node *temp=mp[key]; mp.erase(key); deletenode(temp); } if(mp.size()==mx){ mp.erase(tail->prev->key); deletenode(tail->prev); } addnode(new node(key,value)); mp[key]=head->next; } };
/** * @param {number} capacity */ var LRUCache = function(capacity) { this.capacity = capacity; this.cache = new Map(); }; /** * @param {number} key * @return {number} */ LRUCache.prototype.get = function(key) { if(!this.cache.has(key)){ return -1 } let val = this.cache.get(key); this.cache.delete(key); this.cache.set(key, val) return val }; /** * @param {number} key * @param {number} value * @return {void} */ LRUCache.prototype.put = function(key, value) { if(this.cache.has(key)){ this.cache.delete(key); }else{ if(this.cache.size >= this.capacity){ let [lastElm] = this.cache.keys() this.cache.delete(lastElm) } } this.cache.set(key, value) }; /** * Your LRUCache object will be instantiated and called as such: * var obj = new LRUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) */
LRU Cache
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return an empty string. &nbsp; Example 1: Input: arr = [1,2,3,4] Output: "23:41" Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest. Example 2: Input: arr = [5,5,5,5] Output: "" Explanation: There are no valid 24-hour times as "55:55" is not valid. &nbsp; Constraints: arr.length == 4 0 &lt;= arr[i] &lt;= 9
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: res = "" digit_freq = collections.Counter(arr) # first digit if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2: res += "2" arr.remove(2) else: for digit in [1,0]: if digit in arr: res += str(digit) arr.remove(digit) break # can't make 24-hour time if len(res) == 0: return "" # second digit 0-3 if res == "2": for digit in [3,2,1,0]: if digit in arr: res += str(digit) arr.remove(digit) break # no 0-3 left in arr if len(res) == 1: return "" # second digit 0-9 else: for digit in range(9,-1,-1): if digit in arr: res += str(digit) arr.remove(digit) break res += ":" for digit in range(5, -1, -1): if digit in arr: res += str(digit) arr.remove(digit) break if len(res) == 3: return "" for digit in range(9,-1,-1): if digit in arr: res += str(digit) return res
class Solution { public String largestTimeFromDigits(int[] arr) { int[] count = new int[10]; for (int num: arr) { count[num]++; } StringBuilder sb = backTrack(count, new StringBuilder()); if (sb.length() == 4) sb.insert(2, ':'); return sb.toString(); } private StringBuilder backTrack(int[] count, StringBuilder sb) { int size = sb.length(); int start = 0; if (size == 0) { start = 2; } if (size == 1) { start = sb.charAt(0) == '2' ? 3 : 9; } if (size == 2) { start = 5; } if (size == 3) { start = 9; } for (int i = start; i >= 0; i--) { if (count[i] == 0) continue; count[i]--; sb.append(i); backTrack(count, sb); if (sb.length() == 4) { return sb; } else { count[Character.getNumericValue(sb.charAt(sb.length() - 1))]++; sb.deleteCharAt(sb.length() - 1); } } return sb; } }
class Solution { public: string largestTimeFromDigits(vector<int>& arr) { sort(arr.rbegin(), arr.rend()); used.resize(4); string ret = ""; if(!dfs(arr,0,0)) return ret; else { for(int i=0;i<2;i++) ret.push_back(ans[i] + '0'); ret.push_back(':'); for(int i=2;i<4;i++) ret.push_back(ans[i] + '0'); } return ret; } private: vector<int> min = {600, 60, 10, 1}; vector<int> ans; vector<int> used; bool dfs(const vector<int>& arr, int totalhour,int totalmin) { if(totalhour >= 24 * 60) return false; if(totalmin >= 60) return false; if(ans.size() == 4) return true; for(int i=0;i<4;i++) { if(used[i]) continue; used[i] = 1; int pos = ans.size(); if(pos<2) totalhour += arr[i] * min[pos]; else totalmin += arr[i] * min[pos]; ans.push_back(arr[i]); if(dfs(arr,totalhour,totalmin)) return true; if(pos<2) totalhour -= arr[i] * min[pos]; else totalmin -= arr[i] * min[pos]; ans.pop_back(); used[i] = 0; } return false; } };
var largestTimeFromDigits = function(arr) { let max=-1; for(let A=0; A<4; A++){ for(let B=0; B<4; B++){ if(B==A){continue}; for(let C=0; C<4; C++){ if(C==A||C==B||arr[C]>=6){continue}; for(let D=0; D<4; D++){ if(D==A||D==B||D==C){continue}; let time=arr[A]*1000+arr[B]*100+arr[C]*10+arr[D]; if(time<2400){max=Math.max(max, time)); } } } } // Case1: max<0, which means NOTHING VALID -> return "" // Case2: max isn't 4 digits. i.e.[0,0,0,0] -> padStart to make "0000" let output=max.toString().padStart(4,0); return max<0? "": output.substr(0,2)+":"+output.substr(2); };
Largest Time for Given Digits
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. &nbsp; Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] &nbsp; Constraints: 1 &lt;= strs.length &lt;= 104 0 &lt;= strs[i].length &lt;= 100 strs[i] consists of lowercase English letters.
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: strs_table = {} for string in strs: sorted_string = ''.join(sorted(string)) if sorted_string not in strs_table: strs_table[sorted_string] = [] strs_table[sorted_string].append(string) return list(strs_table.values())
class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap<String,ArrayList<String>> hm=new HashMap<>(); for(String s : strs) { char ch[]=s.toCharArray(); Arrays.sort(ch); StringBuilder sb=new StringBuilder(""); for(char c: ch) { sb.append(c); } String str=sb.toString(); if(hm.containsKey(str)) { ArrayList<String> temp=hm.get(str); temp.add(s); hm.put(str,temp); } else { ArrayList<String> temp=new ArrayList<>(); temp.add(s); hm.put(str,temp); } } System.out.println(hm); List<List<String>> res=new ArrayList<>(); for(ArrayList<String> arr : hm.values()) { res.add(arr); } return res; } }
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { map<string,vector<int>> mp; for(int i=0;i<strs.size();i++) { string t=strs[i]; sort(t.begin(),t.end()); mp[t].push_back(i); } vector<vector<string>> ans; for(auto it:mp) { vector<string> flag; for(auto each:it.second) { flag.push_back(strs[each]); } ans.push_back(flag); } return ans; } };
var groupAnagrams = function(strs) { let totalResults = []; let grouped = new Map(); for (let i=0; i < strs.length; i++) { let results = []; let res = strs[i]; let sortedStr = strs[i].split('').sort().join(''); let value = grouped.get(sortedStr); if (value !== undefined) { grouped.set(sortedStr, [...value, strs[i]]); } else { grouped.set(sortedStr, [strs[i]]); } } for (let [key, value] of grouped) { totalResults.push(grouped.get(key)); } return totalResults; };
Group Anagrams