algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: Jumbo Burger: 4 tomato slices and 1 cheese slice. Small Burger: 2 Tomato slices and 1 cheese slice. Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].   Example 1: Input: tomatoSlices = 16, cheeseSlices = 7 Output: [1,6] Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. There will be no remaining ingredients. Example 2: Input: tomatoSlices = 17, cheeseSlices = 4 Output: [] Explantion: There will be no way to use all ingredients to make small and jumbo burgers. Example 3: Input: tomatoSlices = 4, cheeseSlices = 17 Output: [] Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.   Constraints: 0 <= tomatoSlices, cheeseSlices <= 107
class Solution(object): def numOfBurgers(self, t, c): if t==c==0: return [0,0] four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c two=c-four #number of small burgers if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list return [] return [four,two]
class Solution { public List<Integer> numOfBurgers(int tomatoSlices, int cheeseSlices) { List<Integer>list=new ArrayList<>(); int ts=tomatoSlices; int cs=cheeseSlices; if (ts<cs*2 || ts>cs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0)) { return list; } int cnt=0; while(ts>0 && cs>0 && ts!=cs*2) { ts-=4; cnt++; cs--; } list.add(cnt); list.add(cs); return list; } }
class Solution { public: vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) { // Observation // Total Number of Burgers is Equal to Number of cheeseSlices // Try to make 1 --> cheeseSlices Amount of Jumbo Burgers and // remaining will be Small Burger vector <int> ans; if(tomatoSlices == 0 and cheeseSlices == 0) { ans.push_back(0), ans.push_back(0); return ans; } // Do Binary Search to Get Ideal Division. int low = 0, high = cheeseSlices; while(low < high) { int mid = (low + high) / 2; int jumbo = mid, small = cheeseSlices - mid; // Jumbo needs 4 tomatoes per burger // Small needs 2 tomatoes per burger int needJumboTom = jumbo * 4; int needSmallTom = small * 2; // Should Add Upto tomatoSlices if(needJumboTom + needSmallTom == tomatoSlices) { ans.push_back(jumbo), ans.push_back(small); break; } else if(needJumboTom + needSmallTom < tomatoSlices) { low = mid + 1; } else { high = mid; } } return ans; } };
/** * @param {number} tomatoSlices * @param {number} cheeseSlices * @return {number[]} */ var numOfBurgers = function(tomatoSlices, cheeseSlices) { if (tomatoSlices & 1) return []; // return [] if tomatoSlices is odd const j = (tomatoSlices >> 1) - cheeseSlices; // jumbo = (tomatoSlices / 2) - cheeseSlices return j < 0 || j > cheeseSlices ? [] : [j, cheeseSlices - j]; // small = cheeseSlices - jumbo, if any of jmbo and small < 0 return [] otherwise return [jumbo, small] };
Number of Burgers with No Waste of Ingredients
Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). &nbsp; Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]] &nbsp; Constraints: The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] result = [] level = [root] while level: current_level = [] next_level = [] for node in level: current_level.append(node.val) next_level += node.children result.append(current_level) level = next_level return result
class Solution { public List<List<Integer>> result= new ArrayList(); public List<List<Integer>> levelOrder(Node root) { if(root==null) return result; helper(root,0); return result; } private void helper(Node node,int level){ if(result.size()<=level){ result.add(new ArrayList()); } result.get(level).add(node.val); for(Node child:node.children){ helper(child,level+1); } } }
class Solution { public: vector<vector<int>> ans; vector<vector<int>> levelOrder(Node* root) { dfs(root, 0); return ans; } void dfs(Node* root, int level) { if(!root) { return; } if(level == ans.size()) { ans.push_back({}); } ans[level].push_back(root->val); for(auto i : root->children) { dfs(i, level+1); } } };
var levelOrder = function(root) { if(!root) return []; const Q = [[root, 0]]; const op = []; while(Q.length) { const [node, level] = Q.shift(); if(op.length <= level) { op[level] = []; } op[level].push(node.val); for(const child of node.children) { Q.push([child, level + 1]); } } return op; };
N-ary Tree Level Order Traversal
There is an exam room with n seats in a single row labeled from 0 to n - 1. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0. Design a class that simulates the mentioned exam room. Implement the ExamRoom class: ExamRoom(int n) Initializes the object of the exam room with the number of the seats n. int seat() Returns the label of the seat at which the next student will set. void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p. &nbsp; Example 1: Input ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] [[10], [], [], [], [], [4], []] Output [null, 0, 9, 4, 2, null, 5] Explanation ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. &nbsp; Constraints: 1 &lt;= n &lt;= 109 It is guaranteed that there is a student sitting at seat p. At most 104 calls will be made to seat and leave.
class ExamRoom: def __init__(self, n: int): self.N = n self.pq = [] self.dict = {} self.addSegment(0, self.N - 1) def seat(self) -> int: start, end, distance = heapq.heappop(self.pq) self.dict.pop(start, None) #Remove old segment from dictionary self.dict.pop(end, None) if start == end: position = start elif start == 0: position = start right = self.addSegment(start + 1, end) elif end == self.N - 1: position = end left = self.addSegment(start, end - 1) elif end - start == 1: #ONLY ONE PLACE TO PUT position = start left = self.addSegment(start + 1, end) else: position = start + (end - start) // 2 right = self.addSegment(start, position - 1) left = self.addSegment(position + 1, end) return position def leave(self, p: int) -> None: left = self.dict.get(p - 1, None) right = self.dict.get(p + 1, None) new_start = new_end = p if left: self.removeSegment(left) new_start = left.start if right: self.removeSegment(right) new_end = right.end self.addSegment(new_start, new_end) def addSegment(self, start, end): segment = Segment(start, end, self.N) self.dict[segment.start] = segment self.dict[segment.end] = segment heapq.heappush(self.pq, segment) def removeSegment(self, segment): self.dict.pop(segment.start, None) self.dict.pop(segment.end, None) self.pq.remove(segment) class Segment(): def __init__(self, start, end, N): self.start = start self.end = end self.distance = self.calculateDistance(start, end, N) def __lt__(self, other_segment): return self.distance > other_segment.distance if self.distance != other_segment.distance else self.start < other_segment.start def calculateDistance(self, start, end, N): if start == 0: return end if end == N - 1: return end - start else: return (end - start) // 2 def __iter__(self): return iter((self.start, self.end, self.distance))
class ExamRoom { private final int max; private final TreeSet<Interval> available; private final TreeSet<Integer> taken; public ExamRoom(int n) { this.max = n - 1; this.available = new TreeSet<>((a, b) -> { var distA = getMinDistance(a); var distB = getMinDistance(b); return distA == distB ? a.s - b.s : distB - distA; }); this.available.add(new Interval(0, max)); this.taken = new TreeSet<>(); } public int seat() { var inter = available.pollFirst(); var idx = getInsertPosition(inter); taken.add(idx); if ((idx - 1) - inter.s >= 0) available.add(new Interval(inter.s, idx - 1)); if (inter.e - (idx + 1) >= 0) available.add(new Interval(idx + 1, inter.e)); return idx; } public void leave(int p) { taken.remove(p); var lo = taken.lower(p); if (lo == null) lo = -1; var hi = taken.higher(p); if (hi == null) hi = max + 1; available.remove(new Interval(lo + 1, p - 1)); available.remove(new Interval(p + 1, hi - 1)); available.add(new Interval(lo + 1, hi - 1)); } private int getInsertPosition(Interval inter) { if (inter.s == 0) return 0; else if (inter.e == max) return max; else return inter.s + (inter.e - inter.s) / 2; } private int getMinDistance(Interval in) { return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2; } private final class Interval { private final int s; private final int e; Interval(int s, int e) { this.s = s; this.e = e; } @Override public String toString() { return "[" + s + "," + e + "]"; } } }
class ExamRoom { public: set<int> s; // ordered set int num; ExamRoom(int n) { num=n; // total seats } int seat() { if(s.size()==0) { s.insert(0); return 0;} // if size is zero place at seat 0 auto itr = s.begin(); if(s.size()==1) { // if size==1 -> check if its closer to 0 or last seat (num-1) if(*itr > num-1-(*itr)){ s.insert(0); return 0; } else{ s.insert(num-1); return num-1;} } int mx=-1; // for max gap int l=0; // for left index of the student to max gap. if(s.find(0)==s.end()){mx = (*itr); l=-mx;} // if 0 is not seated -> check gap with 0 and starting seat. // Iterate the set to calculate gaps for(int i=0;i<s.size()-1;i++) { int a=*itr; // seat number for 1st element itr++; int b = *itr; // seat number of next element in the set // check the gap and update if(mx<(b-a)/2){ mx=(b-a)/2; l=a; } } if(s.find(num-1)==s.end()) { // if last seat is vacant -> check gap with last filled seat and (num-1) if(mx< num-1-(*itr)) { mx = (num-1-(*itr)); l=*itr; } } s.insert(l+mx); // place the student at l+mx return l+mx; } void leave(int p) { // remove student from set s.erase(p); } };
/** * @param {number} n */ var ExamRoom = function(n) { this.n = n this.list = [] }; /** * @return {number} */ ExamRoom.prototype.seat = function() { // if nothing in the list, seat the first student at index 0. if(this.list.length === 0){ this.list.push(0) return 0 } // find the largest distance between left wall and first student, and right wall and last student let distance = Math.max(this.list[0], this.n - 1 - this.list[this.list.length-1]) // update the largest distance by considering the distance between students for(let i=0; i<this.list.length-1; i++){ distance = Math.max(distance, Math.floor((this.list[i+1] - this.list[i]) / 2)) } // in case the largest distance is between left wall and first student, we seat next student at the left wall if(distance === this.list[0]){ this.list.unshift(0) return 0 } // in case the largest distance is between two student, we seat the next student in between these two students for(let i=0; i<this.list.length-1; i++){ if(distance === Math.floor( (this.list[i+1]-this.list[i])/2 )){ let insertIndex = Math.floor( (this.list[i+1]+this.list[i]) / 2 ) this.list.splice(i+1,0, insertIndex) return insertIndex } } // in case the largest distance is between the last student and the right wall, we seat the next student at the right wall this.list.push(this.n-1) return this.n - 1 }; /** * @param {number} p * @return {void} */ ExamRoom.prototype.leave = function(p) { // We iterate through the list and find the index where the student p sit at, then remove that index. for(let i=0; i<this.list.length; i++){ if(this.list[i] === p) { this.list.splice(i, 1) break } } }; /** * Your ExamRoom object will be instantiated and called as such: * var obj = new ExamRoom(n) * var param_1 = obj.seat() * obj.leave(p) */
Exam Room
Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: s = "aa" Output: 0 Explanation: The optimal substring here is an empty substring between the two 'a's. Example 2: Input: s = "abca" Output: 2 Explanation: The optimal substring here is "bc". Example 3: Input: s = "cbzxy" Output: -1 Explanation: There are no characters that appear twice in s. &nbsp; Constraints: 1 &lt;= s.length &lt;= 300 s contains only lowercase English letters.
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: last, ans = {}, -1 for i, c in enumerate(s): if c not in last: last[c] = i else: ans = max(ans, i - last[c] - 1) return ans
class Solution { public int maxLengthBetweenEqualCharacters(String s) { int ans = -1; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (map.containsKey(ch)) { ans = Math.max(ans, i - 1 - map.get(ch)); } else { map.put(ch, i); } } return ans; } }
class Solution { public: int maxLengthBetweenEqualCharacters(string s) { vector<int> v(26, -1); int maxi = -1; for (int i = 0; i < s.size(); i++) { if (v[s[i] - 'a'] == -1) v[s[i] - 'a'] = i; else maxi = max(maxi, abs(v[s[i] - 'a'] - i) - 1); } return maxi; } };
var maxLengthBetweenEqualCharacters = function(s) { const map = new Map(); let max=-1; for(let i=0;i<s.length;i++){ if(map.has(s[i])){ max=Math.max(max,i-(map.get(s[i])+1)) }else{ map.set(s[i],i) } } return max; };
Largest Substring Between Two Equal Characters
There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. &nbsp; Example 1: Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] Output: 4 Explanation: The diagram above shows the tree. We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node. Example 2: Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] Output: 3 Explanation: The diagram above shows the tree. We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node. &nbsp; Constraints: 2 &lt;= n &lt;= 105 edges.length == n - 1 edges[i].length == 2 0 &lt;= ai, bi &lt; n ai != bi edges represents a valid tree. 1 &lt;= restricted.length &lt; n 1 &lt;= restricted[i] &lt; n All the values of restricted are unique.
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: # ignore restricted node # bfs from 0 # O(E), EDITED: the time complexity here is wrong, plz see my comment adj_dict = collections.defaultdict(list) for u, v in edges: if u in restricted or v in restricted: # EDITED: not O(1) continue adj_dict[u].append(v) adj_dict[v].append(u) # O(V + E) queue = collections.deque([0]) visited = {0} while queue: cur = queue.popleft() for neighbor in adj_dict[cur]: if neighbor in visited: continue visited.add(neighbor) queue.append(neighbor) return len(visited)
class Solution { int count=0; ArrayList<ArrayList<Integer>> adj=new ArrayList<>(); public int reachableNodes(int n, int[][] edges, int[] restricted) { boolean[] vis=new boolean[n]; for(int i:restricted){ vis[i]=true; } for(int i=0;i<n;i++){ adj.add(new ArrayList<>()); } for(int[] ii:edges){ adj.get(ii[0]).add(ii[1]); adj.get(ii[1]).add(ii[0]); } dfs(0,vis); return count; } private void dfs(int node,boolean[] vis){ vis[node]=true; count++; for(int it:adj.get(node)){ if(vis[it]==false){ dfs(it,vis); } } } }
class Solution { public: int count=1; // node 0 is already reached as it is starting point vector<vector<int>> graph; unordered_set<int> res; // to store restricted numbers for fast fetch vector<bool> vis; // visited array for DFS void dfs(int i){ for(int y: graph[i]){ if(!vis[y] && res.count(y)==0){ vis[y]= true; dfs(y); count++; } } } int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) { for(int x:restricted) res.insert(x); // creating graph graph.resize(n); vis.resize(n); for(auto &x:edges){ graph[x[0]].push_back(x[1]); graph[x[1]].push_back(x[0]); } // mark 0 as visited coz it is starting point and is already reached vis[0]= true; dfs(0); return count; } };
/** * @param {number} n * @param {number[][]} edges * @param {number[]} restricted * @return {number} */ var reachableNodes = function(n, edges, restricted) { const adj = {}; for (const [u, v] of edges) { if (adj[u]) { adj[u].add(v); } else { adj[u] = new Set().add(v); } if (adj[v]) { adj[v].add(u); } else { adj[v] = new Set().add(u); } } const restrictedSet = new Set(restricted); const visited = new Set(); let ans = 0; function dfs(node) { if (restrictedSet.has(node) || visited.has(node)) { return; } ans++; visited.add(node); for (const adjNode of adj[node]) { dfs(adjNode); } } dfs(0); return ans; };
Reachable Nodes With Restrictions
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in&nbsp;O(log n) time. &nbsp; Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times. Example 2: Input: nums = [4,5,6,7,0,1,2] Output: 0 Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. Example 3: Input: nums = [11,13,15,17] Output: 11 Explanation: The original array was [11,13,15,17] and it was rotated 4 times. &nbsp; Constraints: n == nums.length 1 &lt;= n &lt;= 5000 -5000 &lt;= nums[i] &lt;= 5000 All the integers of nums are unique. nums is sorted and rotated between 1 and n times.
class Solution: def findMin(self, nums: List[int]) -> int: if len(nums) == 1 or nums[0] < nums[-1]: return nums[0] l, r = 0, len(nums) - 1 while l <= r: mid = l + (r - l) // 2 if mid > 0 and nums[mid - 1] > nums[mid]: return nums[mid] # We compare the middle number and the right index number # but why we cannot compare it with the left index number? if nums[mid] > nums[r]: l = mid + 1 else: r = mid - 1
class Solution { public int findMin(int[] nums) { int min=nums[0]; for(int i=0;i<nums.length;i++) { if(min>nums[i]) { min=nums[i]; } } return min; } }
class Solution { public: int findMin(vector<int>& nums) { int result = -1; int first = nums[0]; // check the array for rotated point when it is obtained break the loop and assign result as rotation point for(int i = 1; i<nums.size();i++){ if(nums[i-1]>nums[i]){ result = nums[i]; break; } } // if the array is not sorted return first element if(result == -1) { return first; } return result; } };
var findMin = function(nums) { let min = Math.min(...nums) return min; };
Find Minimum in Rotated Sorted Array
Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825. &nbsp; Example 1: Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. Example 2: Input: n = 11111111111111111111111111111101 Output: 3221225471 (10111111111111111111111111111111) Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111. &nbsp; Constraints: The input must be a binary string of length 32 &nbsp; Follow up: If this function is called many times, how would you optimize it?
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): res=0 for i in range(32): bit=(n>>i)&1 res=res|bit<<(31-i) return res
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int mask = 0; int smask = 0; int j = 0; int rev = 0; // basically we are checking that the number is set bit or not // if the number is set bit then we are appending that to our main answer i.e, rev for(int i=31 ; i>=0 ; i--){ mask = 1<<i; if((mask&n)!=0){ smask = 1<<j; rev = rev|smask; } j++; } // Time Complexity : O(32 for int) // Space Complexity : O(1) return rev; } }
class Solution { public: uint32_t reverseBits(uint32_t n) { int ans =0; int i =1; int bit =0; while(i<32){ bit = n&1; ans = ans|bit; n = n>>1; ans = ans<<1; i++; } if (i ==32){ bit = n&1; ans = ans|bit; } return ans; } };
/** * @param {number} n - a positive integer * @return {number} - a positive integer */ // remember the binary must always be of length 32 ;); var reverseBits = function(n) { const reversedBin = n.toString(2).split('').reverse().join(''); const result = reversedBin.padEnd(32,'0'); return parseInt(result, 2); };
Reverse Bits
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one&nbsp;edge of the graph that meets where they are.&nbsp; For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three&nbsp;ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and&nbsp;it is the same player's turn to move), the game is a draw. Given a graph, and assuming both players play optimally, return 1&nbsp;if the mouse wins the game, 2&nbsp;if the cat wins the game, or 0&nbsp;if the game is a draw. &nbsp; Example 1: Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] Output: 0 Example 2: Input: graph = [[1,3],[0],[3],[0,2]] Output: 1 &nbsp; Constraints: 3 &lt;= graph.length &lt;= 50 1&nbsp;&lt;= graph[i].length &lt; graph.length 0 &lt;= graph[i][j] &lt; graph.length graph[i][j] != i graph[i] is unique. The mouse and the cat can always move.&nbsp;
class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: def getPreStates(m,c,t): ans = [] if t == 1: for c2 in graph[c]: if c2 == 0:continue ans.append((m,c2,2)) else: for m2 in graph[m]: ans.append((m2,c,1)) return ans def ifAllNextMovesFailed(m,c,t): if t == 1: for m2 in graph[m]: if result[(m2,c,2)] != 2:return False else: for c2 in graph[c]: if c2 == 0:continue if result[(m,c2,1)] != 1:return False return True result = defaultdict(lambda:0) # key = (m,c,turn) value = (0/1/2) n = len(graph) queue = deque() for t in range(1,3): for i in range(1,n): # mouse win result[(0,i,t)] = 1 queue.append((0,i,t)) # cat win result[(i,i,t)] = 2 queue.append((i,i,t)) while queue: m,c,t = queue.popleft() r = result[(m,c,t)] for m2,c2,t2 in getPreStates(m,c,t): r2 = result[(m2,c2,t2)] if r2 > 0:continue # populate prestate if r == 3-t: # can always win result[(m2,c2,t2)] = r queue.append((m2,c2,t2)) elif ifAllNextMovesFailed(m2,c2,t2): result[(m2,c2,t2)] =3-t2 queue.append((m2,c2,t2)) return result[(1,2,1)]
class Solution { int TIME_MAX = 200; int DRAW = 0; int MOUSE_WIN = 1; int CAT_WIN = 2; public int catMouseGame(int[][] graph) { return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]); } private int dfs(int time, int[] p, int[][] graph, Integer[][][] memo){ // p[0] -> mouse position, p[1] -> cat position Integer old = memo[time][p[0]][p[1]]; if (old != null) return old; // all the base cases here if (time >= TIME_MAX) return DRAW; if (p[0]==0) return MOUSE_WIN; if (p[0]==p[1]) return CAT_WIN; int state = 0; int where = p[time&1]; int res = DRAW; for (int i = 0; i < graph[where].length; i++){ if ((time&1)==0||graph[where][i]>0){ // if mouse turn or cat turn and the dest is not 0, do ... p[time&1]=graph[where][i]; state |= 1 << dfs(time+1, p, graph, memo); if ((time&1)>0&&(state&4)>0 || (time&1)==0&&(state&2)>0) // if mouse's turn & mouse win break; // or cat's turn & cat win, then we stop. } } p[time&1]=where; // restore p if (((time&1)>0 && (state & 4)>0)||((time&1)==0) && state==4){ res = CAT_WIN; // cat win when (cat's turn & cat win) or (mouse's turn and state = cat) }else if (((time&1)==0 && (state & 2)>0)||(time&1)==1 && state==2){ res = MOUSE_WIN; // mouse win when (mouse's turn and mouse win) or (cat's turn and state = mouse) } return memo[time][p[0]][p[1]]=res; } }
class Solution { public: int catMouseGame(vector<vector<int>>& graph) { int N = graph.size(); vector<vector<int>> dp[2]; vector<vector<int>> outdegree[2]; queue<vector<int>> q; // q of {turn, mouse position, cat position} for topological sort dp[0] = vector<vector<int>>(N, vector<int>(N)); dp[1] = vector<vector<int>>(N, vector<int>(N)); outdegree[0] = vector<vector<int>>(N, vector<int>(N)); outdegree[1] = vector<vector<int>>(N, vector<int>(N)); // init dp and queue for (int j = 0; j < N; ++j) { dp[0][0][j] = dp[1][0][j] = 1; q.push({0, 0, j}); q.push({1, 0, j}); } for (int j = 1; j < N; ++j) { dp[0][j][j] = dp[1][j][j] = 2; q.push({0, j, j}); q.push({1, j, j}); } // init outdegree for (int i = 0; i < N; ++i) { for (int j = 1; j < N; ++j) { outdegree[0][i][j] = graph[i].size(); outdegree[1][i][j] = graph[j].size(); } } for (auto &v : graph[0]) { for (int i = 0; i < N; ++i) { outdegree[1][i][v]--; } } // run the topological sort from queue while (q.size()) { auto turn = q.front()[0]; auto mouse = q.front()[1]; auto cat = q.front()[2]; q.pop(); if (turn == 0 && mouse == 1 && cat == 2) { // the result has been inferenced break; } if (turn == 0) { // mouse's turn // v is the prev position of cat for (auto &v : graph[cat]) { if (v == 0) { continue; } if (dp[1][mouse][v] > 0) { continue; } if (dp[turn][mouse][cat] == 2) { // cat wants to move from v to `cat` position, and thus cat wins dp[1][mouse][v] = 2; q.push({1, mouse, v}); continue; } outdegree[1][mouse][v]--; if (outdegree[1][mouse][v] == 0) { dp[1][mouse][v] = 1; q.push({1, mouse, v}); } } } else { // cat's turn // v is the prev position of mouse for (auto &v : graph[mouse]) { if (dp[0][v][cat] > 0) { continue; } if (dp[turn][mouse][cat] == 1) { // mouse wants to move from v to `mouse` position and thus mouse wins dp[0][v][cat] = 1; q.push({0, v, cat}); continue; } outdegree[0][v][cat]--; if (outdegree[0][v][cat] == 0) { dp[0][v][cat] = 2; q.push({0, v, cat}); } } } } return dp[0][1][2]; } };
var catMouseGame = function(graph) { let n=graph.length, memo=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2*n+1)])), seen=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2)])) //dfs returns 0 1 2, whether the current player loses,wins, or draws respectively let dfs=(M,C,level)=>{ let turn=level%2,curr=turn?C:M,draw=0,res=0 //draw when we ve seen the state before or cycles if(seen[M][C][turn]!==undefined||level>=2*n) return memo[M][C][level]=2 if(M==0)// win for mouse if it reaches the hole, loss for cat memo[M][C][level]=turn^1 if(M==C)// win for cat if it reaches the mouse, loss for mouse memo[M][C][level]=turn if(memo[M][C][level]===undefined){ seen[M][C][turn]=0 //set this state as visited for(let i=0;i<graph[curr].length&&!res;i++) //traverse for the available edges if( !(turn&&(!graph[curr][i]))){ //The cat cant move into the hole let val=turn? dfs(M,graph[curr][i],level+1): dfs(graph[curr][i],C,level+1) if(val===2) draw=1 //set draw as an available option else res|=(1^val) //minimax logic, always prefer the losing state of the opponent } memo[M][C][level]=res||(2*draw) // set in this order 1->2->0 } seen[M][C][turn]=undefined;// de-set the state for the current game,as it concluded return memo[M][C][level] } return [2,1,0][dfs(1,2,0)] //js eye candy };
Cat and Mouse
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: There are at least time days before and after the ith day, The number of guards at the bank for the time days before i are non-increasing, and The number of guards at the bank for the time days after i are non-decreasing. More formally, this means day i is a good day to rob the bank if and only if security[i - time] &gt;= security[i - time + 1] &gt;= ... &gt;= security[i] &lt;= ... &lt;= security[i + time - 1] &lt;= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter. &nbsp; Example 1: Input: security = [5,3,3,3,5,6,2], time = 2 Output: [2,3] Explanation: On day 2, we have security[0] &gt;= security[1] &gt;= security[2] &lt;= security[3] &lt;= security[4]. On day 3, we have security[1] &gt;= security[2] &gt;= security[3] &lt;= security[4] &lt;= security[5]. No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank. Example 2: Input: security = [1,1,1,1,1], time = 0 Output: [0,1,2,3,4] Explanation: Since time equals 0, every day is a good day to rob the bank, so return every day. Example 3: Input: security = [1,2,3,4,5,6], time = 2 Output: [] Explanation: No day has 2 days before it that have a non-increasing number of guards. Thus, no day is a good day to rob the bank, so return an empty list. &nbsp; Constraints: 1 &lt;= security.length &lt;= 105 0 &lt;= security[i], time &lt;= 105
class Solution: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: decreasing = [0] * len(security) increasing = [0] * len(security) for i in range(len(security)): if i > 0 and security[i - 1] >= security[i]: decreasing[i] = decreasing[i - 1] + 1 for i in reversed(range(len(security))): if i < len(security) - 1 and security[i] <= security[i + 1]: increasing[i] = increasing[i + 1] + 1 return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time]
class Solution { public List<Integer> goodDaysToRobBank(int[] security, int time) { List<Integer> res = new ArrayList<>(); if (time == 0) { for (int i = 0; i < security.length; i++) res.add(i); return res; } Set<Integer> set = new HashSet<>(); int count = 1; for (int i = 1; i < security.length; i++) { if (security[i] <= security[i - 1]) { count++; } else { count = 1; } if (count > time) { set.add(i); } } count = 1; for (int i = security.length - 2; i >= 0; i--) { if (security[i] <= security[i + 1]) { count++; } else { count = 1; } if (count > time && set.contains(i)) res.add(i); } return res; } }
class Solution { public: vector<int> goodDaysToRobBank(vector<int>& security, int time) { int n = security.size(); vector<int> prefix(n), suffix(n); vector<int> ans; prefix[0] = 0; for(int i=1;i<n;i++) { if(security[i] <= security[i-1]) prefix[i] = prefix[i-1]+1; else prefix[i] = 0; } suffix[n-1] = 0; for(int i=(n-2);i>=0;i--) { if(security[i] <= security[i+1]) suffix[i] = suffix[i+1]+1; else suffix[i] = 0; } for(int i=0;i<n;i++) { if(prefix[i]>=time && suffix[i]>=time) ans.push_back(i); } return ans; } };
var goodDaysToRobBank = function(security, time) { let res = []; if(!time){ let i = 0; while(i<security.length) res.push(i), i++; return res; } let increasing = 0; let decreasing = 0; let set = new Set(); for(let i = 1; i < security.length; i++){ if(security[i]>security[i-1]) decreasing = 0; else decreasing++; if(security[i]<security[i-1]) increasing = 0; else increasing++; if(decreasing>=time) set.add(i); if(increasing>=time&&set.has(i-time)) res.push(i-time); } return res; };
Find Good Days to Rob the Bank
Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently. You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone. The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally.&nbsp;Both players know the other's values. Determine the result of the game, and: If Alice wins, return 1. If Bob wins, return -1. If the game results in a draw, return 0. &nbsp; Example 1: Input: aliceValues = [1,3], bobValues = [2,1] Output: 1 Explanation: If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points. Bob can only choose stone 0, and will only receive 2 points. Alice wins. Example 2: Input: aliceValues = [1,2], bobValues = [3,1] Output: 0 Explanation: If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point. Draw. Example 3: Input: aliceValues = [2,4,3], bobValues = [1,6,7] Output: -1 Explanation: Regardless of how Alice plays, Bob will be able to have more points than Alice. For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7. Bob wins. &nbsp; Constraints: n == aliceValues.length == bobValues.length 1 &lt;= n &lt;= 105 1 &lt;= aliceValues[i], bobValues[i] &lt;= 100
class Solution: def stoneGameVI(self, A, B): G = [a+b for a,b in zip(A,B)] G.sort() L = len(A) d = -sum(B) + sum( G[i] for i in range(L-1,-1,-2) ) return 1 if d>0 else ( -1 if d<0 else 0 )
class Solution { static class Pair { int sum=0; int alice=0; int bob=0; public Pair(int sum,int alice, int bob) { this.sum=sum; this.alice = alice; this.bob = bob; } } // class to define user defined conparator static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p2.sum - p1.sum; } }); } } public int stoneGameVI(int[] aliceValues, int[] bobValues) { int n=aliceValues.length; Pair[] a=new Pair[n]; for(int i=0;i<n;i++) { a[i]=new Pair(aliceValues[i]+bobValues[i],aliceValues[i],bobValues[i]); } Compare.compare(a,n); int al=0;int bo=0; for(int i=0;i<n;i++) { if(i%2==0) { al+=a[i].alice; } else { bo+=a[i].bob; } } return Integer.compare(al,bo); } }
vector<int> alice, bob; struct myComp { bool operator()(pair<int, int>& a, pair<int, int>& b){ return alice[a.second] + bob[a.second] < alice[b.second] + bob[b.second]; } }; class Solution { public: int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) { alice = aliceValues; bob = bobValues; priority_queue<pair<int, int>, vector<pair<int, int>>, myComp> a,b; for(int i=0;i<aliceValues.size();i++){ a.push({aliceValues[i], i}); b.push({bobValues[i], i}); } int ans1, ans2; ans1 = ans2 = 0; int vis[100001] = {}; while(a.size()){ while(a.size() && vis[a.top().second] == 1) a.pop(); if(a.size()){ ans1 += a.top().first; vis[a.top().second] = 1; a.pop(); } while(b.size() && vis[b.top().second] == 1) b.pop(); if(b.size()){ ans2 += b.top().first; vis[b.top().second] = 1; b.pop(); } } if(ans1 == ans2) return 0; if(ans1 > ans2) return 1; return -1; } };
var stoneGameVI = function(aliceValues, bobValues) { let aliceVal = 0 let bobVal = 0 let turn = true const combined = {} let n = aliceValues.length for (let i = 0; i < n; i++) { if (combined[aliceValues[i] + bobValues[i]]) { combined[aliceValues[i] + bobValues[i]].push({value: aliceValues[i] + bobValues[i], id: i}) } else { combined[aliceValues[i] + bobValues[i]] = [{value: aliceValues[i] + bobValues[i], id: i}] } } Object.values(combined).reverse().forEach((value) => { value.forEach(val => { if (turn) { aliceVal += aliceValues[val.id] } else { bobVal += bobValues[val.id] } turn = !turn }) }) if (aliceVal === bobVal) return 0 return aliceVal > bobVal ? 1 : -1 };
Stone Game VI
There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk. &nbsp; Example 1: Input: chalk = [5,1,5], k = 22 Output: 0 Explanation: The students go in turns as follows: - Student number 0 uses 5 chalk, so k = 17. - Student number 1 uses 1 chalk, so k = 16. - Student number 2 uses 5 chalk, so k = 11. - Student number 0 uses 5 chalk, so k = 6. - Student number 1 uses 1 chalk, so k = 5. - Student number 2 uses 5 chalk, so k = 0. Student number 0 does not have enough chalk, so they will have to replace it. Example 2: Input: chalk = [3,4,1,2], k = 25 Output: 1 Explanation: The students go in turns as follows: - Student number 0 uses 3 chalk so k = 22. - Student number 1 uses 4 chalk so k = 18. - Student number 2 uses 1 chalk so k = 17. - Student number 3 uses 2 chalk so k = 15. - Student number 0 uses 3 chalk so k = 12. - Student number 1 uses 4 chalk so k = 8. - Student number 2 uses 1 chalk so k = 7. - Student number 3 uses 2 chalk so k = 5. - Student number 0 uses 3 chalk so k = 2. Student number 1 does not have enough chalk, so they will have to replace it. &nbsp; Constraints: chalk.length == n 1 &lt;= n &lt;= 105 1 &lt;= chalk[i] &lt;= 105 1 &lt;= k &lt;= 109
class Solution: def chalkReplacer(self, chalk: List[int], k: int) -> int: x = sum(chalk) if x<k: k = k%x if x == k: return 0 i = 0 n = len(chalk) while True: if chalk[i]<=k: k -= chalk[i] else: break i +=1 return i
class Solution { public int chalkReplacer(int[] chalk, int k) { long sum = 0; for (int c : chalk) { sum += c; } long left = k % sum; for (int i = 0; i < chalk.length; i++){ if(left >= chalk[i]){ left -= chalk[i]; } else { return i; } } return -1; //just for return statement, put whatever you want here } }
class Solution { public: // T(n) = O(n) S(n) = O(1) int chalkReplacer(vector<int>& chalk, int k) { // Size of the vector int n = chalk.size(); // Store the sum of the elements in the vector long sum = 0; // Calculate the sum of the elements for (int n : chalk) sum += n; // Update k as the remainder of the sum // to make sure that the while loop // will traverse the vector at most 1 time k = k % sum; // Start from the initial value in the array int idx = 0; // While the next student has enough chalk while (k >= chalk[idx]) { // Decrease the remaining chalk k -= chalk[idx]; // Increase the index idx = (idx + 1) % n; } // Return the index of the student without // enough chalk return idx; } };
var chalkReplacer = function(chalk, k) { const sum = chalk.reduce((r, c) => r + c, 0); k %= sum; for (let i = 0; i < chalk.length; i++) { if (chalk[i] > k) { return i; } k -= chalk[i]; } };
Find the Student that Will Replace the Chalk
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and merge = "dv", then after choosing this operation, word1 = "bc" and merge = "dva". If word2 is non-empty, append the first character in word2 to merge and delete it from word2. For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a". Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c. &nbsp; Example 1: Input: word1 = "cabaa", word2 = "bcaaa" Output: "cbcabaaaaa" Explanation: One way to get the lexicographically largest merge is: - Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa" - Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa" - Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa" - Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa" - Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa" - Append the remaining 5 a's from word1 and word2 at the end of merge. Example 2: Input: word1 = "abcabc", word2 = "abdcaba" Output: "abdcabcabcaba" &nbsp; Constraints: 1 &lt;= word1.length, word2.length &lt;= 3000 word1 and word2 consist only of lowercase English letters.
class Solution: def largestMerge(self, word1: str, word2: str) -> str: res = '' p1 = 0 p2 = 0 while p1 < len(word1) and p2 < len(word2): if word1[p1:] > word2[p2:]: res += word1[p1] p1 += 1 else: res += word2[p2] p2 += 1 res += word1[p1:] + word2[p2:] return res
class Solution { public String largestMerge(String word1, String word2) { StringBuilder sb = new StringBuilder(); int i=0; int j=0; char[] w1 = word1.toCharArray(); char[] w2 = word2.toCharArray(); int n1=w1.length; int n2=w2.length; // we loop until we exhaust any one of the 2 words completely while(i<n1 && j<n2){ // if both the characters are equal we choose the one where the next largest occurs earlier if(w1[i]==w2[j]){ if(check(w1,i,w2,j)){ sb.append(w1[i++]); }else{ sb.append(w2[j++]); } } // else we greedily choose the largest of the two characters else if(w1[i]>w2[j]){ sb.append(w1[i++]); }else{ sb.append(w2[j++]); } } // at the end of the loop we append any remaining word sb.append(word1.substring(i)); sb.append(word2.substring(j)); return sb.toString(); } private boolean check(char[] w1, int i, char[] w2, int j){ // will return true if we need to extract from word1 and false if we need to extract from word2 while(i<w1.length && j<w2.length){ if(w1[i]==w2[j]){ i++; j++; } else if(w1[i]>w2[j]){ return true; }else{ return false; } } // if we are unable to find any exhaustable character till the end of the loop we use the one having larger length if(i<w1.length){ return true; } return false; } }
class Solution { public: string largestMerge(string word1, string word2) { string ans=""; while(word1.size()!=0 && word2.size()!=0){ if(word1>=word2) {ans+=word1[0];word1=word1.substr(1);} else {ans+=word2[0];word2=word2.substr(1);} } if(word1.size()!=0)ans=ans+word1; if(word2.size()!=0)ans=ans+word2; return ans; } };
var largestMerge = function(word1, word2) { let ans = ''; let w1 = 0, w2 = 0; while(w1 < word1.length && w2 < word2.length) { if(word1[w1] > word2[w2]) ans += word1[w1++]; else if(word2[w2] > word1[w1]) ans += word2[w2++]; else { const rest1 = word1.slice(w1); const rest2 = word2.slice(w2); if(rest1 > rest2) ans += word1[w1++]; else ans += word2[w2++]; } } ans += word1.slice(w1); ans += word2.slice(w2); return ans; };
Largest Merge Of Two Strings
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false. &nbsp; Example 1: Input: num = 28 Output: true Explanation: 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. Example 2: Input: num = 7 Output: false &nbsp; Constraints: 1 &lt;= num &lt;= 108
class Solution: def checkPerfectNumber(self, num: int) -> bool: sum = 0 root = num**0.5 if num ==1: return False for i in range(2,int(root)+1): if num%i== 0: sum +=(num//i)+i return sum+1 == num
class Solution { public boolean checkPerfectNumber(int num) { if(num==1) return false; int sum = 1; for(int i=2; i<Math.sqrt(num); i++){ if(num%i==0){ sum += i + num / i; } } if(sum==num){ return true; } else{ return false; } } }
class Solution { public: bool checkPerfectNumber(int num) { // we are initialising sum with 1 instead of 0 because 1 will be divisor of every number int sum=1; for(int i=2; i<sqrt(num); i++){ if(num%i==0){ // it checks if both are same factors, for ex, if num=9, i=3, num/i is also equal to 3. It is done so that repeated factors aren't added. if(i==num/i){ sum += i; } else{ // we are adding n/i because since we are running the loop for sqrt(num), we will be missing divisors >sqrt(num) so tto include that factor we'll add num/i; for ex if we have 64 as number than 8 is sqrt but 16 and 32 also divides 64 but our loop won't consider that case; so we are adding num/i, which means with 2 we are adding 32 and with 4 we are adding 16. sum += i + num/i; } } } if(sum==num && num!=1){ return true; } return false; } };
/** * @param {number} num * @return {boolean} */ var checkPerfectNumber = function(num) { let total = 0 for(let i = 1 ; i < num;i++){ if(num % i == 0){ total += i } } return total == num ? true : false };
Perfect Number
Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. &nbsp; Example 1: Input: names = ["pes","fifa","gta","pes(2019)"] Output: ["pes","fifa","gta","pes(2019)"] Explanation: Let's see how the file system creates folder names: "pes" --&gt; not assigned before, remains "pes" "fifa" --&gt; not assigned before, remains "fifa" "gta" --&gt; not assigned before, remains "gta" "pes(2019)" --&gt; not assigned before, remains "pes(2019)" Example 2: Input: names = ["gta","gta(1)","gta","avalon"] Output: ["gta","gta(1)","gta(2)","avalon"] Explanation: Let's see how the file system creates folder names: "gta" --&gt; not assigned before, remains "gta" "gta(1)" --&gt; not assigned before, remains "gta(1)" "gta" --&gt; the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)" "avalon" --&gt; not assigned before, remains "avalon" Example 3: Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"] Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"] Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)". &nbsp; Constraints: 1 &lt;= names.length &lt;= 5 * 104 1 &lt;= names[i].length &lt;= 20 names[i] consists of lowercase English letters, digits, and/or round brackets.
class Solution: def getFolderNames(self, names: List[str]) -> List[str]: # Hashmap will store the name as key and the number of times that name has duplicated so fas as value. hashmap = {} for name in names: modified = name # Check whether the name has already been used if name in hashmap: # Get the number of times the {name} has been used k = hashmap[name] # Calculate the next available suffix. while modified in hashmap: k += 1 modified = f'{name}({k})' # Update the number of times the original {name} is used. This will help to efficiently check for next available suffix if the {name} again comes in future. hashmap[name] = k # Store the modified {name} with 0 as it is not duplicated yet. hashmap[modified] = 0 # Return the keys of hashmap as that would be the unique file names. return hashmap.keys()
class Solution { Map<String, Integer> map = new HashMap<>(); public String[] getFolderNames(String[] names) { String[] op = new String[names.length]; int i = 0; for(String cur : names){ if(map.containsKey(cur)) { cur = generateCopyName(cur); op[i++] = cur; // System.out.println(map.toString()); continue; } op[i++] = cur; map.put(cur, 0); // System.out.println(map.toString()); } return op; } private String generateCopyName(String s) { int count = map.get(s) + 1; String postfix = "(" + count + ")"; StringBuilder sb = new StringBuilder(s); sb.append(postfix); boolean isChanged = false; while(map.containsKey(sb.toString())) { sb = new StringBuilder(s); sb.append("(" + count + ")"); count++; isChanged = true; } String res = sb.toString(); //System.out.println(res); if(isChanged) count = count -1; map.put(s, count); map.put(res, 0); return res; } }
class Solution { unordered_map<string, int> next_index_; bool contain(const string& fn) { return next_index_.find(fn) != next_index_.end(); } string get_name(string fn) { if (!contain(fn)) { next_index_.insert({fn, 1}); return fn; } int idx = next_index_[fn]; auto cur = fn; while (contain(cur)) { next_index_.insert({cur, 1}); cur = fn + "(" + to_string(idx) + ")"; ++idx; } next_index_.insert({cur, 1}); next_index_[fn] = idx; return cur; } public: vector<string> getFolderNames(vector<string>& names) { vector<string> res; for (auto& n : names) { res.push_back(get_name(n)); } return res; } };
/** * @param {string[]} names * @return {string[]} */ var getFolderNames = function(names) { // save existed folder names let hashMap = new Map(); for(let name of names) { let finalName = name; // next smallest suffix number // if this name is not present in the map, next smallest suffix will be 1 let number = hashMap.get(name) || 1; if(hashMap.has(name)) { // append suffix to original name finalName += '(' + number +')'; // find the smallest suffix that hasn't been used before while(hashMap.has(finalName)) { number++; // try to use new suffix to update name finalName = name + '(' + number +')'; } // update next smallest suffix number of new name hashMap.set(finalName, 1); } // update next smallest suffix number of original name hashMap.set(name, number); } return Array.from(hashMap.keys()); };
Making File Names Unique
A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com"&nbsp;and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly. A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times. Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order. &nbsp; Example 1: Input: cpdomains = ["9001 discuss.leetcode.com"] Output: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"] Explanation: We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times. Example 2: Input: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] Output: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"] Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times. &nbsp; Constraints: 1 &lt;= cpdomain.length &lt;= 100 1 &lt;= cpdomain[i].length &lt;= 100 cpdomain[i] follows either the "repi d1i.d2i.d3i" format or the "repi d1i.d2i" format. repi is an integer in the range [1, 104]. d1i, d2i, and d3i consist of lowercase English letters.
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: output, ans = {}, [] for domain in cpdomains : number, domain = domain.split(' ') sub_domain = domain.split('.') pair = '' print(sub_domain) for i in reversed(range(len(sub_domain))) : if i == len(sub_domain)-1 : pair += sub_domain[i] else : pair = sub_domain[i] +'.'+ pair print(pair) # output.append(str(number) + ' '+pair) if pair not in output.keys() : output[pair] = int(number) else : output[pair] += int(number) for key in output.keys() : ans.append(str(output[key]) + ' '+key) return ans
class Solution { public List<String> subdomainVisits(String[] cpdomains) { List<String> result = new LinkedList<>(); HashMap<String, Integer> hmap = new HashMap<>(); for(int i = 0; i < cpdomains.length; i++){ String[] stringData = cpdomains[i].split(" "); String[] str = stringData[1].split("\\."); String subDomains = ""; for(int j = str.length-1; j >= 0; j--){ subDomains = str[j] + subDomains; if(!hmap.containsKey(subDomains)) hmap.put(subDomains, Integer.parseInt(stringData[0])); else hmap.put(subDomains, hmap.get(subDomains) + Integer.parseInt(stringData[0])); subDomains = "." + subDomains; } } for(Map.Entry<String, Integer> entry: hmap.entrySet()){ result.add(entry.getValue() + " " + entry.getKey()); } return result; } }
class Solution { public: vector<string> subdomainVisits(vector<string>& cpdomains) { vector<string> v; unordered_map<string,int> m; for(auto it : cpdomains){ string rep=""; int i=0; while(it[i]!=' '){ rep+=(it[i]); i++; } int r=stoi(rep); m[it.substr(i+1,it.size())]+=r; while(it[i]!='.'){ i++; } m[it.substr(i+1,it.size())]+=r; i++; while(i<it.size() and it[i]!='.'){ i++; } if(i!=it.size()){ m[it.substr(i+1,it.size())]+=r; } } for(auto it : m){ string a=it.first; string b=to_string(it.second); a=b+" "+a; v.push_back(a); } return v; } };
/** * @param {string[]} cpdomains * @return {string[]} */ var subdomainVisits = function(cpdomains) { let map = {} cpdomains.forEach(d => { let data = d.split(" "); let arr = data[1].split(".") while(arr.length > 0) { if(arr.join(".") in map) map[arr.join(".")]+=+data[0] else map[arr.join(".")] = +data[0] arr.shift() } }) let result = [] for(let key in map) result.push(map[key] + " "+ key) return result };
Subdomain Visit Count
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. &nbsp; Example 1: Input: tokens = ["2","1","+","3","*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 &nbsp; Constraints: 1 &lt;= tokens.length &lt;= 104 tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i == "+": stack[-1] = stack[-2] + stack.pop() elif i == "-": stack[-1] = stack[-2] - stack.pop() elif i == "*": stack[-1] = stack[-2] * stack.pop() elif i == "/": stack[-1] = int(stack[-2] / stack.pop()) else: stack.append(int(i)) return stack.pop()
class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack(); for(String i: tokens){ if(i.equals("+") || i.equals("-") || i.equals("*") || i.equals("/")){ int a = stack.pop(); int b = stack.pop(); int temp = 0; if(i.equals("+")) temp = a+b; else if(i.equals("-")) temp = b-a; else if(i.equals("*")) temp = a*b; else if(i.equals("/")) temp = b/a; stack.push(temp); } else stack.push(Integer.parseInt(i)); } return stack.pop(); } }
class Solution { public: int stoi(string s){ int n = 0; int i = 0; bool neg = false; if(s[0] == '-'){ i++; neg = true; } for(; i < s.size(); i++){ n = n*10 + (s[i]-'0'); } if(neg) n = -n; return n; } int evalRPN(vector<string>& tokens) { stack<int>s; int n = tokens.size(); for(int i = 0; i < n; i++){ string str = tokens[i]; if(str == "*"){ int n1 = s.top(); s.pop(); int n2 = s.top(); s.pop(); int res = n2*n1; s.push(res); } else if(str == "+") { int n1 = s.top(); s.pop(); int n2 = s.top(); s.pop(); int res = n2+n1; s.push(res); } else if(str == "/"){ int n1 = s.top(); s.pop(); int n2 = s.top(); s.pop(); int res = n2/n1; s.push(res); } else if(str == "-"){ int n1 = s.top(); s.pop(); int n2 = s.top(); s.pop(); int res = n2-n1; s.push(res); } else{ int num = stoi(str); s.push(num); } } return s.top(); } };
const ops = new Set(['+', '-', '*', '/']); /** * @param {string[]} tokens * @return {number} */ var evalRPN = function(tokens) { const stack = []; for (const token of tokens) { if (!ops.has(token)) { stack.push(Number(token)); continue; } const val1 = stack.pop(); const val2 = stack.pop(); let toPush; if (token === '+') { toPush = val1 + val2; } if (token === '-') { toPush = val2 - val1; } if (token === '*') { toPush = val1 * val2; } if (token === '/') { toPush = Math.trunc(val2 / val1); } stack.push(toPush); } return stack[0] || 0; };
Evaluate Reverse Polish Notation
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment. &nbsp; Example 1: Input: jobs = [3,2,3], k = 3 Output: 3 Explanation: By assigning each person one job, the maximum time is 3. Example 2: Input: jobs = [1,2,4,7,8], k = 2 Output: 11 Explanation: Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. &nbsp; Constraints: 1 &lt;= k &lt;= jobs.length &lt;= 12 1 &lt;= jobs[i] &lt;= 107
class Solution: def dfs(self, pos: int, jobs: List[int], workers: List[int]) -> int: if pos >= len(jobs): return max(workers) mn = float("inf") # we keep track of visited here to skip workers # with the same current value of assigned work # this is an important step in pruning the number # of workers to explore visited = set() for widx in range(len(workers)): if workers[widx] in visited: continue visited.add(workers[widx]) # try this worker workers[widx] += jobs[pos] if max(workers) < mn: # if it's better than our previous proceed res = self.dfs(pos+1, jobs, workers) mn = min(mn, res) # backtrack workers[widx] -= jobs[pos] return mn def minimumTimeRequired(self, jobs: List[int], k: int) -> int: # sorting the jobs means that highest value jobs are assigned first # and more computations can be skipped by pruning jobs.sort(reverse=True) return self.dfs(0, jobs, [0] * k)
class Solution { int result = Integer.MAX_VALUE; public int minimumTimeRequired(int[] jobs, int k) { int length = jobs.length; Arrays.sort(jobs); backtrack(jobs, length - 1, new int [k]); return result; } public void backtrack(int [] jobs, int current, int [] workers) { if (current < 0) { result = Math.min(result, Arrays.stream(workers).max().getAsInt()); return; } if (Arrays.stream(workers).max().getAsInt() >= result) return; for (int i=0; i<workers.length; i++) { if (i > 0 && workers[i] == workers[i-1]) continue; // make choice workers[i] += jobs[current]; // backtrack backtrack(jobs, current-1, workers); // undo the choice workers[i] -= jobs[current]; } } }
class Solution { public: int minimumTimeRequired(vector<int>& jobs, int k) { int sum = 0; for(int j:jobs) sum += j; sort(jobs.begin(),jobs.end(),greater<int>()); int l = jobs[0], r = sum; while(l<r){ int mid = (l+r)>>1; vector<int> worker(k,0); if(dfs(jobs,worker,0,mid)) r = mid; else l = mid + 1; } return l; } bool dfs(vector<int>& jobs, vector<int>& worker, int step, int target){ if(step>=jobs.size()) return true; int cur = jobs[step]; // assign cur to worker i for(int i=0;i<worker.size();i++){ if(worker[i] + cur <= target){ worker[i] += cur; if(dfs(jobs,worker,step+1,target)) return true; worker[i] -= cur; } if(worker[i]==0) break; } return false; } };
var minimumTimeRequired = function(jobs, k) { let n=jobs.length, maskSum=[...Array(1<<n)].map(d=>0) for(let mask=0;mask<(1<<n);mask++) //pre-store the sums of every mask for(let i=0;i<n;i++) maskSum[mask]+=Number(((1<<i) & mask)!=0)*jobs[i] let dp=[...Array(k+1)].map(d=>[...Array(1<<n)].map(d=>Infinity)) dp[0][0]=0 for(let i=1;i<=k;i++) //for each new person for(let curmask=0;curmask<(1<<n);curmask++) //guess what his mask can be, what items can he select for(let prevmask=0;prevmask<(1<<n);prevmask++) // but also, guess what the previous i-1 persons took already if((curmask&prevmask)===0) //obviously, 2 people can't take the same job dp[i][curmask|prevmask]=Math.min(dp[i][curmask|prevmask],Math.max(dp[i-1][prevmask],maskSum[curmask])) return dp[k][(1<<n) -1] };
Find Minimum Time to Finish All Jobs
Given the root of a binary tree, return the inorder traversal of its nodes' values. &nbsp; Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]. -100 &lt;= Node.val &lt;= 100 &nbsp; Follow up: Recursive solution is trivial, could you do it iteratively?
from typing import List, Optional class Solution: """ Time: O(n) """ def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: inorder = [] stack = [] while stack or root is not None: if root: stack.append(root) root = root.left else: node = stack.pop() inorder.append(node.val) root = node.right return inorder class Solution: """ Time: O(n) """ def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: return list(self.inorder_generator(root)) @classmethod def inorder_generator(cls, tree: Optional[TreeNode]): if tree is not None: yield from cls.inorder_generator(tree.left) yield tree.val yield from cls.inorder_generator(tree.right)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { List<Integer> li = new LinkedList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if(root == null){ List<Integer> li = new LinkedList<Integer>(); return li ; } inorderTraversal(root.left); li.add(root.val); inorderTraversal(root.right); return li; } }
class Solution { public: vector<int> v; vector<int> inorderTraversal(TreeNode* root) { if(root!=NULL){ inorderTraversal(root->left); v.push_back(root->val); inorderTraversal(root->right); } return v; } };
var inorderTraversal = function(root) { let result = []; function traverse(node) { if(!node) { return; } traverse(node.left); result.push(node.val); traverse(node.right); } traverse(root); return result; };
Binary Tree Inorder Traversal
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: Trie() Initializes the trie object. void insert(String word) Inserts the string word into the trie. boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. &nbsp; Example 1: Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True &nbsp; Constraints: 1 &lt;= word.length, prefix.length &lt;= 2000 word and prefix consist only of lowercase English letters. At most 3 * 104 calls in total will be made to insert, search, and startsWith.
class Node : def __init__(self ): self.child = {} # to hold the nodes. self.end = False # to mark a node if it is the end node or not. class Trie: def __init__(self): self.root = Node() def insert(self, word:str) -> None: # time compl len(word) sz = len(word) temp = self.root # to hold the root node. for ind , i in enumerate( word ) : if i in temp.child.keys() : # if this curr char in the current node. temp = temp.child[i] #another node. else: temp.child[i] = Node() temp = temp.child[i] if ind == sz - 1 : temp.end = True def search(self, word: str) -> bool: temp = self.root for i in word : if i in temp.child.keys(): temp = temp.child[i] else: return 0 return temp.end == True def startsWith(self, prefix: str) -> bool: temp = self.root for i in prefix : if i in temp.child.keys(): temp = temp.child[i] else: return 0 return 1
class Trie { private class Node{ char character; Node[] sub; Node(char c){ this.character = c; sub = new Node[26]; } } Node root; HashMap<String, Boolean> map; public Trie() { root = new Node('\0'); map = new HashMap<>(); } public void insert(String word) { Node temp = root; for(char c : word.toCharArray()){ int index = c-'a'; if(temp.sub[index] == null) temp.sub[index] = new Node(c); temp = temp.sub[index]; } map.put(word, true); } public boolean search(String word) { return map.containsKey(word); } public boolean startsWith(String prefix) { Node temp = root; for(char c : prefix.toCharArray()){ int index = c-'a'; if(temp.sub[index] == null) return false; temp = temp.sub[index]; } return true; } }
class Trie { public: struct tr { bool isword; vector<tr*> next; tr() { next.resize(26, NULL); // one pointer for each character isword = false; } }; tr *root; Trie() { root = new tr(); } void insert(string word) { tr *cur = root; for(auto c: word) { // if pointer to char doesn't exist create one if(cur->next[c-'a'] == NULL) { cur->next[c-'a'] = new tr(); } cur = cur->next[c-'a']; } // set as end or valid word cur->isword = true; } bool search(string word) { tr *cur = root; for(auto c: word) { // if pointer to char doesn't exist then word is not present if(cur->next[c-'a'] == NULL) { return false; } cur = cur->next[c-'a']; } // check if it is prefix or a word if(cur->isword){ return true; } return false; } // similar to search // here we don't check if it is end or not bool startsWith(string prefix) { tr *cur = root; for(auto c: prefix) { if(cur->next[c-'a'] == NULL) { return false; } cur = cur->next[c-'a']; } return true; } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
var Trie = function() { this.children = {}; this.word = false; }; /** * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { if (!word) { this.word = true; return null; } let head = word[0]; let tail = word.substring(1); if (!this.children[head]) { this.children[head] = new Trie(); } this.children[head].insert(tail); }; /** * @param {string} word * @return {boolean} */ Trie.prototype._search = function(word, method) { if (!word) { if (method === 'search') { return this.word; } else { return true; } } let head = word[0]; let tail = word.substring(1); if (!this.children[head]) { return false; } return this.children[head][method](tail); }; /** * @param {string} word * @return {boolean} */ Trie.prototype.search = function(word) { return this._search(word, 'search'); }; /** * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function(prefix) { return this._search(prefix, 'startsWith'); }; /** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */
Implement Trie (Prefix Tree)
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. &nbsp; Example 1: Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] Output: 3 Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. Example 2: Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] Output: 0 Explanation: There are exactly three trios: 1) [1,4,3] with degree 0. 2) [2,5,6] with degree 2. 3) [5,6,7] with degree 2. &nbsp; Constraints: 2 &lt;= n &lt;= 400 edges[i].length == 2 1 &lt;= edges.length &lt;= n * (n-1) / 2 1 &lt;= ui, vi &lt;= n ui != vi There are no repeated edges.
class Solution: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: result = n ** 2 # placeholder value adj = [set() for _ in range(n + 1)] visited = set() for edge in edges: adj[edge[0]].add(edge[1]) adj[edge[1]].add(edge[0]) for first in range(1, n + 1): # iterate through every node for second in adj[first]: # iterate through every neighbor of the first node e1 = tuple(sorted((first, second))) if e1 in visited: continue visited.add(e1) # mark e1 (first -> second) as visited because we don't want to visit (second -> first) again for third in adj[second]: if third == first: # skip if the third node is the first node (we need the first node to be its neighbor rather than itself!) continue e2 = tuple(sorted((first, third))) if first in adj[third]: # we don't check if e2 is in visited because the third node is not the current node being explored visited.add(e2) # we need to mark e2 as visited because one end of e2 is the first node and if we have checked (third -> first), we don't need to check (first -> third) again degree = len(adj[first]) - 2 + len(adj[second]) - 2 + len(adj[third]) - 2 result = min(result, degree) return -1 if result == n ** 2 else result
class Solution { public int minTrioDegree(int n, int[][] edges) { // to store edge information boolean[][] graph = new boolean[n+1][n+1]; //to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph) int[] inDegree = new int[n+1]; for(int[] edge : edges) { graph[edge[0]][edge[1]] = true; graph[edge[1]][edge[0]] = true; inDegree[edge[0]]++; inDegree[edge[1]]++; } int result = Integer.MAX_VALUE; for(int i=1; i<=n; i++) { for(int j=i+1; j<=n; j++) { if(graph[i][j]) { for(int k=j+1; k<=n; k++) { if(graph[i][k] && graph[j][k]) { result = Math.min(result, inDegree[i] + inDegree[j] + inDegree[k] - 6); } } } } } return result == Integer.MAX_VALUE ? -1 : result; } }
class Solution { public: int minTrioDegree(int n, vector<vector<int>>& edges) { vector<unordered_set<int>> adj(n+1); int res = INT_MAX; for (vector<int>& edge : edges) { adj[edge[0]].insert(edge[1]); adj[edge[1]].insert(edge[0]); } for (int i = 1; i < n; ++i) { for (auto iter1 = adj[i].begin(); iter1 != adj[i].end(); ++iter1) { if (*iter1 <= i) continue; for (auto iter2 = adj[i].begin(); iter2 != adj[i].end(); ++iter2) { int u = *iter1, v = *iter2; if (v <= u) continue; if (adj[u].count(v)) { int cur = adj[i].size() + adj[u].size() + adj[v].size() - 6; res = min(res, cur); } } } } return res == INT_MAX ? -1 : res; } };
var minTrioDegree = function(n, edges) { // create an adjacency list of all the edges; const adjacencyList = new Array(n + 1).fill(0).map(() => new Set()); for (const [x, y] of edges) { adjacencyList[x].add(y); adjacencyList[y].add(x); } let minimumDegree = Infinity; // Find all the combinations of 3 vertices that connect // and if they connect calculate the degree for (let i = 1; i <= n; i++) { for (let j = i + 1; j <= n; j++) { for (let k = j + 1; k <= n; k++) { if (adjacencyList[i].has(j) && adjacencyList[i].has(k) && adjacencyList[j].has(k)) { // We minus 6 because we have 3 vertices and each vertices has 2 edges // going out to the 3 connecting nodes const degree = adjacencyList[i].size + adjacencyList[j].size + adjacencyList[k].size - 6; minimumDegree = Math.min(minimumDegree, degree); } } } } return minimumDegree === Infinity ? -1 : minimumDegree; };
Minimum Degree of a Connected Trio in a Graph
You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations. floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). &nbsp; Example 1: Input: piles = [5,4,9], k = 2 Output: 12 Explanation:&nbsp;Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are [5,4,5]. - Apply the operation on pile 0. The resulting piles are [3,4,5]. The total number of stones in [3,4,5] is 12. Example 2: Input: piles = [4,3,6,7], k = 3 Output: 12 Explanation:&nbsp;Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are [4,3,3,7]. - Apply the operation on pile 3. The resulting piles are [4,3,3,4]. - Apply the operation on pile 0. The resulting piles are [2,3,3,4]. The total number of stones in [2,3,3,4] is 12. &nbsp; Constraints: 1 &lt;= piles.length &lt;= 105 1 &lt;= piles[i] &lt;= 104 1 &lt;= k &lt;= 105
class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: heap = [-p for p in piles] heapq.heapify(heap) for _ in range(k): cur = -heapq.heappop(heap) heapq.heappush(heap, -(cur-cur//2)) return -sum(heap)
class Solution { public int minStoneSum(int[] A, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>((a, b)->b - a); int res = 0; for (int a : A) { pq.add(a); res += a; } while (k-- > 0) { int a = pq.poll(); pq.add(a - a / 2); res -= a / 2; } return res; } }
class Solution { public: int minStoneSum(vector<int>& piles, int k) { priority_queue<int> pq; int sum = 0, curr; for (auto pile : piles) { pq.push(pile); sum += pile; } while (k--) { curr = pq.top(); pq.pop(); sum -= curr/2; pq.push(curr - curr/2); } return sum; } };
/** * @param {number[]} piles * @param {number} k * @return {number} */ var minStoneSum = function(piles, k) { var heapArr = []; for (let i=0; i<piles.length; i++){ heapArr.push(piles[i]); heapifyUp(); } function heapifyUp(){ let currIndex = heapArr.length-1; while (heapArr[currIndex] > heapArr[Math.floor((currIndex-1)/2)]){ swap(currIndex, Math.floor((currIndex-1)/2)); currIndex = Math.floor((currIndex-1)/2); } } function heapifyDown(){ let currIndex = 0; let bigger = currIndex; while (heapArr[currIndex*2+1]){ if (heapArr[currIndex] < heapArr[currIndex*2+1]){ bigger = currIndex * 2 + 1; } if (heapArr[bigger] < heapArr[currIndex*2+2]){ bigger = currIndex * 2 + 2; } if (bigger === currIndex){ break; } swap(currIndex, bigger); currIndex = bigger; } } function swap(currIndex, otherIndex){ let temp = heapArr[currIndex]; heapArr[currIndex] = heapArr[otherIndex]; heapArr[otherIndex] = temp; } while (k > 0){ heapArr[0] -= Math.floor(heapArr[0]/2); heapifyDown(); k--; } return heapArr.reduce((a,num) => a+num, 0); };
Remove Stones to Minimize the Total
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. &nbsp; Example 1: Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. Example 2: Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -109 &lt;= nums[i] &lt;= 109
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: t=len(nums) nums+=nums l=[-1]*len(nums) d={} stack=[0] for x in range(1,len(nums)): #print(x) if nums[x]>nums[stack[-1]]: while nums[x]>nums[stack[-1]] : l[stack[-1]]=nums[x] stack.pop() if stack==[]: break #print(l) stack.append(x) else: stack.append(x) return l[:t]
class Solution { public int[] nextGreaterElements(int[] nums) { Stack<Integer>s=new Stack<>(); for(int i=nums.length-1;i>=0;i--){ s.push(nums[i]); } for(int i=nums.length-1;i>=0;i--){ int num=nums[i]; while(!s.isEmpty() && s.peek()<=nums[i]){ s.pop(); } nums[i]=s.empty()?-1:s.peek(); s.push(num); } return nums; } }
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); vector<int> res; for(int i = 0; i < n; i++){ int j = i + 1; if(j == n) j = 0; int next = -1; while(j != i){ if(nums[j] > nums[i]){ next = nums[j]; break; } j++; if(j == n) j = 0; } res.push_back(next); } return res; } };
var nextGreaterElements = function(nums) { const len = nums.length; const ans = new Array(len).fill(-1); const stack = []; for(let i = 0; i < len; i++) { if(i == 0) stack.push([i, nums[i]]); else { while(stack.length && stack.at(-1)[1] < nums[i]) { ans[stack.pop()[0]] = nums[i]; } stack.push([i, nums[i]]); } } for(let num of nums) { while(stack.length && stack.at(-1)[1] < num) { ans[stack.pop()[0]] = num; } } return ans; };
Next Greater Element II
Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. &nbsp; Example 1: Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3] Output: 2.00000 Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. Example 2: Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0] Output: 4.00000 Example 3: Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4] Output: 4.77778 &nbsp; Constraints: 20 &lt;= arr.length &lt;= 1000 arr.length is a multiple of 20. 0 &lt;= arr[i] &lt;= 105
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])
class Solution { public double trimMean(int[] arr) { Arrays.sort(arr); int length = arr.length; int toRemove = length * 5 / 100; int total = 0; for (int number: arr) { total += number; } for (int i=0; i<toRemove; i++) total -= arr[i]; for (int i=length-1; i>= length-toRemove; i--) total -= arr[i]; length -= (2 * toRemove); return (double) ((double)total / (double)length); } }
class Solution { public: double trimMean(vector<int>& arr) { auto first = arr.begin() + arr.size() / 20; auto second = arr.end() - arr.size() / 20; nth_element(arr.begin(), first, arr.end()); nth_element(first, second, arr.end()); return accumulate(first, second, 0.0) / distance(first, second); } };
var trimMean = function(arr) { arr.sort((a,b) => a - b); let toDelete = arr.length / 20; let sum = 0; for (let i = toDelete; i < arr.length - toDelete; i++) { sum += arr[i]; } return sum / (arr.length - (2 * toDelete)); };
Mean of Array After Removing Some Elements
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls. &nbsp; Example 1: Input: lowLimit = 1, highLimit = 10 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. Example 2: Input: lowLimit = 5, highLimit = 15 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. Example 3: Input: lowLimit = 19, highLimit = 28 Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. &nbsp; Constraints: 1 &lt;= lowLimit &lt;= highLimit &lt;= 105
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: boxes = [0] * 100 for i in range(lowLimit, highLimit + 1): # For the current number "i", convert it into a list of its digits. # Compute its sum and increment the count in the frequency table. boxes[sum([int(j) for j in str(i)])] += 1 return max(boxes)
class Solution { public int countBalls(int lowLimit, int highLimit) { Map<Integer,Integer> map = new HashMap<>(); int count = Integer.MIN_VALUE; for(int i = lowLimit;i<=highLimit;i++){ int value = 0; int temp = i; while (temp!=0){ value += temp%10; temp/=10; } map.put(value,map.getOrDefault(value,0)+1); count = map.get(value) > count ? map.get(value) : count; } return count; } }
class Solution { public: int countBalls(int lowLimit, int highLimit) { vector<int> box (46,0); for(int i = lowLimit;i<=highLimit;i++) { int sum = 0; int temp = i; while(temp) { sum = sum + temp%10; temp = temp/10; } box[sum]++; } return *max_element(box.begin(),box.end()); } };
var countBalls = function(lowLimit, highLimit) { let obj={}; for(let i=lowLimit; i<=highLimit; i++){ i+=''; let sum=0; for(let j=0; j<i.length; j++){ sum+=i[j]*1; } obj[sum]?obj[sum]+=1:obj[sum]=1 } return Math.max(...Object.values(obj)); };
Maximum Number of Balls in a Box
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not. Return true if the array has at least one valid partition. Otherwise, return false. &nbsp; Example 1: Input: nums = [4,4,4,5,6] Output: true Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. This partition is valid, so we return true. Example 2: Input: nums = [1,1,1,2] Output: false Explanation: There is no valid partition for this array. &nbsp; Constraints: 2 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 106
class Solution: def validPartition(self, nums: List[int]) -> bool: n = len(nums) dp = [False] * 3 dp[0] = True # An empty partition is always valid for i in range(2, n + 1): ans = False if nums[i - 1] == nums[i - 2]: ans = ans or dp[(i - 2) % 3] if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]: ans = ans or dp[(i - 3) % 3] if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2: ans = ans or dp[(i - 3) % 3] dp[i % 3] = ans return dp[n % 3]
// Time O(n) // Space O(n) class Solution { public boolean validPartition(int[] nums) { boolean[] dp = new boolean[nums.length+1]; dp[0]=true; // base case for (int i = 2; i <= nums.length; i++){ dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1 dp[i]|= i>2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] && dp[i-3]; // cond 2 dp[i]|= i>2 && nums[i-1]-nums[i-2]==1 && nums[i-2]-nums[i-3]==1 && dp[i-3]; // cond 3 } return dp[nums.length]; } }
class Solution { public: int solve(int i, vector<int> &nums, vector<int> &dp) { if (i == nums.size()) return 1; if (dp[i] != -1) return dp[i]; int ans = 0; if (i+1 < nums.size() and nums[i] == nums[i+1]) ans = max(ans, solve(i+2, nums, dp)); if (i+2 < nums.size()) { if (nums[i] == nums[i+1] && nums[i+1] == nums[i+2]) ans = max(ans, solve(i+3, nums, dp)); else if (abs(nums[i]-nums[i+1]) == 1 and abs(nums[i+1]-nums[i+2]) == 1) ans = max(ans, solve(i+3, nums, dp)); } return dp[i] = ans; } bool validPartition(vector<int>& nums) { vector<int> dp(nums.size()+1, -1); return solve(0, nums, dp); } };
var validPartition = function(nums) { let n = nums.length, memo = Array(n).fill(-1); return dp(0); function dp(i) { if (i === n) return true; if (i === n - 1) return false; if (memo[i] !== -1) return memo[i]; if (nums[i] === nums[i + 1] && dp(i + 2)) return memo[i] = true; if (i < n - 2) { if (!dp(i + 3)) return memo[i] = false; let hasThreeEqual = nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2]; let hasThreeConsecutive = nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2]; if (hasThreeEqual || hasThreeConsecutive) return memo[i] = true; } return memo[i] = false; } };
Check if There is a Valid Partition For The Array
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: steps = 3, arrLen = 2 Output: 4 Explanation: There are 4 differents ways to stay at index 0 after 3 steps. Right, Left, Stay Stay, Right, Left Right, Stay, Left Stay, Stay, Stay Example 2: Input: steps = 2, arrLen = 4 Output: 2 Explanation: There are 2 differents ways to stay at index 0 after 2 steps Right, Left Stay, Stay Example 3: Input: steps = 4, arrLen = 2 Output: 8 &nbsp; Constraints: 1 &lt;= steps &lt;= 500 1 &lt;= arrLen &lt;= 106
class Solution: def numWays(self, steps: int, arrLen: int) -> int: # obtain maximum index we can reach maxLen = min(steps+1, arrLen) dp = [0]*maxLen dp[0] = 1 for step in range(1, steps+1): dp2 = [0]*maxLen for pos in range(maxLen): # dp[step][pos] = dp[step-1][pos] + dp[step-1][pos-1] + dp[step-1][pos+1] temp1 = 0 if pos == 0 else dp[pos-1] temp2 = 0 if pos == maxLen-1 else dp[pos+1] dp2[pos] = (dp[pos] + temp1 + temp2)%(10**9+7) dp = dp2 return dp[0]
class Solution { HashMap<String,Long> map = new HashMap(); public int numWays(int steps, int arrLen) { return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7)); } public long ways(int steps,int arrLen,int index){ String curr = index + "->" + steps; if(index == 0 && steps == 0){ return 1; }else if(index < 0 || (index >= arrLen) || steps == 0){ return 0; } if(map.containsKey(curr)){ return map.get(curr); } long stay = ways(steps-1,arrLen,index); long right = ways(steps-1,arrLen,index+1); long left = ways(steps-1,arrLen,index-1); map.put(curr , (stay+right+left) % 1000000007); return (right + left + stay) % 1000000007; } }
class Solution { public: int n, MOD = 1e9 + 7; int numWays(int steps, int arrLen) { n = arrLen; vector<vector<int>> memo(steps / 2 + 1, vector<int>(steps + 1, -1)); return dp(memo, 0, steps) % MOD; } long dp(vector<vector<int>>& memo, int i, int steps){ if(steps == 0) return i == 0; if(i < 0 || i == n || i > steps) return 0; if(memo[i][steps] != -1) return memo[i][steps]; return memo[i][steps] = (dp(memo, i, steps - 1) + dp(memo, i - 1, steps - 1) + dp(memo, i + 1, steps - 1)) % MOD; } };
var numWays = function(steps, arrLen) { let memo = Array(steps + 1).fill(0).map(() => Array(steps + 1).fill(-1)), mod = 10 ** 9 + 7; return dp(0, steps); function dp(i, steps) { if (steps === 0) return i === 0 ? 1 : 0; // found a way if (i > steps || i < 0 || i >= arrLen) return 0; // out of bounds if (memo[i][steps] !== -1) return memo[i][steps]; // memoized let moveLeft = dp(i - 1, steps - 1); let moveRight = dp(i + 1, steps - 1); let stay = dp(i, steps - 1); return memo[i][steps] = (moveLeft + moveRight + stay) % mod; } };
Number of Ways to Stay in the Same Place After Some Steps
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. &nbsp; Example 1: Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0] Example 2: Input: temperatures = [30,40,50,60] Output: [1,1,1,0] Example 3: Input: temperatures = [30,60,90] Output: [1,1,0] &nbsp; Constraints: 1 &lt;=&nbsp;temperatures.length &lt;= 105 30 &lt;=&nbsp;temperatures[i] &lt;= 100
class Solution: def dailyTemperatures(self, T): ans, s = [0]*len(T), deque() for cur, cur_tmp in enumerate(T): while s and cur_tmp > T[s[-1]]: ans[s[-1]] = cur - s[-1] s.pop() s.append(cur) return ans
class Solution { public int[] dailyTemperatures(int[] temperatures) { HashMap<Integer,Integer>hm=new HashMap<>(); Stack<Integer>st=new Stack<>(); for(int i=0;i<temperatures.length;i++){ while(st.size()>0&&temperatures[i]>temperatures[st.peek()]){ hm.put(st.pop(),i); } st.push(i); } int []ans=new int[temperatures.length]; for(int i=0;i<temperatures.length;i++){ if(hm.containsKey(i)){ ans[i]=hm.get(i)-i; }else{ ans[i]=0; } } return ans; } }
class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { int n = temperatures.size(); stack<int> st; vector<int> result(n, 0); for(int i = 0; i<n; i++){ while(!st.empty() && temperatures[i]>temperatures[st.top()]){ result[st.top()] = i-st.top(); st.pop(); } st.push(i); } return result; } };
var dailyTemperatures = function(temperatures) { const len = temperatures.length; const res = new Array(len).fill(0); const stack = []; for (let i = 0; i < len; i++) { const temp = temperatures[i]; while (temp > (stack[stack.length - 1] || [Infinity])[0]) { const [_, j] = stack.pop(); res[j] = i - j; } stack.push([temp, i]); } return res; };
Daily Temperatures
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. &nbsp; Example 1: Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7] Example 2: Input: preorder = [1], postorder = [1] Output: [1] &nbsp; Constraints: 1 &lt;= preorder.length &lt;= 30 1 &lt;= preorder[i] &lt;= preorder.length All the values of preorder are unique. postorder.length == preorder.length 1 &lt;= postorder[i] &lt;= postorder.length All the values of postorder are unique. It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
class Solution: def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def build(preorder, preStart, preEnd, postorder, postStart, postEnd): if preStart > preEnd: return elif preStart == preEnd: return TreeNode(preorder[preStart]) rootVal = preorder[preStart] leftRootVal = preorder[preStart + 1] index = valToIndex[leftRootVal] root = TreeNode(rootVal) leftSize = index - postStart + 1 root.left = build(preorder, preStart + 1, preStart + leftSize, postorder, postStart, index) root.right = build(preorder, preStart + leftSize + 1, preEnd, postorder, index + 1, postEnd - 1) return root valToIndex = {} for i in range(len(postorder)): valToIndex[postorder[i]] = i return build(preorder, 0, len(preorder) - 1, postorder, 0, len(postorder) - 1)
class Solution { public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { // O(n) time | O(h) space if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null; TreeNode root = new TreeNode(preorder[0]); int mid = 0; if(preorder.length == 1) return root; // update mid for(int i = 0; i < postorder.length; i++) { if(preorder[1] == postorder[i]) { mid = i; break; } } root.left = constructFromPrePost( Arrays.copyOfRange(preorder, 1, 1 + mid + 1), Arrays.copyOfRange(postorder, 0, mid + 1)); root.right = constructFromPrePost( Arrays.copyOfRange(preorder, 1 + mid + 1, preorder.length), Arrays.copyOfRange(postorder, mid + 1, postorder.length - 1)); 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: bool vis[40]; TreeNode* solve(vector<int>& pre,int p, vector<int>& pos,int q){ TreeNode* root=new TreeNode(pre[p]); vis[pre[p]]=true; p++; q--; if(p>=pre.size() || q<0){ return root; } if(!vis[pre[p]]){ int x=q; while(x>0 and pos[x]!=pre[p])x--; if(pos[x]==pre[p]){ root->left=solve(pre,p,pos,x); } } if(!vis[pos[q]]){ int x=p; while(x<pre.size()-1 and pos[q]!=pre[x])x++; if(pos[q]==pre[x]){ root->right=solve(pre,x,pos,q); } } return root; } TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) { int n=postorder.size(); return solve(preorder,0,postorder,n-1); } };
var constructFromPrePost = function(preorder, postorder) { let preIndex = 0 const dfs = (postArr) => { if (postArr.length === 0) return null const val = preorder[preIndex] const nextVal = preorder[++preIndex] const mid = postArr.indexOf(nextVal) const root = new TreeNode(val) root.left = dfs(postArr.slice(0, mid + 1)) root.right = dfs(postArr.slice(mid + 1, postArr.indexOf(val))) return root } return dfs(postorder) };
Construct Binary Tree from Preorder and Postorder Traversal
You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. &nbsp; Example 1: Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] Output: "Sao Paulo" Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -&gt; "New York" -&gt; "Lima" -&gt; "Sao Paulo". Example 2: Input: paths = [["B","C"],["D","B"],["C","A"]] Output: "A" Explanation: All possible trips are:&nbsp; "D" -&gt; "B" -&gt; "C" -&gt; "A".&nbsp; "B" -&gt; "C" -&gt; "A".&nbsp; "C" -&gt; "A".&nbsp; "A".&nbsp; Clearly the destination city is "A". Example 3: Input: paths = [["A","Z"]] Output: "Z" &nbsp; Constraints: 1 &lt;= paths.length &lt;= 100 paths[i].length == 2 1 &lt;= cityAi.length, cityBi.length &lt;= 10 cityAi != cityBi All strings consist of lowercase and uppercase English letters and the space character.
from collections import defaultdict class Solution: def destCity(self, paths: List[List[str]]) -> str: deg = defaultdict(int) for v, w in paths: deg[v] += 1 deg[w] for v in deg: if not deg[v]: return v
class Solution { public String destCity(List<List<String>> paths) { HashSet<String> set1 = new HashSet<>(); for (int i = 0; i < paths.size(); ++i) { set1.add(paths.get(i).get(0)); } for (int i = 0; i < paths.size(); ++i) { if (!set1.contains(paths.get(i).get(1))) return paths.get(i).get(1); } return "placeholder"; } }
class Solution { public: string destCity(vector<vector<string>>& paths) { string ans; unordered_map<string, int> m; for(int i=0; i<paths.size(); i++){ m[paths[i][0]]++; m[paths[i][1]]--; } for(auto city : m){ if(city.second == -1) ans = city.first; } return ans; } };
* @param {string[][]} paths * @return {string} */ var destCity = function(paths) { let map={} for(let city of paths){ map[city[0]]=map[city[0]]?map[city[0]]+1:1 } for(let city of paths){ if(!map[city[1]]) return city[1] } };```
Destination City
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: Input: target = [3,1,1,2] Output: 4 Explanation: [0,0,0,0] -&gt; [1,1,1,1] -&gt; [1,1,1,2] -&gt; [2,1,1,2] -&gt; [3,1,1,2] Example 3: Input: target = [3,1,5,4,2] Output: 7 Explanation: [0,0,0,0,0] -&gt; [1,1,1,1,1] -&gt; [2,1,1,1,1] -&gt; [3,1,1,1,1] -&gt; [3,1,2,2,2] -&gt; [3,1,3,3,2] -&gt; [3,1,4,4,2] -&gt; [3,1,5,4,2]. &nbsp; Constraints: 1 &lt;= target.length &lt;= 105 1 &lt;= target[i] &lt;= 105
class Solution: def minNumberOperations(self, nums: List[int]) -> int: res=nums[0] prev=nums[0] for i in range(1,len(nums)): res += max(0,nums[i]-prev) prev=nums[i] return res
// Imagine 3 cases // Case 1. [3,2,1], we need 3 operations. // Case 2. [1,2,3], we need 3 operations. // Case 3. [3,2,1,2,3], we need 5 operations. // What we need to add is actually the diff (cur - prev) // Time complexity: O(N) // Space complexity: O(1) class Solution { public int minNumberOperations(int[] target) { int res = 0; int prev = 0; for (int cur : target) { if (cur > prev) { res += cur - prev; } prev = cur; } return res; } }
class Solution { public: int minNumberOperations(vector<int>& target) { int n=target.size(); int pre=0, cnt=0; for(int i=0;i<n;i++) { if(target[i]>pre) cnt+=target[i]-pre; pre=target[i]; } return cnt; } };
var minNumberOperations = function(target) { let res = target[0]; for(let g=1; g<target.length; g++){ if(target[g] > target[g-1]){ res = res + (target[g] - target[g-1]); } // for target[g] < target[g-1] we need not worry as its already been taken care by previous iterations } return res; };
Minimum Number of Increments on Subarrays to Form a Target Array
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. &nbsp; Example 1: Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -&gt; "1000" -&gt; "1100" -&gt; "1200" -&gt; "1201" -&gt; "1202" -&gt; "0202". Note that a sequence like "0000" -&gt; "0001" -&gt; "0002" -&gt; "0102" -&gt; "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102". Example 2: Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -&gt; "0009". Example 3: Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We cannot reach the target without getting stuck. &nbsp; Constraints: 1 &lt;= deadends.length &lt;= 500 deadends[i].length == 4 target.length == 4 target will not be in the list deadends. target and deadends[i] consist of digits only.
class Solution: def openLock(self, deadends: List[str], target: str) -> int: def neighbor(s): res = [] for i, c in enumerate(s): res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:]) res.append(s[:i] + chr((ord(c) - ord('0') + 1) % 10 + ord('0')) + s[i + 1:]) return res deadends = set(deadends) if "0000" in deadends: return -1 ans = 0 queue = deque(["0000"]) vis = set() while queue: l = len(queue) for _ in range(l): cur = queue.popleft() if cur == target: return ans for nxt in neighbor(cur): if nxt not in vis and nxt not in deadends: queue.append(nxt) vis.add(nxt) ans += 1 return -1
class Solution { public int openLock(String[] deadends, String target) { // Converted target to Integer type. int t = Integer.parseInt(target); HashSet<Integer> visited = new HashSet<>(); // Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited. for(String str: deadends){ visited.add(Integer.parseInt(str)); } // BFS Queue<Integer> q = new ArrayDeque<>(); // We make sure that 0 itself isn't a deadend if(visited.contains(0)){ return -1; } q.add(0); visited.add(0); int level = 0; while(q.size() > 0){ int size = q.size(); while(size-->0){ int elem = q.remove(); if(t == elem){ return level; } // Will help check 4 digits of the element. From digit with low precendence(ones place) to high precedence(thousands place) for(int i = 1; i < 10000; i= i*10){ // The wheel can be rotated in two directions. Hence two numbers. int num1; int num2; // The wheel at 0 can become 1 or 9 due to wrapping. if(elem / i % 10 == 0){ num1=elem + i; num2 = elem+ i * 9; } // The wheel at 9 can become 0 or 8 due to wrapping. else if(elem / i % 10 == 9){ num1 = elem - i * 9; num2 = elem -i; } else{ num1 = elem -i; num2 = elem + i; } // Checking if numbers have already been visited. if(!(visited.contains(num1))){ visited.add(num1); q.add(num1); } if(!(visited.contains(num2))){ visited.add(num2); q.add(num2); } } } level++; } return -1; } }
class Solution { public: void setPermutations(const string& s, queue<pair<string, int>>& q, int count) { for (int i=0; i<4; i++) { int j = s[i]-'0'; char b = (10+j-1)%10 + '0', n = (10+j+1)%10 + '0'; auto tmp = s; tmp[i]=b; q.push({tmp, count+1}); tmp = s; tmp[i]=n; q.push({tmp, count+1}); } } int openLock(vector<string>& deadends, string target) { unordered_set<string> deadies(deadends.begin(), deadends.end()); queue<pair<string, int>> q({{"0000", 0}}); while (!q.empty()) { auto t = q.front(); q.pop(); if (deadies.count(t.first)) continue; if (t.first==target) return t.second; deadies.insert(t.first); setPermutations(t.first, q, t.second); } return -1; } };
var openLock = function(deadends, target) { if(deadends.includes('0000')) { return -1 } // treat deadends like visited // if a number is in visited/deadends, simply ignore it const visited = new Set(deadends) const queue = [['0000', 0]]; visited.add('0000') while(queue.length) { const [cur, count] = queue.shift() if(cur === target) { return count } // each number will create 8 more different paths to check // e.g. if cur = 0000. 8 next/prev numbers to check are // 1000, 9000, 0100, 0900, 0010, 0090, 0001, 0009 for(let i=0; i<4; i++) { const c = cur[i] let up = Number(c) + 1; let down = Number(c) - 1; // if up is 9, then up + 1 = 10 -> set it to 0 if(up === 10) { up = '0'; } // if down is 0. then down - 1 = -1 -> set to 9 if(down === -1) { down = '9' } const next = cur.substring(0, i) + up + cur.substring(i+1) const prev = cur.substring(0, i) + down + cur.substring(i + 1) // if not visited, push to queue if(!visited.has(next)) { visited.add(next) queue.push([next, count + 1]) } if(!visited.has(prev)) { visited.add(prev) queue.push([prev, count + 1]) } } } return -1; };
Open the Lock
Given an integer array arr, return true&nbsp;if there are three consecutive odd numbers in the array. Otherwise, return&nbsp;false. &nbsp; Example 1: Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds. Example 2: Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,23] are three consecutive odds. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 1000 1 &lt;= arr[i] &lt;= 1000
class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: c=0 for i in arr: if i%2==0: c=0 else: c+=1 if c==3: return True return False
class Solution { public boolean threeConsecutiveOdds(int[] arr) { int count = 0,n = arr.length; for(int i=0;i<n;i++) { if((arr[i] & 1) > 0) { count++; if(count == 3) return true; } else { count = 0; } } return false; } }
class Solution { public: bool threeConsecutiveOdds(vector<int>& arr) { int k = 0; for(int i=0;i<arr.size();i++){ if(arr[i] % 2 != 0){ k++; if(k == 3){ return true; } }else{ k = 0; } } return false; } };
var threeConsecutiveOdds = function(arr) { let c = 0; for(let val of arr){ if(val % 2 === 1){ c++; if(c === 3) { return true; } } else { c=0; } } return false; };
Three Consecutive Odds
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick any city j such that j != i and 0 &lt;= j &lt; locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x. Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish). Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5 Output: 4 Explanation: The following are all possible routes, each uses 5 units of fuel: 1 -&gt; 3 1 -&gt; 2 -&gt; 3 1 -&gt; 4 -&gt; 3 1 -&gt; 4 -&gt; 2 -&gt; 3 Example 2: Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6 Output: 5 Explanation: The following are all possible routes: 1 -&gt; 0, used fuel = 1 1 -&gt; 2 -&gt; 0, used fuel = 5 1 -&gt; 2 -&gt; 1 -&gt; 0, used fuel = 5 1 -&gt; 0 -&gt; 1 -&gt; 0, used fuel = 3 1 -&gt; 0 -&gt; 1 -&gt; 0 -&gt; 1 -&gt; 0, used fuel = 5 Example 3: Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3 Output: 0 Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel. &nbsp; Constraints: 2 &lt;= locations.length &lt;= 100 1 &lt;= locations[i] &lt;= 109 All integers in locations are distinct. 0 &lt;= start, finish &lt; locations.length 1 &lt;= fuel &lt;= 200
from bisect import bisect_left from functools import lru_cache class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: start = locations[start] end = locations[finish] locations.sort() start = bisect_left(locations, start) end = bisect_left(locations, end) @lru_cache(None) def dfs(i, fuel): if fuel == 0 and i == end: return 1 res = 0 if i == end: res += 1 j = i-1 while j>=0 and abs(locations[j]-locations[i]) <= fuel: res += dfs(j, fuel-abs(locations[j]-locations[i])) j -= 1 j = i+1 while j<len(locations) and abs(locations[j]-locations[i]) <= fuel: res += dfs(j, fuel-abs(locations[j]-locations[i])) j += 1 return res return dfs(start, fuel) % (10**9+7)
/* Using DFS and Memo : 1. We will start from start pos provided and will dfs travel to each other location . 2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling 3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path 4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing . */ class Solution { int mod = (int)Math.pow(10,9) + 7 ; int[][] dp ; public int countRoutes(int[] locations, int start, int finish, int fuel) { dp = new int[locations.length][fuel+1] ; for(int[] row : dp){ Arrays.fill(row , -1) ; } return dfs(locations , start , finish , fuel); } public int dfs(int[] locations , int cur_location , int finish , int fuel){ if(fuel < 0){ return 0 ; } if(dp[cur_location][fuel] != -1){ return dp[cur_location][fuel] ; } int result = 0 ; if(cur_location == finish){ result++ ; } for(int i=0 ; i<locations.length ; i++){ if(i == cur_location) continue ; int fuel_cost = Math.abs(locations[i] - locations[cur_location]); int next_trip = dfs(locations , i , finish , fuel-fuel_cost); result += next_trip ; result %= mod ; } dp[cur_location][fuel] = result ; return dp[cur_location][fuel] ; } }
class Solution { public: int fun(vector<int> &arr , int s , int f , int k , vector<vector<int>> &dp){ if(k<0) return 0 ; if(dp[s][k]!=-1) return dp[s][k] ; int ans=0 ; if(s==f) ans=1 ; for(int i=0 ; i<arr.size() ; i++){ if(i!=s) ans=(ans+fun(arr,i,f,k-abs(arr[s]-arr[i]),dp))%1000000007; } return dp[s][k]=ans ; } int countRoutes(vector<int>& locations, int start, int finish, int fuel) { vector<vector<int>> dp(locations.size()+1,vector<int>(fuel+1,-1)) ; int ans=fun(locations,start,finish,fuel,dp) ; return ans ; } };
var countRoutes = function(locations, start, finish, fuel) { const memo = new Array(locations.length+1).fill(0).map(()=>new Array(201).fill(-1)); const dfs = function(cur, f){ if(f<0) return 0; if(memo[cur][f]!=-1) return memo[cur][f]; let res = (cur==finish); for(let i in locations){ if(i==cur) continue; res = (res + dfs(i, f-Math.abs(locations[i]-locations[cur])))%1000000007; } return memo[cur][f]=res; } return dfs(start, fuel); };
Count All Possible Routes
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. &nbsp; Example 1: Input: arr = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is&nbsp;[1,5,7], so the answer is&nbsp;13. Example 2: Input: grid = [[7]] Output: 7 &nbsp; Constraints: n == grid.length == grid[i].length 1 &lt;= n &lt;= 200 -99 &lt;= grid[i][j] &lt;= 99
class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) if m == 1 and n == 1: return grid[0][0] min_arr = [0 for _ in range(n)] for i in range(m): prefix = [float('inf') for _ in range(n)] suffix = [float('inf') for _ in range(n)] current_row = [elem1+elem2 for elem1, elem2 in zip(grid[i], min_arr)] for i in range(1, n): prefix[i] = min(prefix[i-1], current_row[i-1]) for i in range(n-2, -1, -1): suffix[i] = min(suffix[i+1], current_row[i+1]) min_arr = [min(pre, suff) for pre, suff in zip(prefix, suffix)] return min(min_arr)
class Solution { // Recursion /* public int minFallingPathSum(int[][] grid) { int n=grid.length; if(n==1) return grid[0][0]; int ans = 10000000; for(int i=0 ; i<n ; i++){ ans = Math.min(ans , grid[0][i] + helper(grid , n , 1 , i)); } return ans; } private int helper(int[][] grid , int n , int i , int last){ if( i == n-1 ){ int min = 100; for(int k=0 ; k<n ; k++){ if(k!=last){ min = Math.min( grid[n-1][k] , min); } } return min; } int min = 100000000; for(int k=0 ; k<n ; k++){ if(k != last){ min = Math.min( min ,grid[i][k] + helper(grid , n , i+1 , k) ); } } return min; } */ // DP MEMOIZATION public int minFallingPathSum(int[][] grid) { int n=grid.length; if(n==1) return grid[0][0]; int[][] dp = new int[n][n]; for(int i=0 ; i<n ; i++){ for(int j=0 ; j<n ; j++){ dp[i][j] = -1; } } int ans = 10000000; for(int i=0 ; i<n ; i++){ ans = Math.min(ans , grid[0][i] + helper(grid , n , 1 , i , dp)); } return ans; } private int helper(int[][] grid , int n , int i , int last , int[][] dp){ if( i == n-1 ){ int min = 100; for(int k=0 ; k<n ; k++){ if(k!=last){ min = Math.min( grid[n-1][k] , min); } } return min; } if(dp[i][last] != -1) return dp[i][last]; int min = 100000000; for(int k=0 ; k<n ; k++){ if(k != last){ min = Math.min( min ,grid[i][k] + helper(grid , n , i+1 , k , dp) ); } } dp[i][last] = min; return dp[i][last]; } }
class Solution { public: int f(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &dp){ //to handle edge cases if the j index is less than 0 or greater than size of the array. if(j<0 or j>=matrix[0].size()) return 1e8; //base case if(i==0) return dp[0][j] = matrix[0][j]; if(dp[i][j]!=-1) return dp[i][j]; int ans = INT_MAX; //Here we have to iterate through all the possiblities in the entire upper row for each //element except for the element which is directly above the current element in the //matrix, and then we have to find the minimum. for(int k=0;k<matrix[0].size();k++){ if(k==j) continue; ans = min(ans, matrix[i][j] + f(i-1, k, matrix, dp)); } return dp[i][j] = ans; } int minFallingPathSum(vector<vector<int>>& grid) { int mini = INT_MAX; int n = grid.size(); vector<vector<int>> dp(n, vector<int>(n,-1)); for(int j=0;j<n;j++){ mini = min(mini, f(n-1, j, grid, dp)); } return mini; } };
var minFallingPathSum = function(grid) { if(grid.length===1){ return grid[0][0]; } let sums = [];//find first, second and third minimum values in the grid as these are only possible values for path //store the index for fast lookup in a 3D array for(let i=0; i<grid.length; i++){ let min = Math.min(...grid[i]); let idx = grid[i].indexOf(min); grid[i].splice(idx, 1, Infinity); let min2 = Math.min(...grid[i]); let idx2 = grid[i].indexOf(min2); grid[i].splice(idx2, 1, Infinity); let min3 = Math.min(...grid[i]); let idx3 = grid[i].indexOf(min3); sums.push([[min,idx],[min2,idx2],[min3,idx3]]); } // sums contains 1st , 2nd and 3rd min value and index let memo = {}; // for memoization let recur = (r,li) => {//recursive call to decide which path to choose from r=row, li=lastIndex if(memo[r+','+li] !== undefined){// memoized return memo[r+','+li]; } if(r===grid.length-1){// last and first choice for path can only be from 1st and 2nd minimum, as there is only one other row to occupy these columns if(li===sums[r][0][1]){ memo[r+','+li] = sums[r][1][0]; } else{ memo[r+','+li] = sums[r][0][0]; } return memo[r+','+li]; } else{ switch (li) {// pick the minimum value path where index is not equal to last index case sums[r][0][1]: memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1])); break; case sums[r][1][1]: memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][2][0]+recur(r+1,sums[r][2][1])); break; case sums[r][2][1]: memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][0][0]+recur(r+1,sums[r][0][1])); break; default: memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1])); } return memo[r+','+li]; } } return recur(0,sums[0][2][1]);//since first and last can only be picked from 1st and 2nd min values };
Minimum Falling Path Sum II
You are given a string num representing a large integer. An integer is good if it meets the following conditions: It is a substring of num with length 3. It consists of only one unique digit. Return the maximum good integer as a string or an empty string "" if no such integer exists. Note: A substring is a contiguous sequence of characters within a string. There may be leading zeroes in num or a good integer. &nbsp; Example 1: Input: num = "6777133339" Output: "777" Explanation: There are two distinct good integers: "777" and "333". "777" is the largest, so we return "777". Example 2: Input: num = "2300019" Output: "000" Explanation: "000" is the only good integer. Example 3: Input: num = "42352338" Output: "" Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. &nbsp; Constraints: 3 &lt;= num.length &lt;= 1000 num only consists of digits.
class Solution: def largestGoodInteger(self, n: str) -> str: return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else "" for i in range(2, len(n)))
class Solution { public String largestGoodInteger(String num) { String ans = ""; for(int i = 2; i < num.length(); i++) if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2)) if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is larger ans = num.substring(i-2,i+1); return ans; } }
class Solution { public: string largestGoodInteger(string num) { string ans = ""; for(int i=1; i<num.size()-1; i++) { if(num[i-1] == num[i] && num[i] == num[i+1]) { string temp = {num[i-1], num[i], num[i+1]}; ans = max(ans, temp); } } return ans; } };
var largestGoodInteger = function(num) { let maxGoodInt = ''; for (let i = 0; i <= num.length - 3; i++) { if (num[i] === num[i+1] && num[i+1] === num[i+2]) { if (num[i] >= maxGoodInt) { maxGoodInt = num[i]; } } } return maxGoodInt + maxGoodInt + maxGoodInt; };
Largest 3-Same-Digit Number in String
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: You choose any number of obstacles between 0 and i inclusive. You must include the ith obstacle in the course. You must put the chosen obstacles in the same order as they appear in obstacles. Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it. Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above. &nbsp; Example 1: Input: obstacles = [1,2,3,2] Output: [1,2,3,3] Explanation: The longest valid obstacle course at each position is: - i = 0: [1], [1] has length 1. - i = 1: [1,2], [1,2] has length 2. - i = 2: [1,2,3], [1,2,3] has length 3. - i = 3: [1,2,3,2], [1,2,2] has length 3. Example 2: Input: obstacles = [2,2,1] Output: [1,2,1] Explanation: The longest valid obstacle course at each position is: - i = 0: [2], [2] has length 1. - i = 1: [2,2], [2,2] has length 2. - i = 2: [2,2,1], [1] has length 1. Example 3: Input: obstacles = [3,1,5,6,4,2] Output: [1,1,2,3,2,2] Explanation: The longest valid obstacle course at each position is: - i = 0: [3], [3] has length 1. - i = 1: [3,1], [1] has length 1. - i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid. - i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid. - i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid. - i = 5: [3,1,5,6,4,2], [1,2] has length 2. &nbsp; Constraints: n == obstacles.length 1 &lt;= n &lt;= 105 1 &lt;= obstacles[i] &lt;= 107
from bisect import bisect_right class Solution: def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: longest, res = [], [] for i in range(len(obstacles)): idx = bisect_right(longest, obstacles[i]) if idx == len(longest): longest.append(obstacles[i]) else: longest[idx] = obstacles[i] res.append(idx+1) return res
class Solution { public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { int i = -1, cur = 0, lisSize = -1; int[] lis = new int[obstacles.length]; int[] ans = new int[obstacles.length]; for (int curHeight: obstacles) { if (i == -1 || lis[i] <= curHeight) { lis[++i] = curHeight; lisSize = i; } else { lisSize = search(lis, 0, i, curHeight); lis[lisSize] = curHeight; } ans[cur++] = lisSize + 1; } return ans; } private int search(int[] nums, int start, int end, int target) { int left = start, right = end; int boundary = 0; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] > target) { boundary = mid; right = mid - 1; } else left = mid + 1; } return boundary; } }
class Solution { public: // ranking each element to make segment tree of small size void compress(vector<int>& a){ vector<int> b=a; sort(b.begin(),b.end()); map<int,int> mp; int prev=b[0],rnk=0,n=a.size(); for(int i=0;i<n;i++){ if(b[i]!=prev){ prev=b[i]; rnk++; } mp[b[i]]=rnk; } for(int i=0;i<n;i++) a[i]=mp[a[i]]; } void update(int st[],int tind,int ind,int val,int tl,int tr){ if(tl>tr) return; if(tl==tr){ st[tind]=val; return; } int m=tl+(tr-tl)/2,left=tind<<1; if(ind<=m) update(st,left,ind,val,tl,m); else update(st,left+1,ind,val,m+1,tr); st[tind]=max(st[left],st[left+1]); } int query(int st[],int tind,int tl,int tr,int ql,int qr){ if(tl>tr or ql>tr or qr<tl) return 0; if(ql<=tl and tr<=qr) return st[tind]; int m=tl+(tr-tl)/2,left=tind<<1; return max(query(st,left,tl,m,ql,qr),query(st,left+1,m+1,tr,ql,qr)); } vector<int> longestObstacleCourseAtEachPosition(vector<int>& a) { compress(a); int i,n=a.size(); int st[4*n+10]; memset(st,0,sizeof(st)); update(st,1,a[0],1,0,n-1); vector<int> dp(n); dp[0]=1; for(i=1;i<n;i++){ int mx=query(st,1,0,n-1,0,a[i]); dp[i]=1+mx; update(st,1,a[i],dp[i],0,n-1); } return dp; } };
var longestObstacleCourseAtEachPosition = function(obstacles) { var n = obstacles.length; var lis = []; var res = new Array(n).fill(0); for(var i = 0; i<n; i++) { if(lis.length>0 && obstacles[i] >= lis[lis.length-1]) { lis.push(obstacles[i]); res[i] = lis.length; } else { // find the upper bound var l = 0; var r = lis.length; while(l<=r) { var mid = Math.floor((l+r)/2); if(lis[mid]<=obstacles[i]) { l = mid+1; } else { r = mid-1; } } lis[l] = obstacles[i]; res[i] = l+1; } } return res; }
Find the Longest Valid Obstacle Course at Each Position
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3. &nbsp; Example 1: Input: n = 22 Output: 2 Explanation: 22 in binary is "10110". The first adjacent pair of 1's is "10110" with a distance of 2. The second adjacent pair of 1's is "10110" with a distance of 1. The answer is the largest of these two distances, which is 2. Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined. Example 2: Input: n = 8 Output: 0 Explanation: 8 in binary is "1000". There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0. Example 3: Input: n = 5 Output: 2 Explanation: 5 in binary is "101". &nbsp; Constraints: 1 &lt;= n &lt;= 109
class Solution: def binaryGap(self, n: int) -> int: prev = 0 res = 0 for i, d in enumerate(bin(n)[3:]): if d == "1": res = max(res, i-prev+1) prev = i + 1 return res
class Solution { public int binaryGap(int n) { char[] arr = Integer.toBinaryString(n).toCharArray(); List<Integer> ans = new ArrayList(); for(int i = 0; i < arr.length ; i++){ if(arr[i] == '1') ans.add(i); } int res = 0; for ( int i = 0 ; i < ans.size() -1 ; i++){ res =Math.max(res,ans.get(i+1) - ans.get(i)); } return res; } }
class Solution { public: int binaryGap(int n) { int res=0; int s=0,i=0; while(n){ if(n&1){ s=i;break; } i++; n=n>>1; } while(n){ if(n&1){ res=max(res,(i-s)); s=i; } i++; n=n>>1; } return res; } };
var binaryGap = function(n) { var str = (n >>> 0).toString(2), start = 0, end = 0, diff = 0; for(var i=0;i<str.length;i++) { if(str[i] === '1') { end = i; diff = Math.max(diff, end - start); start = i; } } return diff; };
Binary Gap
Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defined as a non-empty contiguous sequence of elements in an array. &nbsp; Example 1: Input: nums = [2,3,3,2,2], k = 2, p = 2 Output: 11 Explanation: The elements at indices 0, 3, and 4 are divisible by p = 2. The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2]. Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once. The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 4, p = 1 Output: 10 Explanation: All element of nums are divisible by p = 1. Also, every subarray of nums will have at most 4 elements that are divisible by 1. Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 200 1 &lt;= nums[i], p &lt;= 200 1 &lt;= k &lt;= nums.length &nbsp; Follow up: Can you solve this problem in O(n2) time complexity?
class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: n = len(nums) sub_arrays = set() # generate all combinations of subarray for start in range(n): cnt = 0 temp = '' for i in range(start, n): if nums[i]%p == 0: cnt+=1 temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format if cnt>k: # check for termination break sub_arrays.add(temp) return len(sub_arrays)
class Solution { public int countDistinct(int[] nums, int k, int p) { int n = nums.length; // we are storing hashcode for all the substrings so that we can compare them faster. // main goal is to avoid entire sub array comparision using hashcode. Set<Long> ways = new HashSet<>(); for(int i = 0; i < n; i++) { int cnt = 0; long hc = 1; // this is the running hashcode for sub array [i...j] for(int j = i; j < n; j++) { hc = 199L * hc + nums[j]; // updating running hashcode, since we nums are <=200, we shall consider a prime near 200 to avoid collision if(nums[j] % p == 0) cnt++; if(cnt <= k) { // if current subarray [i...j] is valid, add its hashcode in our storage. ways.add(hc); } } } return ways.size(); } }
class Solution { public: int countDistinct(vector<int>& nums, int k, int p) { int n=nums.size(); set<vector<int>>ans; int i,j; for(i=0;i<n;i++) { vector<int>tt; int ct=0; for(j=i;j<n;j++) { tt.push_back(nums[j]); if(nums[j]%p==0) ++ct; if(ct>k) break; ans.insert(tt); } } return ans.size(); } };
var countDistinct = function(nums, k, p) { let ans = []; let rec = (index,k,p,nums,ans,curr) => { let val = nums[index]; let check = val%p; let isdiv = false; if(check == 0) isdiv=true; if(index == nums.length) { if(curr.length>0){ ans.push(curr.join(",")); } return; } //take conditions if(isdiv && k==0){ ans.push(curr.join(",")); } else if(isdiv){ curr.push(val) rec(index+1,k-1,p,nums,ans,curr); curr.pop() } else { curr.push(val) rec(index+1,k,p,nums,ans,curr); curr.pop() } //non take conditions if(curr.length == 0){ rec(index+1,k,p,nums,ans,curr); } else { ans.push(curr.join(",")); } } rec(0,k,p,nums,ans,[]); let set = new Set(ans); return set.size };
K Divisible Elements Subarrays
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7. &nbsp; Example 1: Input: packages = [2,3,5], boxes = [[4,8],[2,8]] Output: 6 Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box. The total waste is (4-2) + (4-3) + (8-5) = 6. Example 2: Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]] Output: -1 Explanation: There is no box that the package of size 5 can fit in. Example 3: Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]] Output: 9 Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes. The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9. &nbsp; Constraints: n == packages.length m == boxes.length 1 &lt;= n &lt;= 105 1 &lt;= m &lt;= 105 1 &lt;= packages[i] &lt;= 105 1 &lt;= boxes[j].length &lt;= 105 1 &lt;= boxes[j][k] &lt;= 105 sum(boxes[j].length) &lt;= 105 The elements in boxes[j] are distinct.
class Solution: def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: # prefix sum to save time acc = [0] + [*accumulate(packages)] packages.sort() ans = float('inf') for box in boxes: tmp = 0 # deal with smallest box first box.sort() # record number of packages already dealt with start = 0 for b in box: loc = bisect.bisect(packages, b) if loc == 0: continue tmp += b * (loc - start) - (acc[loc] - acc[start]) # all are packaged if loc == len(packages): ans = min(ans, tmp) break start = loc return ans % (10 **9+7) if ans != float('inf') else -1
class Solution { public int minWastedSpace(int[] packages, int[][] boxes) { Arrays.sort(packages); int n = packages.length, k = -1; long sum = 0, ans = Long.MAX_VALUE; int[] pos = new int[100001]; for (int i = 0; i < 100001; i++){ // precompute jump position. while(k < n - 1 && packages[k+1] == i){ sum += packages[++k]; } pos[i] = k; } for (int[] b : boxes){ Arrays.sort(b); long cost = -sum; k=-1; for (int i = 0; i < b.length; i++){ if (pos[b[i]] >= 0){ int cnt = pos[b[i]]-k; cost += 1L * cnt * b[i]; k=pos[b[i]]; } } ans = k == n-1? Math.min(cost, ans) : ans; } return ans == Long.MAX_VALUE? -1 : (int)(ans % (int)(1e9+7)); } }
class Solution { public: #define MOD 1000000007 #define ll long long int minWastedSpace(vector<int>& packages, vector<vector<int>>& boxes) { int n = packages.size(); int m = boxes.size(); sort(packages.begin(), packages.end()); vector<ll> pack(n + 1); pack[0] = 0; for(int i = 0;i<n; i++){ pack[i + 1] = packages[i]; pack[i + 1] += pack[i]; } ll ans = 1e18; bool mf = false; for(int i = 0; i<m; i++){ vector<int> opt = boxes[i]; sort(opt.begin(), opt.end()); int back = 0; ll temp = 0; bool flag = false; ll bag ; for(int j = 0; j<(int)opt.size(); j++){ bag = opt[j]; auto it = upper_bound(packages.begin(), packages.end(), bag); auto it1 = it; int idx ; if(it != packages.begin()){ it--; idx = it - packages.begin(); ll num_packs = idx + 1 - back; ll pack_sum = pack[idx + 1] - pack[back]; back = idx + 1; temp += (num_packs*bag - pack_sum); } if(it1 == packages.end()){ flag = true; break; } } if(flag){ ans = min(ans, temp); mf = true; } } if(!mf) return -1; if(ans == 1e18) return -1; ans = ans % MOD; return ans; } };
/** * @param {number[]} packages * @param {number[][]} boxes * @return {number} */ var minWastedSpace = function(packages, boxes) { let count=0,b,minWastage,totalPackagesSize=0n,minBoxesAreaForAnySupplier=BigInt(Number.MAX_SAFE_INTEGER),boxesArea=0n,p,coverdPackagesIndex,totalBoxesAreaForSupplier; packages.sort(function(a,b){return a-b}); for(let i=0;i<packages.length;i++){ totalPackagesSize+=BigInt(packages[i]); } for(let i=0;i<boxes.length;i++){ boxes[i].sort(function(a,b){return a-b}); p=0; totalBoxesAreaForSupplier=0n; if(boxes[i][boxes[i].length-1]<packages[packages.length-1]){//This supplier is not big enough box for the largest package, hence this supplier can't be used. continue; } for(let b=0;b<boxes[i].length;b++){ coverdPackagesIndex = binaryLowerBound(packages,p,packages.length-1,boxes[i][b]); if(coverdPackagesIndex!==-1){ totalBoxesAreaForSupplier+=BigInt(boxes[i][b])*BigInt(coverdPackagesIndex-p+1); p=coverdPackagesIndex+1; if(p===packages.length){ break; } } } if(p===packages.length){//Check if the current supplier was able to pack all the packages. if(totalBoxesAreaForSupplier<minBoxesAreaForAnySupplier){ minBoxesAreaForAnySupplier = totalBoxesAreaForSupplier; } } } if(minBoxesAreaForAnySupplier!==BigInt(Number.MAX_SAFE_INTEGER)){ return (minBoxesAreaForAnySupplier-totalPackagesSize)%1000000007n; }else{ return -1; } function binaryLowerBound(arr,left,right,key){ let mid,ans=-1; while(left<=right){ mid = left + Math.floor((right-left)/2); if(arr[mid]<=key){ ans=mid; left=mid+1; }else{ right=mid-1; } } return ans; } };
Minimum Space Wasted From Packaging
A cinema&nbsp;has n&nbsp;rows of seats, numbered from 1 to n&nbsp;and there are ten&nbsp;seats in each row, labelled from 1&nbsp;to 10&nbsp;as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8]&nbsp;means the seat located in row 3 and labelled with 8&nbsp;is already reserved. Return the maximum number of four-person groups&nbsp;you can assign on the cinema&nbsp;seats. A four-person group&nbsp;occupies four&nbsp;adjacent seats in one single row. Seats across an aisle (such as [3,3]&nbsp;and [3,4]) are not considered to be adjacent, but there is an exceptional case&nbsp;on which an aisle split&nbsp;a four-person group, in that case, the aisle split&nbsp;a four-person group in the middle,&nbsp;which means to have two people on each side. &nbsp; Example 1: Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]] Output: 4 Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. Example 2: Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]] Output: 2 Example 3: Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]] Output: 4 &nbsp; Constraints: 1 &lt;= n &lt;= 10^9 1 &lt;=&nbsp;reservedSeats.length &lt;= min(10*n, 10^4) reservedSeats[i].length == 2 1&nbsp;&lt;=&nbsp;reservedSeats[i][0] &lt;= n 1 &lt;=&nbsp;reservedSeats[i][1] &lt;= 10 All reservedSeats[i] are distinct.
class Solution(object): def maxNumberOfFamilies(self, n, reservedSeats): """ :type n: int :type reservedSeats: List[List[int]] :rtype: int """ d = defaultdict(set) for row,seat in reservedSeats: d[row].add(seat) def row(i): a1 = not set((2,3,4,5)).intersection(d[i]) a2 = not set((6,7,8,9)).intersection(d[i]) if a1 and a2: return 2 if a1 or a2: return 1 return 1 if not set((4,5,6,7)).intersection(d[i]) else 0 return sum((row(i) for i in d.keys())) + (n-len(d)) * 2
class Solution { public int maxNumberOfFamilies(int n, int[][] reservedSeats) { Map<Integer, int[]> seats = new HashMap<>(); int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots for (int[] seat: reservedSeats) { int row = seat[0]; int col = seat[1]; int[] slots = seats.getOrDefault(row, new int[3]); if (col >= 2 && col <= 5) { // left slot slots[0] = 1; } if (col >= 4 && col <= 7) { // middle slot slots[1] = 1; } if (col >= 6 && col <= 9) { // right slot slots[2] = 1; } seats.put(seat[0], slots); } for (int[] slots: seats.values()) { int taken = slots[0] + slots[2]; if (taken == 2) { // both slots at either ends are taken if (slots[1] == 0) { // check if middle slot not taken availableSlots--; // reduce availableslots by 1 since middle slot is available } else { availableSlots -= 2; // entire row not available - reduce by 2 } } else if (taken == 1) { // one of the slots at either ends are taken availableSlots--; // reduce by 1 since either side of the slots not available } else { continue; // entire row is available - no need to reduce the available slots } } return availableSlots; } }
class Solution { public: int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) { unordered_map<int, vector<int>> o; for (auto r : reservedSeats) { o[r[0]].push_back(r[1]); } int ans = 2 * (n - o.size()); // seats with no occupancy directly adding 2 // if we iterate from 1 to n (10 ^ 9) we cross time limit for (auto p : o) { // get reserved seats vector<int> seats = p.second; int occupied_mask = 0; // representing occupied seats as bits for (int s : seats) { if (s > 1 && s < 10) { occupied_mask += (int)pow(2, 10 - s); } } // checking 3 seating configurations int masks[3] = {480, 120, 30}; int row_ans = 0; bool res1 = (masks[0] & occupied_mask) == 0; bool res2 = (masks[1] & occupied_mask) == 0; bool res3 = (masks[2] & occupied_mask) == 0; // if all 3 configurations are empty, 2 families // if either one of them are empty, 1 family if (res1 && res2 && res3) row_ans += 2; else if (res1 || res2 || res3) row_ans += 1; ans += row_ans; } return ans; } };
/** * @param {number} n * @param {number[][]} reservedSeats * @return {number} */ var maxNumberOfFamilies = function(n, reservedSeats) { let a,b,c,reservedMap={},ans=n*2,takenB={}; for(let i=0;i<reservedSeats.length;i++){ let resverd = reservedSeats[i]; let row = resverd[0]; if(reservedMap[row]===undefined){ reservedMap[row]={} } if(2<=resverd[1] && resverd[1]<=3 && reservedMap[row]['a']===undefined){//a is blocked now ans--; reservedMap[row]['a']=true; if(reservedMap[row]['c']===true && reservedMap[row]['b']===undefined){ takenB[resverd[0]]=true; ans++;//add for b } }else if(8<=resverd[1] && resverd[1]<=9 && reservedMap[row]['c']===undefined){//c is blocked now ans--; reservedMap[row]['c']=true; if(reservedMap[row]['a']===true && reservedMap[row]['b']===undefined){ takenB[resverd[0]]=true; ans++;//add for b } }else if(4<=resverd[1] && resverd[1]<=5){//b is blocked now if(reservedMap[row]['a']===undefined){ ans--; reservedMap[row]['a']=true; } if(takenB[resverd[0]]===true){ ans--;//substract for b takenB[resverd[0]]=false; } reservedMap[row]['b']=true; }else if(6<=resverd[1] && resverd[1]<=7){//b is blocked now if(reservedMap[row]['c']===undefined){ ans--; reservedMap[row]['c']=true; } if(takenB[resverd[0]]===true){ ans--;//substract for b takenB[resverd[0]]=false; } reservedMap[row]['b']=true; } } return ans; };
Cinema Seat Allocation
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. For example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved. &nbsp; Example 1: Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]] Output: 8 Explanation:&nbsp;We assign students to mentors in the following way: - student 0 to mentor 2 with a compatibility score of 3. - student 1 to mentor 0 with a compatibility score of 2. - student 2 to mentor 1 with a compatibility score of 3. The compatibility score sum is 3 + 2 + 3 = 8. Example 2: Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]] Output: 0 Explanation: The compatibility score of any student-mentor pair is 0. &nbsp; Constraints: m == students.length == mentors.length n == students[i].length == mentors[j].length 1 &lt;= m, n &lt;= 8 students[i][k] is either 0 or 1. mentors[j][k] is either 0 or 1.
import heapq from collections import defaultdict class Solution: def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int: m, n = len(students), len(students[0]) def hamming(student, mentor): return sum([int(student[i] != mentor[i]) for i in range(n)]) pq = [(0, 0, '0'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status) optimal = defaultdict(lambda:float('inf')) while pq: # O(V) cost, i, mentor_status = heapq.heappop(pq) # O(logV) # early stopping with termination condition if i == m: return m * n - cost # generate successors. The next student to be assigned is at index i for j, mentor in enumerate(mentors): # O(m) if mentor_status[j] != '1': new_cost = cost + hamming(students[i], mentor) new_mentor_status = mentor_status[:j] + '1' + mentor_status[j+1:] # update optimal cost if a new successor appears with lower cost to the same node if new_cost < optimal[(i+1, new_mentor_status)]: optimal[(i+1, new_mentor_status)] = new_cost heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV) return 0
class Solution { int max; public int maxCompatibilitySum(int[][] students, int[][] mentors) { boolean[] visited = new boolean[students.length]; helper(visited, students, mentors, 0, 0); return max; } public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos, int score){ if(pos >= students.length){ max = Math.max(max, score); return; } for(int i = 0; i < mentors.length; i++) if(!visited[i]){ visited[i] = true; helper(visited, students, mentors, pos + 1, score + score(students[pos], mentors[i])); visited[i] = false; } } public int score(int[] a, int[] b){ int count = 0; for(int i = 0; i < b.length; i++) if(a[i] == b[i]) count += 1; return count; } }
class Solution { // Calculating compatibility scores of ith student and jth mentor int cal(int i,int j,vector<vector<int>>& arr1,vector<vector<int>>& arr2){ int cnt=0; for(int k=0;k<arr1[0].size();k++){ if(arr1[i][k]==arr2[j][k]){ cnt++; } } return cnt; } int helper(int i,int m,vector<vector<int>>& arr1,vector<vector<int>>& arr2,vector<bool>& vis){ if(i==m){ return 0; } int ans = 0; for(int j=0;j<m;j++){ if(!vis[j]){ vis[j]=1; ans = max(ans,cal(i,j,arr1,arr2) + helper(i+1,m,arr1,arr2,vis)); vis[j]=0; // Backtracking } } return ans; } public: int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) { int m = students.size(); vector<bool> vis(m,0); // To keep track of which mentor is already paired up return helper(0,m,students,mentors,vis); } };
var maxCompatibilitySum = function(students, mentors) { const m = students.length; const n = students[0].length; let max = 0; dfs(0, (1 << m) - 1, 0); return max; function dfs(studentIdx, bitmask, scoreTally) { if (studentIdx === m) { max = Math.max(max, scoreTally); return; } for (let mentorIdx = 0; mentorIdx < m; ++mentorIdx) { if (bitmask & (1 << mentorIdx)) { const matchScore = hammingDistance(students[studentIdx], mentors[mentorIdx]); const setMask = bitmask ^ (1 << mentorIdx); dfs(studentIdx + 1, setMask, scoreTally + matchScore); } } return; } function hammingDistance(studentsAnswers, mentorsAnswers) { let matches = 0; for (let j = 0; j < n; ++j) { if (studentsAnswers[j] === mentorsAnswers[j]) ++matches; } return matches; } };
Maximum Compatibility Score Sum
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. &nbsp; Example 1: Input: nums = [1,2,3,2] Output: 4 Explanation: The unique elements are [1,3], and the sum is 4. Example 2: Input: nums = [1,1,1,1,1] Output: 0 Explanation: There are no unique elements, and the sum is 0. Example 3: Input: nums = [1,2,3,4,5] Output: 15 Explanation: The unique elements are [1,2,3,4,5], and the sum is 15. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 1 &lt;= nums[i] &lt;= 100
class Solution: def sumOfUnique(self, nums: List[int]) -> int: hashmap = {} for i in nums: if i in hashmap.keys(): hashmap[i] += 1 else: hashmap[i] = 1 sum = 0 for k, v in hashmap.items(): if v == 1: sum += k return sum
class Solution { public int sumOfUnique(int[] nums) { int res = 0; Map<Integer,Integer> map = new HashMap<>(); for(int i = 0;i<nums.length;i++){ map.put(nums[i],map.getOrDefault(nums[i],0)+1); if(map.get(nums[i]) == 1)res+=nums[i]; else if(map.get(nums[i]) == 2)res-=nums[i]; } return res; } }
class Solution { public: int sumOfUnique(vector<int>& nums) { int sum=0; map<int,int>mp; for(auto x:nums) mp[x]++; for(auto m:mp) { if(m.second==1) sum+=m.first; } return sum; } };
var sumOfUnique = function(nums) { let obj = {} let sum = 0 // count frequency of each number for(let num of nums){ if(obj[num] === undefined){ sum += num obj[num] = 1 }else if(obj[num] === 1){ sum -= num obj[num] = -1 } } return sum };
Sum of Unique Elements
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity. void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity. int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty. int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty. &nbsp; Example 1: Input ["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"] [[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []] Output [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1] Explanation: DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 D.push(1); D.push(2); D.push(3); D.push(4); D.push(5); // The stacks are now: 2 4 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 2. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.push(20); // The stacks are now: 20 4 1 3 5 ﹈ ﹈ ﹈ D.push(21); // The stacks are now: 20 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 20. The stacks are now: 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(2); // Returns 21. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.pop() // Returns 5. The stacks are now: 4 1 3 ﹈ ﹈ D.pop() // Returns 4. The stacks are now: 1 3 ﹈ ﹈ D.pop() // Returns 3. The stacks are now: 1 ﹈ D.pop() // Returns 1. There are no stacks. D.pop() // Returns -1. There are still no stacks. &nbsp; Constraints: 1 &lt;= capacity &lt;= 2 * 104 1 &lt;= val &lt;= 2 * 104 0 &lt;= index &lt;= 105 At most 2 * 105 calls will be made to push, pop, and popAtStack.
class DinnerPlates: def __init__(self, capacity: int): self.heap = [] self.stacks = [] self.capacity = capacity def push(self, val: int) -> None: if self.heap: index = heapq.heappop(self.heap) if index < len(self.stacks): self.stacks[index].append(val) else: self.push(val) elif self.stacks: lastStack = self.stacks[-1] if len(lastStack) != self.capacity: lastStack.append(val) else: stack = deque() stack.append(val) self.stacks.append(stack) else: stack = deque() stack.append(val) self.stacks.append(stack) def pop(self) -> int: while self.stacks: lastStack = self.stacks[-1] if lastStack: val = lastStack.pop() if not lastStack: self.stacks.pop() return val else: self.stacks.pop() return -1 def popAtStack(self, index: int) -> int: if index == len(self.stacks) - 1: return self.pop() if index < len(self.stacks): stack = self.stacks[index] if stack: val = stack.pop() heapq.heappush(self.heap, index) return val return -1 # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = obj.popAtStack(index)
class DinnerPlates { List<Stack<Integer>> stack; PriorityQueue<Integer> leftEmpty; PriorityQueue<Integer> rightNonEmpty; int cap; public DinnerPlates(int capacity) { this.cap = capacity; this.stack = new ArrayList<>(); this.leftEmpty = new PriorityQueue<>(); this.rightNonEmpty = new PriorityQueue<>(Collections.reverseOrder()); stack.add(new Stack<>()); leftEmpty.offer(0); } public void push(int val) { while(!leftEmpty.isEmpty() && stack.get(leftEmpty.peek()).size() == cap) leftEmpty.poll(); if(leftEmpty.isEmpty()) { stack.add(new Stack<>()); leftEmpty.offer(stack.size() - 1); } Stack<Integer> s = stack.get(leftEmpty.peek()); if(s.isEmpty()) rightNonEmpty.offer(leftEmpty.peek()); s.push(val); } public int pop() { while(!rightNonEmpty.isEmpty() && stack.get(rightNonEmpty.peek()).isEmpty()) rightNonEmpty.poll(); if(rightNonEmpty.isEmpty()) { return -1; } Stack<Integer> s = stack.get(rightNonEmpty.peek()); if(s.size() == cap) leftEmpty.offer(rightNonEmpty.peek()); return s.pop(); } public int popAtStack(int index) { if(index >= stack.size()) return -1; Stack<Integer> s = stack.get(index); if(s.isEmpty()) return -1; if(s.size() == cap) leftEmpty.offer(index); return s.pop(); } } /** * Your DinnerPlates object will be instantiated and called as such: * DinnerPlates obj = new DinnerPlates(capacity); * obj.push(val); * int param_2 = obj.pop(); * int param_3 = obj.popAtStack(index); */
class DinnerPlates { public: map<int,stack<int>>mp; set<int>empty; int cap; DinnerPlates(int capacity) { this->cap=capacity; } void push(int val) { if(empty.size()==0) { empty.insert(mp.size()); } mp[*empty.begin()].push(val); if(mp[*empty.begin()].size()==cap) { empty.erase(empty.begin()); } } int pop() { if(mp.size()==0) { return -1; } int index=mp.rbegin()->first; int val=mp[index].top(); mp[index].pop(); empty.insert(index); if(mp[index].size()==0) { mp.erase(index); } return val; } int popAtStack(int index) { if(mp.size()==0||mp.find(index)==mp.end()) { return -1; } int val=mp[index].top(); mp[index].pop(); empty.insert(index); if(mp[index].size()==0) { mp.erase(index); } return val; } };
/** * @param {number} capacity */ var DinnerPlates = function(capacity) { this.capacity = capacity; this.stacks = []; }; /** * @param {number} val * @return {void} */ DinnerPlates.prototype.push = function(val) { var needNewStack = true for (var i = 0; i < this.stacks.length; i++) { if (this.stacks[i].length < this.capacity) { this.stacks[i].push(val); needNewStack = false; break; } } if (needNewStack) { this.stacks.push([val]); } }; /** * @return {number} */ DinnerPlates.prototype.pop = function() { var val = -1; for (var i = this.stacks.length - 1; i >= 0; i--) { if (this.stacks[i].length > 0) { val = this.stacks[i].pop(); break; } } return val; }; /** * @param {number} index * @return {number} */ DinnerPlates.prototype.popAtStack = function(index) { // console.log(index, this.stacks, ...this.stacks[index]) var val = -1; if (this.stacks[index] && this.stacks[index].length > 0) { val = this.stacks[index].pop() } return val; }; /** * Your DinnerPlates object will be instantiated and called as such: * var obj = new DinnerPlates(capacity) * obj.push(val) * var param_2 = obj.pop() * var param_3 = obj.popAtStack(index) */
Dinner Plate Stacks
Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return an array of the k parts. &nbsp; Example 1: Input: head = [1,2,3], k = 5 Output: [[1],[2],[3],[],[]] Explanation: The first element output[0] has output[0].val = 1, output[0].next = null. The last element output[4] is null, but its string representation as a ListNode is []. Example 2: Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 Output: [[1,2,3,4],[5,6,7],[8,9,10]] Explanation: The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. &nbsp; Constraints: The number of nodes in the list is in the range [0, 1000]. 0 &lt;= Node.val &lt;= 1000 1 &lt;= k &lt;= 50
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: length = 0 cur = head while cur: length += 1 cur = cur.next # DON'T do following since this makes head become null # while head: # length += 1 # head = head.next # calculate the base size and the number of parts contain extra number size, extra = length // k, length % k # create empty list to store split parts res = [[] for _ in range(k)] # use two ptrs to split parts prev, cur = None, head for i in range(k): res[i] = cur # if this part contains extra number, it has (size+1) number for j in range(size + (1 if extra > 0 else 0)): prev, cur = cur, cur.next if prev: prev.next = None extra -= 1 return res
class Solution { public ListNode[] splitListToParts(ListNode head, int k) { ListNode[] arr=new ListNode[k]; if(k<2 || head==null || head.next==null){ arr[0]=head; return arr; } ListNode temp=head; int len=1; while(temp.next!=null){ len++; temp=temp.next; } int partition= len/k; //no of part 3 int extra=len%k; //extra node 1 0 ListNode curr=head; ListNode prev=null; int index=0; while(head!=null){ arr[index++]=curr; for(int i=0; i<partition && curr!=null ; i++){ prev=curr; curr=curr.next; } if(extra>0){ prev=curr; curr=curr.next; extra--; } head=curr; prev.next=null; } return arr; } }
class Solution { public: vector<ListNode*> splitListToParts(ListNode* head, int k) { vector<ListNode*>ans; int len=0; ListNode*temp=head; while(temp!=NULL) len++,temp=temp->next; int y=len/k , z=len%k; while(head !=NULL) { ans.push_back(head); int count=1; while(head!=NULL && count<y) head=head->next,count++; if(z && y) { head=head->next;z--; } if(head==NULL) continue; ListNode*temp=head->next; head->next=NULL; head=temp; } while(ans.size()<k) { ans.push_back(NULL); } return ans; } };
var splitListToParts = function(head, k) { let length = 0, current = head, parts = []; while (current) { length++; current = current.next; } let base_size = Math.floor(length / k), extra = length % k; current = head; for (let i = 0; i < k; i++) { let part_size = base_size + (extra > 0 ? 1 : 0); let part_head = null, part_tail = null; for (let j = 0; j < part_size; j++) { if (!part_head) { part_head = part_tail = current; } else { part_tail.next = current; part_tail = part_tail.next; } if (current) { current = current.next; } } if (part_tail) { part_tail.next = null; } parts.push(part_head); extra = Math.max(extra - 1, 0); } return parts; };
Split Linked List in Parts
Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. &nbsp; Example 1: Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4 Output: 2 Explanation: Substring "aab" has 2 ocurrences in the original string. It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). Example 2: Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3 Output: 2 Explanation: Substring "aaa" occur 2 times in the string. It can overlap. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 1 &lt;= maxLetters &lt;= 26 1 &lt;= minSize &lt;= maxSize &lt;= min(26, s.length) s consists of only lowercase English letters.
# 0 1 2 3 # a a a a # l # r #ref: https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/457577/C%2B%2B-Greedy-approach-%2B-Sliding-window-O(n). #Intuition #if a string have occurrences x times, any of its substring must also appear at least x times #there must be a substring of length minSize, that has the most occurrences #so that we just need to count the occurrences of all substring with length minSize #Explanation #find the maximum occurrences of all substrings with length = minSize class Solution: #T=O(n), S=O(n) #use sliding window to lock down substrings to minSize limit (greedy approach) #then use a counter to count the occurences of valid substrings def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: #dict to store valid substrings and their respective occurences count d = defaultdict(int) #find longest substrings that has k unique chars #counter dict for char count and make sure unique char count is not exceeded counter = defaultdict(int) #init left and right pointers of sliding window r = l = 0 #iterate right pointer while r < len(s): counter[s[r]] += 1 #invalid window found, so make it valid again #len of window is greater than minSize while (r - l + 1) > minSize: counter[s[l]] -= 1 #remove the key from dict for unique char count if it becomes zero if counter[s[l]] == 0: del counter[s[l]] #increment the left pointer to make it a valid window l += 1 #valid window size (minSize) and unique char count is lesser than or equal to maxLetters if r - l + 1 == minSize and len(counter) <= maxLetters: #increment count of the occurence of the substring d[s[l:r+1]] += 1 #make sure to update right pointer only after an iteration r += 1 #return the count of substring with max occurence #edge case with no substring return max(d.values()) if d else 0
class Solution { public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { Map<String,Integer> count = new HashMap<>(); int ans = 0; int n = s.length(); for(int i=0;i+minSize-1<n;i++){ String y = s.substring(i,i+minSize); count.put(y,count.getOrDefault(y,0)+1); int unique = uniqueCharactersInString(y); if(unique<=maxLetters){ ans = Math.max(ans,count.get(y)); } } //System.out.println(count); return ans; } int uniqueCharactersInString(String y){ Set<Character> hs = new HashSet<>(); for(int j=0;j<y.length();j++) hs.add(y.charAt(j)); return hs.size(); } }
class Solution { public: int maxFreq(string s, int maxLetters, int minSize, int maxSize) { int i, j, k, ans = 0, res, n = s.length(); string temp; unordered_map<char, int> st; unordered_map<string, int> mp; i = 0, j = 0; while(i <= n - minSize && j < n) { temp += s[j]; st[s[j]] += 1;; if(temp.length() == minSize) { if(st.size() <= maxLetters) mp[temp] += 1; i += 1; st[temp[0]] -= 1; if(st[temp[0]] == 0) st.erase(temp[0]); temp.erase(temp.begin()); } j += 1; } for(auto el : mp) ans = max(ans, el.second); return ans; } };
var maxFreq = function(s, maxLetters, minSize, maxSize) { let output = 0; let left = 0, right = 0; let map = {}; let map2 = {}; let count = 0; while(right < s.length){ if(map[s[right]] === undefined){ // adding letters to map to keep track of occurences (count) map[s[right]] = 1; count++; } else { if(map[s[right]] === 0){ count++; } map[s[right]]++; } if(right - left + 1 > minSize) { // once over minSize removing occurence of left most letter from map and adjusting count map[s[left]]--; if(map[s[left]] < 1){ count--; } left++; } if(right - left + 1 >= minSize && count <= maxLetters){ map2[s.substring(left, right + 1)] = (map2[s.substring(left, right + 1)] || 0) + 1; // if subsitrng meets constraints of size and count add to map2; } right++; } Object.entries(map2).map(([key, val]) => output = Math.max(output, val)); // get largest value in map2 return output; };
Maximum Number of Occurrences of a Substring
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word. &nbsp; Example 1: Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 Output: [ &nbsp; &nbsp;"This &nbsp; &nbsp;is &nbsp; &nbsp;an", &nbsp; &nbsp;"example &nbsp;of text", &nbsp; &nbsp;"justification. &nbsp;" ] Example 2: Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 Output: [ &nbsp; "What &nbsp; must &nbsp; be", &nbsp; "acknowledgment &nbsp;", &nbsp; "shall be &nbsp; &nbsp; &nbsp; &nbsp;" ] Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. Example 3: Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 Output: [ &nbsp; "Science &nbsp;is &nbsp;what we", "understand &nbsp; &nbsp; &nbsp;well", &nbsp; "enough to explain to", &nbsp; "a &nbsp;computer. &nbsp;Art is", &nbsp; "everything &nbsp;else &nbsp;we", &nbsp; "do &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;" ] &nbsp; Constraints: 1 &lt;= words.length &lt;= 300 1 &lt;= words[i].length &lt;= 20 words[i] consists of only English letters and symbols. 1 &lt;= maxWidth &lt;= 100 words[i].length &lt;= maxWidth
class Solution: def fullJustify(self, words: List[str], maxwidth: int) -> List[str]: curr = 0 last = [] res = [] for i in words: if curr + len(i) + len(res) <= maxwidth: curr += len(i) res.append(i) else: last.append(res) curr = len(i) res = [i] last.append(res) ans = [] for idx ,row in enumerate(last): x = maxwidth-len("".join(row)) t = len(row)-1 if t == 0: ans.append(row[0] + " "*(x)) elif idx != len(last)-1: spaces = x//t rem = x%t res = row[0] for i in row[1:]: temp = spaces if rem: temp += 1 rem -= 1 res = res + " "*temp + i # print(res, temp) ans.append(res) else: res = row[0] for i in row[1:]: res = res + ' '+i res = res + " "*(maxwidth-len(res)) ans.append(res) return ans
class Solution { public List<String> fullJustify(String[] words, int maxWidth) { List<String> unBalanced = new ArrayList<>(); List<String> balanced = new ArrayList<>(); int numSpaces = 0; StringBuffer sb = new StringBuffer(); //Following code creates a list of unbalanced lines by appending words and 1 space between them for(String word : words){ if(sb.length() == 0){ sb.append(word); }else{ if(sb.length() + 1 + word.length() <= maxWidth){ sb.append(" "+word); }else{ unBalanced.add(sb.toString()); sb = new StringBuffer(word); } } } if(sb.length() >0){ unBalanced.add(sb.toString()); } for(int j = 0; j < unBalanced.size(); j++){ String line = unBalanced.get(j); numSpaces = maxWidth - line.length(); StringBuffer lineB = new StringBuffer(line); //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces if(j == unBalanced.size()-1 || !line.contains(" ")){ int tempSpaces = maxWidth - lineB.length(); while(tempSpaces > 0){ lineB.append(" "); tempSpaces --; } balanced.add(lineB.toString()); continue; }; // The following block checks for each character and appends 1 space during each loop //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word while(numSpaces > 0){ int i = 0; while(i < lineB.length() - 1){ if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){ lineB.insert(i+1, ' '); i++; numSpaces --; if(numSpaces == 0) break; } i++; } } balanced.add(lineB.toString()); } return balanced; } }
class Solution { string preprocessing(string &f, int space, int limit) { int noofspace = limit-f.size()+space; int k = 0; string r = ""; while(space) { int n = noofspace / space; if((noofspace%space) != 0) n += 1; noofspace -= n; while(f[k] != ' ') { r += f[k]; k++; } k++; while(n--) { r += ' '; } space--; } while(k < f.size()) { r += f[k]; k++; } while(noofspace--) r += ' '; return r; } public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> ans; string f = ""; int space = 0; for(string &str : words) { if((f.size() + str.size() + 1) <= maxWidth && f.size() > 0) { f += ' ' + str; space++; } else { if(f.size() > 0){ f = preprocessing(f, space, maxWidth); ans.push_back(f); f = ""; } f += str; space = 0; } } int sz = f.size(); while(sz < maxWidth) { f += ' '; sz++; } ans.push_back(f); return ans; } };
/** * @param {string[]} words * @param {number} maxWidth * @return {string[]} */ var fullJustify = function(words, maxWidth) { if (!words || !words.length) return; const wordRows = []; let wordCols = []; let count = 0; words.forEach((word, i) => { if ((count + word.length + wordCols.length) > maxWidth) { wordRows.push(wordCols); wordCols = []; count = 0; } wordCols.push(word); count += word.length; if (i === words.length - 1) { wordRows.push(wordCols); } }); return wordRows.map((rowWords, i) => justifyText(rowWords, maxWidth, i === wordRows.length - 1)); }; const justifyText = (rowWords, maxWidth, isLastLine) => { let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0); if (rowWords.length === 1) { return rowWords[0] + ' '.repeat(spaces); } if (isLastLine) { spaces -= rowWords.length - 1 return rowWords.join(' ') + ' '.repeat(spaces); } let index = rowWords.length - 1; let justifiedWord = ''; while (rowWords.length > 0) { const repeater = Math.floor(spaces / (rowWords.length - 1)); const word = rowWords.pop(); if (index === 0) { justifiedWord = word + justifiedWord; } else if (index === 1) { justifiedWord = ' '.repeat(spaces) + word + justifiedWord; } else { justifiedWord = ' '.repeat(repeater) + word + justifiedWord; } index--; spaces -= repeater; } return justifiedWord; }
Text Justification
Given an integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left &lt;= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). &nbsp; Example 1: Input ["NumArray", "sumRange", "sumRange", "sumRange"] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] Output [null, 1, -1, -3] Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -105 &lt;= nums[i] &lt;= 105 0 &lt;= left &lt;= right &lt; nums.length At most 104 calls will be made to sumRange.
class NumArray: def __init__(self, nums: List[int]): self.nums, Sum = [], 0 for num in nums: Sum += num self.nums.append(Sum) def sumRange(self, left: int, right: int) -> int: return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]
class NumArray { int [] prefix; public NumArray(int[] nums) { int n = nums.length; prefix = new int[n]; prefix[0] = nums[0]; for(int i = 1; i < n; i++){ prefix[i] = nums[i] + prefix[i - 1]; } } public int sumRange(int left, int right) { if(left == 0){ return prefix[right]; } return prefix[right] - prefix[left - 1]; } }
class NumArray { public: vector<int>arr; NumArray(vector<int>& nums) { arr=nums; } int sumRange(int left, int right) { int sum=0; for(int i=left;i<=right;i++) sum+=arr[i]; return sum; } };
var NumArray = function(nums) { this.nums = nums; }; NumArray.prototype.sumRange = function(left, right) { let sum = 0; for(let i = left; i <= right; i++) sum += this.nums[i] return sum };
Range Sum Query - Immutable
You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. &nbsp; Example 1: Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^" corresponds to bitwise XOR operator. Example 2: Input: n = 4, start = 3 Output: 8 Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. &nbsp; Constraints: 1 &lt;= n &lt;= 1000 0 &lt;= start &lt;= 1000 n == nums.length
class Solution: def xorOperation(self, n: int, start: int) -> int: nums = [start + 2*i for i in range(n)] #generate list of numbers ans = nums[0] for i in range(1,n): ans = ans^nums[i] # XOR operation return ans
class Solution { public int xorOperation(int n, int start) { int nums[]=new int[n]; for(int i=0;i<n;i++) nums[i] = start + 2 * i; for(int i=1;i<n;i++) nums[i] = nums[i-1]^nums[i]; return nums[n-1]; } }
class Solution { public: int xorOperation(int n, int start) { int res = start; for(int i=1 ; i<n ; i++){ res = res ^ (start + 2 * i); } return res; } };
var xorOperation = function(n, start) { let arr = [] for(let i=0; i<n; i++){ arr.push(start+2*i) } return arr.reduce((a,c)=> a^c) };
XOR Operation in an Array
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove. &nbsp; Example 1: Input: beans = [4,1,6,5] Output: 4 Explanation: - We remove 1 bean from the bag with only 1 bean. This results in the remaining bags: [4,0,6,5] - Then we remove 2 beans from the bag with 6 beans. This results in the remaining bags: [4,0,4,5] - Then we remove 1 bean from the bag with 5 beans. This results in the remaining bags: [4,0,4,4] We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that remove 4 beans or fewer. Example 2: Input: beans = [2,10,3,2] Output: 7 Explanation: - We remove 2 beans from one of the bags with 2 beans. This results in the remaining bags: [0,10,3,2] - Then we remove 2 beans from the other bag with 2 beans. This results in the remaining bags: [0,10,3,0] - Then we remove 3 beans from the bag with 3 beans. This results in the remaining bags: [0,10,0,0] We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that removes 7 beans or fewer. &nbsp; Constraints: 1 &lt;= beans.length &lt;= 105 1 &lt;= beans[i] &lt;= 105
class Solution: def minimumRemoval(self, A: List[int]) -> int: return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))
class Solution { public long minimumRemoval(int[] beans) { Arrays.parallelSort(beans); long sum=0,min=Long.MAX_VALUE; int n=beans.length; for(int i:beans) sum+=i; for(int i=0;i<n;i++) { long temp=sum-((n-i+0L)*beans[i]); min=(long)Math.min(min,temp); } return min; } }
class Solution { public: long long minimumRemoval(vector<int>& beans) { long long n = beans.size(); sort(beans.begin(), beans.end()); long long sum = 0; for(int i=0; i<n; i++) { sum += beans[i]; } long long ans = sum; for(int i=0; i<n; i++) { long long curr = sum - (n-i)*beans[i]; if(ans > curr) ans = curr; } return ans; } };
/** * @param {number[]} beans * @return {number} */ // time complexity -> O(NlogN) and Space is O(logN) due to sorting. var minimumRemoval = function(beans) { beans.sort((a, b) => a - b); let frontSum = beans.reduce((sum , a) => sum + a, 0); let backSum = 0; let done = 0; let result = Number.MAX_SAFE_INTEGER; for(let j = beans.length - 1; j >= 0; j--){ frontSum -= beans[j]; count = frontSum + (backSum - (beans[j] * done)); result = Math.min(result, count); done++; backSum += beans[j]; } return result; };
Removing Minimum Number of Magic Beans
You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product. &nbsp; Example 1: Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]] Output: -1 Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. Example 2: Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]] Output: 8 Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8). Example 3: Input: grid = [[1,3],[0,-4]] Output: 0 Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0). &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 15 -4 &lt;= grid[i][j] &lt;= 4
class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache(None) def fn(i, j): """Return maximum & minimum products ending at (i, j).""" if i == 0 and j == 0: return grid[0][0], grid[0][0] if i < 0 or j < 0: return -inf, inf if grid[i][j] == 0: return 0, 0 mx1, mn1 = fn(i-1, j) # from top mx2, mn2 = fn(i, j-1) # from left mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j] return (mx, mn) if grid[i][j] > 0 else (mn, mx) mx, _ = fn(m-1, n-1) return -1 if mx < 0 else mx % 1_000_000_007
class Solution { public class Pair{ long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; Pair(){ } Pair(long min,long max){ this.min=min; this.max=max; } } public int maxProductPath(int[][] grid) { Pair[][] dp=new Pair[grid.length][grid[0].length]; for(int r=grid.length-1;r>=0;r--){ for(int c=grid[0].length-1;c>=0;c--){ if(r==grid.length-1 && c==grid[0].length-1){ dp[r][c]=new Pair(grid[r][c],grid[r][c]); }else{ Pair hor=(c==grid[0].length-1)?new Pair():dp[r][c+1]; Pair ver=(r==grid.length-1)?new Pair():dp[r+1][c]; long min,max; if(grid[r][c]>=0){ max=Math.max(hor.max,ver.max); min=Math.min(hor.min,ver.min); }else{ min=Math.max(hor.max,ver.max); max=Math.min(hor.min,ver.min); } dp[r][c]=new Pair(min*grid[r][c],max*grid[r][c]); } } } int mod=(int)1e9 +7; return dp[0][0].max<0?-1:(int)(dp[0][0].max%mod); } }
const long long MOD = 1e9 + 7; class Solution { public: int maxProductPath(vector<vector<int>>& grid) { long long mx[20][20] = {0}; long long mn[20][20] = {0}; int row = grid.size(), col = grid[0].size(); // Init mx[0][0] = mn[0][0] = grid[0][0]; // Init the row0 and col0 to be the continuous multiply of the elements. for(int i = 1; i < row; i++){ mx[i][0] = mn[i][0] = mx[i - 1][0] * grid[i][0]; } for(int j = 1; j < col; j++){ mx[0][j] = mn[0][j] = mx[0][j - 1] * grid[0][j]; } // DP as the explanation picture shows for(int i = 1; i < row; i++){ for(int j = 1; j < col; j++){ mx[i][j] = max(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]); mn[i][j] = min(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]); } } return mx[row - 1][col - 1] < 0 ? -1 : mx[row - 1][col - 1] % MOD; } };
var maxProductPath = function(grid) { const R = grid.length, C = grid[0].length; if (R === 0 || C === 0) return -1; const mat = [...Array(R)].map(() => [...Array(C)].map(() => new Array(2))); mat[0][0] = [grid[0][0], grid[0][0]]; for (let i = 1; i < R; i++) mat[i][0] = [mat[i-1][0][0]*grid[i][0], mat[i-1][0][1]*grid[i][0]]; for (let i = 1; i < C; i++) mat[0][i] = [mat[0][i-1][0]*grid[0][i], mat[0][i-1][1]*grid[0][i]]; for (let i = 1; i < R; i++) { for (let j = 1; j < C; j++) { const max = Math.max(mat[i-1][j][0], mat[i][j-1][0]), min = Math.min(mat[i-1][j][1], mat[i][j-1][1]); if (grid[i][j] >= 0) mat[i][j] = [max*grid[i][j], min*grid[i][j]]; else mat[i][j] = [min*grid[i][j], max*grid[i][j]]; } } return mat[R-1][C-1][0] >= 0 ? mat[R-1][C-1][0] % (10**9+7) : -1; };
Maximum Non Negative Product in a Matrix
Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. &nbsp; Example 1: Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6. Example 2: Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Explanation: Both "2*3+2" and "2+3*2" evaluate to 8. Example 3: Input: num = "3456237490", target = 9191 Output: [] Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191. &nbsp; Constraints: 1 &lt;= num.length &lt;= 10 num consists of only digits. -231 &lt;= target &lt;= 231 - 1
class Solution: def addOperators(self, num: str, target: int) -> List[str]: s=num[0] q=["+","-","*",""] ans=[] def cal(w): i=1 while i<len(w)-1: if w[i]=='*': q=int(w[i-1])*int(w[i+1]) del w[i+1] del w[i] w[i-1]=q continue i+=2 i=1 while i<len(w)-1: if w[i]=='+': q=int(w[i-1])+int(w[i+1]) del w[i+1] del w[i] w[i-1]=q continue elif w[i]=='-': q=int(w[i-1])-int(w[i+1]) del w[i+1] del w[i] w[i-1]=q continue i+=2 return w def dfs(s,i): nonlocal ans if i==len(num): x='' myl=[] for i in s: if i not in ['+','-','*']: x+=i else: myl.append(int(x)) myl.append(i) x='' myl.append(int(x)) print(myl) a=cal(myl) print(a) if a[0]==target: ans.append(s) return for j in q: dfs(s+j+num[i],i+1) dfs(s,1) return ans
class Solution { String s; List<String>result; int target; public void operator(int i,int prev,long prod,long mid,String exp,List<Long>l){ if(i==l.size()){ if(mid+prod==target) result.add(exp); return; } if(prev==-1){ operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+"*"+l.get(i),l); }else if(prev==1){ operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+"*"+l.get(i),l); }else{ operator(i+1,0,prod*l.get(i),mid,exp+"*"+l.get(i),l); } operator(i+1,-1,0,mid+prod-l.get(i),exp+"-"+l.get(i),l); operator(i+1,1,0,mid+prod+l.get(i),exp+"+"+l.get(i),l); } public void rec(int in,List<Long>l){ if(in==s.length()){ operator(1,1,0,l.get(0),l.get(0)+"",l); return; } if(s.charAt(in)=='0'){ l.add(0L); rec(in+1,l); l.remove(l.size()-1); }else{ for(int i=in;i<s.length();i++){ l.add(Long.parseLong(s.substring(in,i+1))); rec(i+1,l); l.remove(l.size()-1); } } } public List<String> addOperators(String num, int target) { result=new ArrayList<>(); this.s=num; this.target=target; rec(0,new ArrayList<>(30)); return result; } }
class Solution { public: vector<string> res; string s; int target, n; void solve(int it, string path, long long resSoFar, long long prev){ if(it == n){ if(resSoFar == target) res.push_back(path); return; } long long num = 0; string tmp; for(auto j = it; j < n; j++){ if(j > it && s[it] == '0') break; num = num * 10 + (s[j] - '0'); tmp.push_back(s[j]); if(it == 0) solve(j + 1, tmp, num, num); else{ solve(j + 1, path + "+" + tmp, resSoFar + num, num); solve(j + 1, path + '-' + tmp, resSoFar - num, -num); solve(j + 1, path + '*' + tmp, resSoFar - prev + prev * num, prev * num); } } } vector<string> addOperators(string num, int target) { this -> target = target; s = num, n = num.size(); solve(0, "", 0, 0); return res; } };
var addOperators = function(num, target) { let res = []; let i = 0; const helper = (idx, sum, prev, path) => { if(idx >= num.length) { if(sum === target) { res.push(path); } return null; } for(let j = idx; j < num.length; j++) { if(j !== idx && num[idx] === "0") break; let n = Number(num.slice(idx, j+1)); if(idx === 0) { helper(j + 1, sum + n, sum + n, path + n); } else { helper(j + 1, sum + n, n, path + "+" + n); helper(j + 1, sum - n, 0 - n, path + "-" + n); helper(j + 1, sum - prev + (prev * n), prev * n, path + "*" + n); } } } helper(i, 0, 0, ""); return res; };
Expression Add Operators
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city. &nbsp; Example 1: Input: dist = [1,3,4], speed = [1,1,1] Output: 3 Explanation: In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster. After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster. After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster. All 3 monsters can be eliminated. Example 2: Input: dist = [1,1,2,3], speed = [1,1,1,1] Output: 1 Explanation: In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster. After a minute, the distances of the monsters are [X,0,1,2], so you lose. You can only eliminate 1 monster. Example 3: Input: dist = [3,2,4], speed = [5,3,2] Output: 1 Explanation: In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster. After a minute, the distances of the monsters are [X,0,2], so you lose. You can only eliminate 1 monster. &nbsp; Constraints: n == dist.length == speed.length 1 &lt;= n &lt;= 105 1 &lt;= dist[i], speed[i] &lt;= 105
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])): if i > t: return i return len(dist)
class Solution { public int eliminateMaximum(int[] dist, int[] speed) { int n = dist.length; int[] time = new int[n]; for(int i = 0; i < n; i++){ time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]); } Arrays.sort(time); int eliminated = 0; // At i = 0, minute = 0 ( therefore, we can use i in place of minute ) for(int i = 0; i < n; i++){ if(time[i] > i){ // At ith minute, eliminate the first monster arriving after ith minute eliminated++; }else{ break; // Monster reached the city } } return eliminated; } }
class Solution { public: int eliminateMaximum(vector<int>& dist, vector<int>& speed) { priority_queue<double, vector<double>, greater<double>> pq; for(int i = 0; i < dist.size(); ++i) pq.push(ceil((double)dist[i] / speed[i] )); int t = 0; while(pq.size() && pq.top() > t++) pq.pop(); return dist.size() - pq.size(); } };
/** * @param {number[]} dist * @param {number[]} speed * @return {number} */ var eliminateMaximum = function(dist, speed) { let res = 0; let len = dist.length; let map = new Map(); for(let i=0; i<len; i++){ // the last time to eliminate let a = Math.ceil(dist[i] / speed[i]); if(map.has(a)){ let c = map.get(a); c ++; map.set(a, c); }else{ map.set(a, 1); } } let keys = Array.from(map.keys()); keys.sort((a, b) => a-b); // time to eliminate let t = 0; for(let i=0; i<keys.length; i++){ let c = map.get(keys[i]); if(c > keys[i]-t){ res += keys[i]-t; break; }else{ res += c; t += c; } } return res; };
Eliminate Maximum Number of Monsters
Given the root of a binary tree, invert the tree, and return its root. &nbsp; Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: [] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]. -100 &lt;= Node.val &lt;= 100
class Solution(object): def invertTree(self, root): # Base case... if root == None: return root # swapping process... root.left, root.right = root.right, root.left # Call the function recursively for the left subtree... self.invertTree(root.left) # Call the function recursively for the right subtree... self.invertTree(root.right) return root # Return the root...
class Solution { public TreeNode invertTree(TreeNode root) { swap(root); return root; } private static void swap(TreeNode current) { if (current == null) { return; } swap(current.left); swap(current.right); TreeNode temp = current.left; current.left = current.right; current.right = temp; } }
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == NULL) return root; TreeNode* temp = root->left; root->left = root->right; root->right = temp; invertTree(root->left); invertTree(root->right); return root; } };
var invertTree = function(root) { if (!root) return root; [root.left, root.right] = [root.right, root.left]; invertTree(root.right) invertTree(root.left) return root };
Invert Binary Tree
You have n dice and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 1, k = 6, target = 3 Output: 1 Explanation: You throw one die with 6 faces. There is only one way to get a sum of 3. Example 2: Input: n = 2, k = 6, target = 7 Output: 6 Explanation: You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. Example 3: Input: n = 30, k = 30, target = 500 Output: 222616187 Explanation: The answer must be returned modulo 109 + 7. &nbsp; Constraints: 1 &lt;= n, k &lt;= 30 1 &lt;= target &lt;= 1000
class Solution(object): def numRollsToTarget(self, n, k, target): """ :type n: int :type k: int :type target: int :rtype: int """ mem = {} def dfs(i,currSum): if currSum > target: return 0 if i == n: if currSum == target: return 1 return 0 if (i,currSum) in mem: return mem[(i,currSum)] ans = 0 for dicenumber in range(1,k+1): ans += dfs(i+1,currSum+dicenumber) mem[(i,currSum)] = ans return mem[(i,currSum)] return dfs(0,0) % (10**9 + 7)
class Solution { public int numRollsToTarget(int n, int k, int target) { if (target < n || target > n*k) return 0; if (n == 1) return 1; int[][] dp = new int[n+1][n*k+1]; for (int i = 1; i<= k; i++) { dp[1][i] = 1; } int mod = 1000000007; for (int i = 2; i <= n; i++) { for (int j = i; j <= i*k && j <= target; j++) { for (int x = 1; x <= k; x++) { if (j-x >= 1) { dp[i][j] += dp[i-1][j-x]; if (dp[i][j] >= mod) { dp[i][j] %= mod; } } } } } return dp[n][target]%mod; } }
class Solution { public: int dp[31][1001]; Solution(){ memset(dp,-1,sizeof(dp)); } int help(int dno,int &tdice,int &tf,int target){ if(target<0 or dno>tdice) return 0; if(target==0 and dno==tdice) { return 1; } if(dp[dno][target]!=-1) return dp[dno][target]; int ans=0; for(int i=1;i<=tf;i++){ ans=(ans%1000000007+help(dno+1,tdice,tf,target-i)%1000000007)%1000000007; } return dp[dno][target]=ans; } int numRollsToTarget(int n, int k, int target) { return help(0,n,k,target); } };
var numRollsToTarget = function(n, k, target) { if (n > target || n * k < target) return 0 //target is impossible to reach let arr = new Array(k).fill(1), depth = n //start the first layer of Pascal's N-ary Triangle. while (depth > 1) { //more layers of Triangle to fill out tempArr = [] //next layer of triangle. not done in place as previous layer's array values are needed for (let i = 0; i < arr.length + k - 1 && i <= target - n; i++) { //looping is bounded by size of next layer AND how much data we actually need let val = ((tempArr[i - 1] || 0) + (arr[i] || 0) - (arr[i - k] || 0)) % (1000000007) //current index value is the sum of K number of previous layer's values, once we hit K we add next and subtract last so we don't have to manually add all K values tempArr.push(val) } arr = tempArr depth -= 1 } let ans = arr[target - n] //answer will be in target - nth index return ans < 0 ? ans + 1000000007 : ans };
Number of Dice Rolls With Target Sum
Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c &lt;= a and b &lt;= d. Return the number of remaining intervals. &nbsp; Example 1: Input: intervals = [[1,4],[3,6],[2,8]] Output: 2 Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. Example 2: Input: intervals = [[1,4],[2,3]] Output: 1 &nbsp; Constraints: 1 &lt;= intervals.length &lt;= 1000 intervals[i].length == 2 0 &lt;= li &lt; ri &lt;= 105 All the given intervals are unique.
class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key = lambda x: (x[0], -x[1])) current, count = intervals[0], 1 for i in range(1, len(intervals)): if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]: continue current = intervals[i] count += 1 return count # time and space complexity # time: O(nlog(n)) # space: O(1)
class Solution { public int removeCoveredIntervals(int[][] intervals) { if(intervals == null || intervals.length == 0) return 0; Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0])); int c = intervals[0][0], d = intervals[0][1]; int ans = intervals.length; for(int i=1;i<intervals.length;i++){ int a = intervals[i][0], b = intervals[i][1]; if(c<=a && b<=d) ans--; else { c = a; d = b; } } return ans; } }
class Solution { public: int removeCoveredIntervals(vector<vector<int>>& intervals) { int cnt = 0, last = INT_MIN; sort(intervals.begin(), intervals.end(), [] (const vector<int>& v1, const vector<int>& v2) { if(v1[0] != v2[0]) return v1[0] < v2[0]; else return v1[1] > v2[1]; }); for(int i=0; i<intervals.size(); i++) { if(intervals[i][1] <= last) ++cnt; if(intervals[i][1] > last) last = intervals[i][1]; } return intervals.size()-cnt; } };
var removeCoveredIntervals = function(intervals) { intervals.sort((a,b)=> a[0]-b[0] || b[1]-a[1]); let overlap=0; for (i=1,prev=0; i<intervals.length; i++) // if ((intervals[prev][0] <= intervals[i][0]) //no need to check, already done in sort // && (intervals[prev][1] >= intervals[i][1])) if (intervals[prev][1] >= intervals[i][1]) // just look at 2nd index overlap++ // add to skipped elements else prev=i; // didn't overlap, so we can advance our previous element return intervals.length-overlap; };
Remove Covered Intervals
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left &lt;= x &lt; right. Implement the RangeModule class: RangeModule() Initializes the object of the data structure. void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked. boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise. void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right). &nbsp; Example 1: Input ["RangeModule", "addRange", "removeRange", "queryRange", "queryRange", "queryRange"] [[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]] Output [null, null, null, true, false, true] Explanation RangeModule rangeModule = new RangeModule(); rangeModule.addRange(10, 20); rangeModule.removeRange(14, 16); rangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked) rangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation) &nbsp; Constraints: 1 &lt;= left &lt; right &lt;= 109 At most 104 calls will be made to addRange, queryRange, and removeRange.
from bisect import bisect_left as bl, bisect_right as br class RangeModule: def __init__(self): self._X = [] def addRange(self, left: int, right: int) -> None: # Main Logic # If idx(left) or idx(right) is odd, it's in a interval. So don't add it. # If idx(left) or idx(right) is even, it's not in any interval. So add it as new interval # Slice array[idx(left) : idx(right)] # 1) both odd: Nothing is added. Merge all middle intervals. # 2) both even: Add new intervals. Merge all middle intervals # 3) idx(left) is even: update start point of next interval with left # 4) idx(right) is even: update end point of previous interval with right # Bisect_left vs. Bisect_right # left need to proceed all interval closing at left, so use Bisect_left # right need to go after all interval openning at right, so use Bisect_right i, j = bl(self._X, left), br(self._X, right) self._X[i : j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0) def queryRange(self, left: int, right: int) -> bool: # Main logic # If idx of left/right is odd, it's in a interval. Else it's not. # If idx of left&right is the same, they're in the same interval # Bisect_left vs. Bisect_right # [start, end). Start is included. End is not. # so use bisect_right for left # so use bisect_left for right i, j = br(self._X, left), bl(self._X, right) return i == j and i % 2 == 1 def removeRange(self, left: int, right: int) -> None: # Main Logic # If idx(left) is odd, the interval that contains left need to change end point to left # If idx(right) is odd, the interval that contains right need to change start point to right # Else, everything from idx(left) to idx(right) is removed. Nothing is changed. # Bisect_left vs. Bisect_right # Same as addRange i, j = bl(self._X, left), br(self._X, right) self._X[i : j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)
class RangeModule { TreeMap<Integer, Integer> map; public RangeModule() { map = new TreeMap<>(); } public void addRange(int left, int right) { // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of right. Like this: // [left, right) // [l1, r1) [l2, r2) // Note: l2 could be the same as l1, so they are either both null or both non-null Integer l1 = map.floorKey(left); Integer l2 = map.floorKey(right); // try to visualize each case, and what to do based on r1 if (l1 == null && l2 == null) { map.put(left, right); } else if (l1 != null && map.get(l1) >= left) { map.put(l1, Math.max(right, map.get(l2))); // r2 will always be greater than r1, so no need to check r1 } else { map.put(left, Math.max(right, map.get(l2))); } // we don't want to remove the range starts at left, so left should be exclusive. // but we want to remove the one starts at right, so right should be inclusive. map.subMap(left, false, right, true).clear(); } public boolean queryRange(int left, int right) { Integer l = map.floorKey(left); if (l != null && map.get(l) >= right) { return true; } return false; } public void removeRange(int left, int right) { Integer l1 = map.lowerKey(left); // I used lowerKey here, since we don't care about the range starting at left, as it should be removed Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right // do this first, in case l1 == l2, the later one will change r1(or r2 in this case) if (l2 != null && map.get(l2) > right) { map.put(right, map.get(l2)); } if (l1 != null && map.get(l1) > left) { map.put(l1, left); } // range that starts at left should be removed, so left is inclusive // range that starts at right should be kept, so right is exclusive map.subMap(left, true, right, false).clear(); } }
/* https://leetcode.com/problems/range-module/ Idea is to use a height balanced tree to save the intervals. Intervals are kept according to the start point. We search for the position where the given range can lie, then check the previous if it overlaps and keep iterating forward while the intervals are overlapping. QueryRange: We first find the range of values in [left, right). Then for each of the overlapping intervals, we subtract the common range. Finally if the entire range is covered, then the range will become zero. */ class RangeModule { private: struct Interval { const bool operator<(const Interval& b) const { // Important to implement for == case, otherwise intervals // with same start won't exist // return start < b.start || (start == b.start && end < b.end); // This is the best way to compare since tuple already have ordering implemented for // fields return tie(start, end) < tie(b.start, b.end); } int start = -1, end = -1; Interval(int start, int end): start(start), end(end) {}; }; set<Interval> intervals; public: RangeModule() { } // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all, insertion would take O(1) // SC: O(1) void addRange(int left, int right) { Interval interval(left, right); // Find the position where interval should lie st the next interval's // start >= left auto it = intervals.lower_bound(interval); // check if previous overlaps, move the iterator backwards if(!intervals.empty() && it != intervals.begin() && prev(it)->end >= interval.start) { --it; interval.start = min(it->start, interval.start); } // merge while intervals overlap while(it != intervals.end() && it->start <= interval.end) { interval.end = max(it->end, interval.end); intervals.erase(it++); } intervals.insert(interval); } // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all // SC: O(1) bool queryRange(int left, int right) { Interval interval(left, right); // Range of numbers that needs to be checked int range = right - left; // Find the position where interval should lie st the next interval's // start >= left auto it = intervals.lower_bound(interval); // check if previous interval overlaps the range, previous only // covers iff the open end > start of current. [prev.start, prev.end) [left, right) if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start) { // remove the common portion int common = min(interval.end, prev(it)->end) - interval.start; range -= common; } // for all the following overlapping intervals, remove the common portion while(it != intervals.end() && it->start <= interval.end) { int common = min(interval.end, it->end) - it->start; range -= common; ++it; } // Check if the entire range was covered or not return range == 0; } // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all // SC: O(1) void removeRange(int left, int right) { Interval interval(left, right); // Find the position where interval should lie st the next interval's // start >= left auto it = intervals.lower_bound(interval); // check if previous overlaps, then move the iterator position backwards if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start) --it; // For each of the overlapping intervals, remove the common portions while(it != intervals.end() && it->start < interval.end) { // Start and End of common portion int common_start = max(interval.start, it->start); int common_end = min(interval.end, it->end); // only a section of interval overlaps, remove that part // an overlapping interval might have to be broken into two non-overlapping parts // Eg [---------------------) Bigger interval // [--------) Ongoing interval // [------) [-----) Original interval broken into left and right parts // check if there is some range left on the left side if(it->start < common_start) intervals.insert(Interval(it->start, common_start)); // check if there is some range left on the right side if(it->end > common_end) intervals.insert(Interval(common_end, it->end)); // Remove the original interval intervals.erase(it++); } } }; /** * Your RangeModule object will be instantiated and called as such: * RangeModule* obj = new RangeModule(); * obj->addRange(left,right); * bool param_2 = obj->queryRange(left,right); * obj->removeRange(left,right); */
var RangeModule = function() { this.ranges = [] }; /** * @param {number} left * @param {number} right * @return {void} */ //Time: O(logN) RangeModule.prototype.addRange = function(left, right) { const lIdx = this.findIndex(left), rIdx = this.findIndex(-right) if (lIdx === this.ranges.length) { this.ranges.push(left) this.ranges.push(-right) } else if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) { this.ranges.splice(lIdx, rIdx - lIdx, -right) } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) { this.ranges.splice(lIdx, rIdx - lIdx) } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) { this.ranges.splice(lIdx, rIdx - lIdx, left, -right) } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) { this.ranges.splice(lIdx, rIdx - lIdx, left) } return null }; /** * @param {number} left * @param {number} right * @return {boolean} */ //Time: O(logN) RangeModule.prototype.queryRange = function(left, right) { const lIdx = this.findIndex(left), rIdx = this.findIndex(-right) if (lIdx === this.ranges.length) return false if (lIdx + 2 < rIdx) return false if (lIdx === rIdx) { return this.ranges[lIdx] < 0 } else if (lIdx + 1 === rIdx) { return this.ranges[lIdx] === left || this.ranges[lIdx] === -right } { return this.ranges[lIdx] === left && Math.abs(this.ranges[lIdx + 1]) === right } }; /** * @param {number} left * @param {number} right * @return {void} */ //Time: O(logN) RangeModule.prototype.removeRange = function(left, right) { let lIdx = this.findIndex(left), rIdx = this.findIndex(-right) if (lIdx === this.ranges.length) return null if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) { this.ranges.splice(lIdx, rIdx - lIdx, -left) } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) { this.ranges.splice(lIdx, rIdx - lIdx, -left, right) } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) { this.ranges.splice(lIdx, rIdx - lIdx) } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) { this.ranges.splice(lIdx, rIdx - lIdx, right) } // console.log(this.ranges) return null }; RangeModule.prototype.findIndex = function(number) { let l = 0, r = this.ranges.length while(l < r) { const m = l + ((r - l) >> 1) if (Math.abs(this.ranges[m]) > Math.abs(number)) { r = m } else if (Math.abs(this.ranges[m]) < Math.abs(number)) { l = m + 1 } else { if (number < 0) { l = m + 1 } else { r = m } } } return l } /** * Your RangeModule object will be instantiated and called as such: * var obj = new RangeModule() * obj.addRange(left,right) * var param_2 = obj.queryRange(left,right) * obj.removeRange(left,right) */
Range Module
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. &nbsp; Example 1: Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. &nbsp; Constraints: 2 &lt;= asteroids.length &lt;= 104 -1000 &lt;= asteroids[i] &lt;= 1000 asteroids[i] != 0
class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: stack = [] for a in asteroids: while stack and stack[-1] > 0 > a: if stack[-1] < abs(a): stack.pop() continue elif stack[-1] == abs(a): stack.pop() break # this means asteroid must be destroyed (not add to stack in else statement below) else: stack.append(a) return stack
/* 0. Start iterating over the asteroid one by one. 1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision. 2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0)) 3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid. 4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid. 5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack. 6. Convert the stack to an array in return it. */ class Solution { public int[] asteroidCollision(int[] asteroids) { Stack<Integer> stack = new Stack<>(); //0. Start iterating over the asteroid one by one. for(int a : asteroids) { //1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision. //2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0)) while(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() < Math.abs(a)) { stack.pop(); } //3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid. if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() == Math.abs(a)) { stack.pop(); continue; } //4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid. if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() > Math.abs(a)) { continue; } //5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack. stack.push(a); } //6. Convert the stack to an array in return it. int[] ans = new int[stack.size()]; int i = stack.size() - 1; while(!stack.isEmpty()) { ans[i] = stack.pop(); i--; } return ans; } }
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { vector<int>v; stack<int>s; for(auto x: asteroids){ if(x > 0) s.push(x); else{ // Case 1: whem top is less than x while(s.size() > 0 && s.top() > 0 && s.top() < -x){ s.pop(); } // case 2 : when both of same size if( s.size() > 0 && s.top()==-x) { s.pop(); } // case 3: when top is greater else if( s.size() > 0 && s.top() > -x ){ // do nothing } // case 4: when same direction else{ s.push(x); } } } while(!s.empty()){ v.push_back(s.top()); s.pop(); } reverse(v.begin(),v.end()); return v; } };
/** * @param {number[]} asteroids * @return {number[]} */ var asteroidCollision = function(asteroids) { const s = []; for (let i = 0; i < asteroids.length; i++) { const a = asteroids[i]; // Negative asteroids to the left of the stack can be ignored. // They'll never collide. Let's just add it to the answer stack and // move on. I consider this a special case. if ((s.length === 0 || s[s.length -1] < 0) && a < 0 ) { s.push(a); // If an asteroid a is positive (l to r), it may still collide with an // a negative asteroid further on in the asteroids array } else if (a > 0) { s.push(a); // a is negative. It can only collide with positive ones in // the stack. The following will keep on iterating // until it is dealt with. } else { const pop = s.pop(); // positive pop beats negative a, so pick up pop // and re-add it to the stack. if (Math.abs(pop) > Math.abs(a)) { s.push(pop); // a has larger size than pop, so pop will get dropped // and we'll retry another iteration with the same // negative a asteroid and whatever the stack's state is. } else if (Math.abs(pop) < Math.abs(a)) { i--; // magnitude of positive pop and negative a are the same // so we can drop both of them. } else { continue; } } } // The stack should be the answer return s; };
Asteroid Collision
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i &lt; j &lt; k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (arr[i], arr[j], arr[k]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. Example 2: Input: arr = [1,1,2,2,2,2], target = 5 Output: 12 Explanation: arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times: We choose one 1 from [1,1] in 2 ways, and two 2s from [2,2,2,2] in 6 ways. Example 3: Input: arr = [2,1,3], target = 6 Output: 1 Explanation: (1, 2, 3) occured one time in the array so we return 1. &nbsp; Constraints: 3 &lt;= arr.length &lt;= 3000 0 &lt;= arr[i] &lt;= 100 0 &lt;= target &lt;= 300
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() count = 0 for i in range(0, len(arr)-2): rem_sum = target - arr[i] hash_map = {} for j in range(i+1, len(arr)): if arr[j] > rem_sum: break if rem_sum - arr[j] in hash_map: count = count + hash_map[rem_sum-arr[j]] # update the hash_map hash_map[arr[j]] = hash_map.get(arr[j], 0) + 1 return count % 1000000007
class Solution { public int threeSumMulti(int[] arr, int target) { long[] cnt = new long[101]; long res = 0; for (int i : arr) { cnt[i]++; } for (int i = 0; i < 101 && i <= target; i++) { if (cnt[i] == 0) { continue; } for (int j = i; j < 101 && i + j <= target; j++) { int k = target - i - j; if (k < j) { break; } if (cnt[j] == 0 || k >= 101 || cnt[k] == 0) { continue; } if (i == j && j == k) { res += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 3 / 2; } else if (i == j) { res += cnt[k] * cnt[j] * (cnt[j] - 1) / 2; } else if (j == k) { res += cnt[i] * cnt[j] * (cnt[j] - 1) / 2; } else { res += cnt[i] * cnt[j] * cnt[target - i - j]; } } } return (int) (res % (Math.pow(10, 9) + 7)); } }
class Solution { public: int threeSumMulti(vector<int>& arr, int target) { long long ans = 0; int MOD = pow(10, 9) + 7; // step 1: create a counting array; vector<long long> counting(101); // create a vector with size == 101; for(auto &value : arr) counting[value]++; // count the number; // step 2: evaluate all cases: x, y, z; // case 1: x != y != z; for(int x_idx = 0; x_idx < counting.size() - 2; x_idx++){ if(counting[x_idx] < 1) continue; int target_tmp = target - x_idx; for(int y_idx = x_idx + 1; y_idx < counting.size() - 1; y_idx++){ if(counting[y_idx] < 1) continue; if(target_tmp - y_idx <= 100 && target_tmp - y_idx > y_idx){ ans += counting[x_idx] * counting[y_idx] * counting[target_tmp - y_idx]; ans %= MOD; } } } // case 2: x == y != z; for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){ if(counting[x_idx] < 2) continue; int target_tmp = target - 2 * x_idx; if(target_tmp <= 100 && target_tmp > x_idx){ ans += counting[x_idx] * (counting[x_idx] - 1) / 2 * counting[target_tmp]; ans %= MOD; } } // case 3: x != y == z; for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){ if(counting[x_idx] < 1) continue; int target_tmp = target - x_idx; if(target_tmp %2 != 0) continue; if(target_tmp/2 <= 100 && target_tmp/2 > x_idx && counting[target_tmp/2] > 1){ ans += counting[x_idx] * counting[target_tmp/2] * (counting[target_tmp/2] - 1) / 2; ans %= MOD; } } // case 4: x == y == z; for(int x_idx = 0; x_idx < counting.size(); x_idx++){ if(counting[x_idx] < 3) continue; if(x_idx * 3 == target){ ans += counting[x_idx] * (counting[x_idx] - 1) * (counting[x_idx] - 2) / 6; ans %= MOD; } } return ans; } };
/** * @param {number[]} arr * @param {number} target * @return {number} */ var threeSumMulti = function(arr, target) { let count=0 arr.sort((a,b)=>a-b) for(let i=0;i<arr.length-2;i++){ let j=i+1,k=arr.length-1 while(j<k){ let sum=arr[i]+arr[j]+arr[k] if(sum<target){ j++ } else if(sum>target){ k-- } else{ if(arr[j]!==arr[k]){ let j1=j,k1=k while(arr[j]===arr[j1]){ j1++ } while(arr[k]===arr[k1]){ k1-- } count+=((j1-j)*(k-k1)) j=j1 k=k1 } else{ for(let n=1;n<=k-j;n++){ count+=n } break } } } } return count% (10**9 + 7) };
3Sum With Multiplicity
The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). "./" : Remain in the same folder. "x/" : Move to the child folder named x (This folder is guaranteed to always exist). You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step. The file system starts in the main folder, then the operations in logs are performed. Return the minimum number of operations needed to go back to the main folder after the change folder operations. &nbsp; Example 1: Input: logs = ["d1/","d2/","../","d21/","./"] Output: 2 Explanation: Use this change folder operation "../" 2 times and go back to the main folder. Example 2: Input: logs = ["d1/","d2/","./","d3/","../","d31/"] Output: 3 Example 3: Input: logs = ["d1/","../","../","../"] Output: 0 &nbsp; Constraints: 1 &lt;= logs.length &lt;= 103 2 &lt;= logs[i].length &lt;= 10 logs[i] contains lowercase English letters, digits, '.', and '/'. logs[i] follows the format described in the statement. Folder names consist of lowercase English letters and digits.
class Solution: def minOperations(self, logs: List[str]) -> int: m='../' r='./' #create an empty stack stk=[] #iterate through the list for i in logs: #if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack if(i==m): if(len(stk)>0): stk.pop() #else if Remain in the same folder (./) operator occurs, do nothing and move to next element in list elif(i==r): continue #else add element to the stack else: stk.append(i) #now return the size of the stack which would be the minimum number of operations needed to go back to the main folder return(len(stk)) ```
class Solution { public int minOperations(String[] logs) { var stack = new Stack<String>(); for(var log : logs){ if(log.equals("../")){ if(!stack.empty()) stack.pop(); }else if(log.equals("./")){ }else{ stack.push(log); } } return stack.size(); } }
//1.using stack class Solution { public: int minOperations(vector<string>& logs) { if(logs.size()==0) return 0; stack<string> st; for(auto x: logs){ if (x[0] != '.') //Move to the child folder so add children st.push(x); else if(x=="../"){ // Move to the parent folder of the current folder so pop if(!st.empty()) st.pop(); else continue; //don’t move the pointer beyond the main folder. } } return st.size(); } }; //2. class Solution { public: int minOperations(vector<string>& logs) { int ans = 0; for (string log : logs) { if (log == "../") { // go deeper ans--; ans = max(ans, 0); } else if (log != "./") // one level up ans++; } return ans; } }; //3. class Solution { public: int minOperations(vector<string>& logs) { int res = 0; for (string s : logs) { if (s=="../") res = max(0, --res); else if (s=="./") continue; else res++; } return res; } };
var minOperations = function(logs) { let count = 0; for(i=0;i<logs.length;i++){ if(logs[i] === '../') { if(count > 0) count = count - 1; continue } if(logs[i] === './') continue; else count = count + 1; } return count };
Crawler Log Folder
Given a non-empty&nbsp;array of integers nums, every element appears twice except for one. Find that single one. 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,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Output: 4 Example 3: Input: nums = [1] Output: 1 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 3 * 104 -3 * 104 &lt;= nums[i] &lt;= 3 * 104 Each element in the array appears twice except for one element which appears only once.
class Solution: def singleNumber(self, nums: List[int]) -> int: nums.sort() i=0 while i<len(nums)-1: if nums[i]==nums[i+1]: i+=2 else: return nums[i] return nums[-1]
class Solution { public int singleNumber(int[] nums) { Stack numStack = new Stack(); Arrays.sort(nums); for (var i = 0; i < nums.length; ++i) { numStack.push(nums[i]); if (i < nums.length - 1 && nums[++i] != (int) numStack.peek()) break; } return (int) numStack.pop(); } }
class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int,int> a; for(auto x: nums) a[x]++; for(auto z:a) if(z.second==1) return z.first; return -1; } };
var singleNumber = function(nums) { let s = 0; // Location of first possible suspect for (let i = s + 1; i < nums.length; i++) { if (nums[i] == nums[s]) { // If we found a duplicate nums.splice(i, 1); // Remove duplicate so it won't confuse us next time we come across it s++; // Next suspect's location i = s; // Start of next search (i=s+1 in next loop iteration) } } return nums[s]; };
Single Number
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words. &nbsp; Example 1: Input: words = ["alex","loves","leetcode"] Output: "alexlovesleetcode" Explanation: All permutations of "alex","loves","leetcode" would also be accepted. Example 2: Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"] Output: "gctaagttcatgcatc" &nbsp; Constraints: 1 &lt;= words.length &lt;= 12 1 &lt;= words[i].length &lt;= 20 words[i] consists of lowercase English letters. All the strings of words are unique.
class Solution: def shortestSuperstring(self, A): @lru_cache(None) def suffix(i,j): for k in range(min(len(A[i]),len(A[j])),0,-1): if A[j].startswith(A[i][-k:]): return A[j][k:] return A[j] n = len(A) @lru_cache(None) def dfs(bitmask, i): if bitmask + 1 == 1 << n: return "" return min([suffix(i, j)+dfs(bitmask | 1<<j, j) for j in range(n) if not(bitmask & 1<<j)], key = len) return min([A[i]+dfs(1<<i,i) for i in range(n)], key = len)
class Solution { public String shortestSuperstring(String[] words) { int n = words.length; int[][] discount = new int[n][n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->j and j->i if (words[j].startsWith(words[i].substring(k))){ discount[i][j]=words[i].length()-k; break; } } } } int[][] dp = new int[1<<n][n]; int[][] path = new int[1<<n][n]; for (int i = 0; i < 1<<n; i++){ // find the max discount for mask (1<<n)-1 with dp for (int j = 0; j < n; j++){ for (int k = 0; k < n && (i&1<<j)>0; k++){ if ((i&1<<k)==0 && dp[i][j]+discount[j][k]>=dp[i|1<<k][k]){ dp[i|1<<k][k]=dp[i][j]+discount[j][k]; path[i|1<<k][k]=j; } } } } int m = (1<<n)-1, idx = n; // build the path from end to start int end=IntStream.range(0,n).reduce((a,b)->dp[(1<<n)-1][a]>dp[(1<<n)-1][b]?a:b).getAsInt(); String[] ans = new String[n]; while(m>0){ ans[--idx]=words[end].substring((m&(m-1))==0?0:discount[path[m][end]][end]); m^=1<<end; end=path[m|1<<end][end]; } return String.join("",ans); } }
vector<vector<int> > dp,pre,par; bool startWith(string s, string t) { // returns true if string s starts with string t int i; for(i=0; i<s.length()&&i<t.length(); i++) { if(s[i]==t[i]) continue; else return false; } if(i==t.length()) return true; else return false; } int calc(string A, string B) { // calculate the number of extra characters required to be appended to A // if A is followed by B // for eg. calc("abcd","cdef") = 2 int a=A.length(),b=B.length(); for(int i=0; i<a; i++) { if(a-i<=b&&startWith(B,A.substr(i))) { return b-(a-i); } } return b; } int finalMask,n; int helper(int mask, int last) { // returns the minimum length of string required if last string appended was A[last] // the sets bit in mask represents the strings that were already appended to the final string if(mask==finalMask) // all strings are appended in final string return 0; if(dp[mask][last]!=-1) // memoization return dp[mask][last]; int mn=INT_MAX; int p; for(int i=0; i<n; i++) { if(mask&(1<<i)) continue; int cost=pre[last][i]+helper(mask|(1<<i),i); // extra characters need to be appended if(cost<mn) { mn=cost; p=i; } } par[mask][last]=p; // store parent, so that it is easy to traceback and find the final result return dp[mask][last]=mn; // store result in DP table } class Solution { public: string shortestSuperstring(vector<string>& A) { n=A.size(); pre.assign(n,vector<int>(n)); // for pre-computing calc(a,b) for all pairs of strings par.assign(1<<n,vector<int>(n,-1)); for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(j==i) continue; pre[i][j]=calc(A[i],A[j]); } } finalMask=(1<<n)-1; dp.assign(1<<n,vector<int>(n,-1)); int len=INT_MAX; // len will contain minimum length of required string int ind; for(int i=0; i<n; i++) { int prev=len; len=min(len, (int)A[i].length()+helper(1<<i,i)); if(len!=prev) { ind=i; } } // Now traceback to find the final answer string ans=A[ind]; int msk=1<<ind; int prev_ind=ind; ind=par[msk][ind]; while(ind!=-1) { len=pre[prev_ind][ind]; int alen=A[ind].length(); ans+=A[ind].substr(alen-len,len); msk=msk^(1<<ind); prev_ind=ind; ind=par[msk][ind]; } return ans; } };
var shortestSuperstring = function(words) { let N = words.length, suffixes = new Map(), edges = Array.from({length: N}, () => new Uint8Array(N)) // Build the edge graph for (let i = 0, word = words; i < N; i++) { let word = words[i] for (let k = 1; k < word.length; k++) { let sub = word.slice(k) if (suffixes.has(sub)) suffixes.get(sub).push(i) else suffixes.set(sub, [i]) } } for (let j = 0; j < N; j++) { let word = words[j] for (let k = 1; k < word.length; k++) { let sub = word.slice(0,k) if (suffixes.has(sub)) for (let i of suffixes.get(sub)) edges[i][j] = Math.max(edges[i][j], k) } } // Initialize DP array let M = N - 1, dp = Array.from({length: M}, () => new Uint16Array(1 << M)) // Helper function to find the best value for dp[curr][currSet] // Store the previous node with bit manipulation for backtracking const solve = (curr, currSet) => { let prevSet = currSet - (1 << curr), bestOverlap = 0, bestPrev if (!prevSet) return (edges[M][curr] << 4) + M for (let prev = 0; prev < M; prev++) if (prevSet & 1 << prev) { let overlap = edges[prev][curr] + (dp[prev][prevSet] >> 4) if (overlap >= bestOverlap) bestOverlap = overlap, bestPrev = prev } return (bestOverlap << 4) + bestPrev } // Build DP using solve for (let currSet = 1; currSet < 1 << M; currSet++) for (let curr = 0; curr < N; curr++) if (currSet & 1 << curr) dp[curr][currSet] = solve(curr, currSet) // Join the ends at index M let curr = solve(M, (1 << N) - 1) & (1 << 4) - 1 // Build the circle by backtracking path info from dp // and find the best place to cut the circle let path = [curr], currSet = (1 << M) - 1, bestStart = 0, lowOverlap = edges[curr][M], prev while (curr !== M) { prev = dp[curr][currSet] & (1 << 4) - 1, currSet -= 1 << curr let overlap = edges[prev][curr] if (overlap < lowOverlap) lowOverlap = overlap, bestStart = N - path.length curr = prev, path.unshift(curr) } // Build and return ans by cutting the circle at bestStart let ans = [] for (let i = bestStart; i < bestStart + M; i++) { let curr = path[i%N], next = path[(i+1)%N], word = words[curr] ans.push(word.slice(0, word.length - edges[curr][next])) } ans.push(words[path[(bestStart+M)%N]]) return ans.join("") };
Find the Shortest Superstring
You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x &lt; m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row. Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row. &nbsp; Example 1: Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]] Output: 17 Explanation: The path with the minimum possible cost is the path 5 -&gt; 0 -&gt; 1. - The sum of the values of cells visited is 5 + 0 + 1 = 6. - The cost of moving from 5 to 0 is 3. - The cost of moving from 0 to 1 is 8. So the total cost of the path is 6 + 3 + 8 = 17. Example 2: Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]] Output: 6 Explanation: The path with the minimum possible cost is the path 2 -&gt; 3. - The sum of the values of cells visited is 2 + 3 = 5. - The cost of moving from 2 to 3 is 1. So the total cost of this path is 5 + 1 = 6. &nbsp; Constraints: m == grid.length n == grid[i].length 2 &lt;= m, n &lt;= 50 grid consists of distinct integers from 0 to m * n - 1. moveCost.length == m * n moveCost[i].length == n 1 &lt;= moveCost[i][j] &lt;= 100
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_row, max_col = len(grid), len(grid[0]) dp = [[-1] * max_col for _ in range(max_row)] def recursion(row, col): if row == max_row - 1: # If last row then return nodes value return grid[row][col] if dp[row][col] == -1: # If DP for this node is not computed then we will do so now. current = grid[row][col] # Current Node Value res = float('inf') # To store best path from Current Node for c in range(max_col): # Traverse all path from Current Node val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value res = min(res, val) dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val return dp[row][col] for c in range(max_col): recursion(0, c) # Start recursion from all nodes in 1st row return min(dp[0]) # Return min value from 1st row
class Solution { Integer dp[][]; public int minPathCost(int[][] grid, int[][] moveCost) { dp=new Integer[grid.length][grid[0].length]; int ans=Integer.MAX_VALUE; for(int i=0;i<grid[0].length;i++) { ans=Math.min(ans,grid[0][i]+helper(grid,moveCost,grid[0][i],1)); } return ans; } public int helper(int[][] grid,int[][] moveCost,int cur,int i) { if(i==grid.length) { return 0; } int ans=Integer.MAX_VALUE; for(int k=0;k<grid[0].length;k++) { int a=Integer.MAX_VALUE; if(dp[i][k]!=null) { a=dp[i][k]; } else { a=helper(grid,moveCost,grid[i][k],i+1); dp[i][k]=a; } ans=Math.min(grid[i][k]+moveCost[cur][k]+a,ans); } return ans; } }
class Solution { public: int solve(vector<vector<int>> &grid,vector<vector<int>>& moveCost,int i,int j,int n,int m){ if(i==n-1){ return grid[i][j]; } int ans=INT_MAX; for(int k=0;k<m;k++){ ans=min(ans,grid[i][j]+moveCost[grid[i][j]][k]+solve(grid,moveCost,i+1,k,n,m)); } return ans; } int minPathCost(vector<vector<int>>& grid, vector<vector<int>>& moveCost) { int ans=INT_MAX; int n=grid.size(); int m=grid[0].size(); for(int i=0;i<m;i++){ ans=min(ans,solve(grid,moveCost,0,i,n,m)); } return ans; } };
var minPathCost = function(grid, moveCost) { const rows = grid.length; const cols = grid[0].length; const cache = []; for (let i = 0; i < rows; i++) { cache.push(Array(cols).fill(null)); } function move(row, col) { const val = grid[row][col]; if (cache[row][col] !== null) { return cache[row][col]; } if (row === rows - 1) { return val; } let ans = Number.MAX_SAFE_INTEGER; for (let i = 0; i < cols; i++) { const addCost = moveCost[val][i]; ans = Math.min(ans, move(row + 1, i) + val + addCost); } cache[row][col] = ans; return ans; } let ans = Number.MAX_SAFE_INTEGER; for (let i = 0; i < cols; i++) { ans = Math.min(ans, move(0, i)); } return ans; };
Minimum Path Cost in a Grid
Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example, 21 written in binary is 10101, which has 3 set bits. &nbsp; Example 1: Input: left = 6, right = 10 Output: 4 Explanation: 6 -&gt; 110 (2 set bits, 2 is prime) 7 -&gt; 111 (3 set bits, 3 is prime) 8 -&gt; 1000 (1 set bit, 1 is not prime) 9 -&gt; 1001 (2 set bits, 2 is prime) 10 -&gt; 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. Example 2: Input: left = 10, right = 15 Output: 5 Explanation: 10 -&gt; 1010 (2 set bits, 2 is prime) 11 -&gt; 1011 (3 set bits, 3 is prime) 12 -&gt; 1100 (2 set bits, 2 is prime) 13 -&gt; 1101 (3 set bits, 3 is prime) 14 -&gt; 1110 (3 set bits, 3 is prime) 15 -&gt; 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. &nbsp; Constraints: 1 &lt;= left &lt;= right &lt;= 106 0 &lt;= right - left &lt;= 104
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} return sum(bin(n).count('1') in primes for n in range(left, right + 1))
class Solution { public int calculateSetBits(String s){ int count=0; for (int i = 0; i < s.length(); i++) { if(s.charAt(i)=='1') count++; } return count; } public boolean isPrime(int n){ if (n==0 || n==1) return false; for (int i = 2; i <= n/2; i++) { if(n%i ==0 ) return false; } // System.out.println(n+" - "); return true; } public int countPrimeSetBits(int left, int right) { int count=0; for(int i=left;i<=right;i++){ String b= Integer.toBinaryString(i); int n=calculateSetBits(b); if(isPrime(n)) count++; } return count; } }
class Solution { public: int countPrimeSetBits(int left, int right) { int ans=0; while(left<=right) { int cnt=__builtin_popcount(left); if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19) ++ans; ++left; } return ans; } };
/** * @param {number} L * @param {number} R * @return {number} */ var countPrimeSetBits = function(L, R) { let set = new Set([2, 3, 5, 7, 11, 13, 17, 19]); let countPrime = 0; for (let i = L; i <= R; i++) { if (set.has(i.toString(2).replace(/0/g, '').length)) countPrime++; } return countPrime; };
Prime Number of Set Bits in Binary Representation
Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 &lt; j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) &nbsp; Example 1: Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1] Output: true Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 Example 2: Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1] Output: false Example 3: Input: arr = [3,3,6,5,-2,2,5,1,-9,4] Output: true Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 &nbsp; Constraints: 3 &lt;= arr.length &lt;= 5 * 104 -104 &lt;= arr[i] &lt;= 104
class Solution: def canThreePartsEqualSum(self, arr: List[int]) -> bool: total = sum(arr) if total % 3 != 0: return False ave = total // 3 stage = 0 add = 0 for i in arr[:-1]: add += i if add == ave: stage +=1 add = 0 if stage == 2: return True return False
class Solution { public boolean canThreePartsEqualSum(int[] arr) { int sum = 0; for (Integer no : arr) { sum += no; } if (sum % 3 != 0) { return false; } sum = sum / 3; int tempSum = 0; int count = 0; for (int i = 0; i < arr.length; i++) { tempSum += arr[i]; if (tempSum == sum) { count++; tempSum = 0; } } return count >= 3; } }
class Solution { public: bool canThreePartsEqualSum(vector<int>& arr) { int sum=0; for(auto i : arr) sum+=i; if(sum%3!=0) return false; //partition not possible int part=sum/3,temp=0,found=0; for(int i=0;i<arr.size();i++){ temp+=arr[i]; if(temp==part){ temp=0; found++; } } return found>=3 ? true : false; } }; feel free to ask your doubts :) and pls upvote if it was helpful :)
var canThreePartsEqualSum = function(arr) { const length = arr.length; let sum =0, count = 0, partSum = 0; for(let index = 0; index < length; index++) { sum += arr[index]; } if(sum%3 !== 0) return false; partSum = sum/3; sum = 0; for(let index = 0; index < length; index++) { sum += arr[index]; if(sum === partSum){ count++; sum = 0; if(count == 2 && index < length-1) return true; } } return false; };
Partition Array Into Three Parts With Equal Sum
A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. For example, "AACCGGTT" --&gt; "AACCGGTA" is one mutation. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1. Note that the starting point is assumed to be valid, so it might not be included in the bank. &nbsp; Example 1: Input: start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"] Output: 1 Example 2: Input: start = "AACCGGTT", end = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"] Output: 2 Example 3: Input: start = "AAAAACCC", end = "AACCCCCC", bank = ["AAAACCCC","AAACCCCC","AACCCCCC"] Output: 3 &nbsp; Constraints: start.length == 8 end.length == 8 0 &lt;= bank.length &lt;= 10 bank[i].length == 8 start, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: q = deque() q.append(start) n = len(bank) last = 0 used = [False] * n for i, x in enumerate(bank): if start == x: used[i] = True if end == x: last = i dist = 0 while q: dist += 1 for _ in range(len(q)): w = q.popleft() for i, x in enumerate(bank): if used[i]: continue bad = 0 for j in range(8): if w[j] != x[j]: bad += 1 if bad == 2: break if bad == 1: if last == i: return dist used[i] = True q.append(x) return -1
class Solution { public int minMutation(String start, String end, String[] bank) { Set<String> set = new HashSet<>(); for(String tmp: bank){ set.add(tmp); } if(!set.contains(end)) return -1; if(start.equals(end)) return 0; char[] var = {'A','C','G','T'}; Queue<String> q = new LinkedList<>(); q.add(start); int count = 0; while(!q.isEmpty()){ int size = q.size(); for(int i = 0; i < size; i ++){ String str = q.poll(); char[] tmp = str.toCharArray(); if(str.equals(end)) return count; for(int j = 0; j < 8; j ++){ char ch = tmp[j]; for(int k = 0; k < 4; k ++){ tmp[j] = var[k]; String node = new String(tmp); if(set.contains(node)){ q.add(node); set.remove(node); } } tmp[j] = ch; } } count++; } return -1; } }
class Solution { public: int minMutation(string start, string end, vector<string>& bank) { unordered_set<string> st(bank.begin(), bank.end()); if (st.find(end) == st.end()) return -1; queue<string> q; q.push(start); unordered_set<string> vis; vis.insert(start); int res=0; while (not q.empty()) { int sz = q.size(); while (sz--) { string currString = q.front(); q.pop(); if (currString == end) return res; for (int i=0;i<currString.size();i++) { string temp = currString; for (auto g: string("ATGC")) { temp[i] = g; if (st.find(temp) != st.end() and (vis.find(temp) == vis.end())) { q.push(temp); vis.insert(temp); } } } } res++; } return -1; } };
/** * @param {string} start * @param {string} end * @param {string[]} bank * @return {number} */ var minMutation = function(start, end, bank) { if(start.length!=end.length || !contains(end,bank)){ return -1; } return bfs(start,end,bank); }; function contains(end,bank){ for(const x of bank){ if(x==end){ return true; } } return false; } function convertPossible(a,b){ if(a.length != b.length) return false; let count=0; for(let i=0;i<a.length;i++){ if(a[i]!=b[i]){ count++; } } return count==1; } function bfs(start,end,bank){ let count=0; let q=[]; let set=new Set(); q.push(start); while(q.length>0){ let size=q.length; for(let i=0;i<size;i++){ let curr=q.shift(); if(curr==end){ return count; } bank.forEach((x)=>{ if(convertPossible(curr,x) && !set.has(x)){ q.push(x); set.add(x); } }) } count++; } return -1; }
Minimum Genetic Mutation
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. &nbsp; Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -231 &lt;= nums[i] &lt;= 231 - 1 &nbsp; Follow up: Could you minimize the total number of operations done?
class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ notzero = 0 zero = 0 while notzero < len(nums): if nums[notzero] != 0: nums[zero] , nums[notzero] = nums[notzero], nums[zero] zero += 1 notzero += 1
class Solution { public void moveZeroes(int[] nums) { int a = 0, z = 0, temp; while(a < nums.length){ if(nums[a] != 0){ temp = nums[z]; nums[z] = nums[a]; nums[a] = temp; z += 1; } a += 1; } } }
class Solution { public: void moveZeroes(vector<int>& nums) { int nums_size = nums.size(); int cntr=0; for(int i=0;i<nums_size;i++) { if(nums[i] != 0) { nums[cntr] = nums[i]; cntr++; } } for( int i=cntr;i<nums_size;i++) { nums[i] = 0; } } };
var moveZeroes = function(nums) { let lastNonZeroNumber = 0; //Moves all the non zero numbers at the start of the array for(let i=0; i<nums.length;i++){ if(nums[i] !=0){ nums[lastNonZeroNumber] = nums[i]; lastNonZeroNumber++; } } //Moves all the zeroes replaced from last non zero number found //to the end of array for(let i = lastNonZeroNumber; i<nums.length;i++){ nums[i] =0; } };
Move Zeroes
Given the head of a singly linked list, reverse the list, and return the reversed list. &nbsp; Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] &nbsp; Constraints: The number of nodes in the list is the range [0, 5000]. -5000 &lt;= Node.val &lt;= 5000 &nbsp; Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head==None or head.next==None: return head p = None while(head != None): temp = head.next head.next = p p = head head = temp return p
/** * 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 ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode curr = head; ListNode temp = null, next = curr.next; curr.next = null; while(curr !=null && next !=null) { // before cutting off link between next & its next, save next.next temp = next.next; // let next point to curr next.next = curr; curr = next; next = temp; } return curr; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) { return head; } ListNode *s=reverseList(head->next); ListNode *t=head->next; t->next=head; head->next=NULL; return s; } };
var reverseList = function(head) { // Iteratively [cur, rev, tmp] = [head, null, null] while(cur){ tmp = cur.next; cur.next = rev; rev = cur; cur = tmp; //[current.next, prev, current] = [prev, current, current.next] } }
Reverse Linked List
Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order. &nbsp; Example 1: Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] Output: [3,2] Explanation: The values that are present in at least two arrays are: - 3, in all three arrays. - 2, in nums1 and nums2. Example 2: Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] Output: [2,3,1] Explanation: The values that are present in at least two arrays are: - 2, in nums2 and nums3. - 3, in nums1 and nums2. - 1, in nums1 and nums3. Example 3: Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] Output: [] Explanation: No value is present in at least two arrays. &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length, nums3.length &lt;= 100 1 &lt;= nums1[i], nums2[j], nums3[k] &lt;= 100
class Solution: def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]: output = [] for i in nums1: if i in nums2 or i in nums3: if i not in output: output.append(i) for j in nums2: if j in nums3 or j in nums1: if j not in output: output.append(j) return output
class Solution { public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { int[] bits = new int[101]; for (int n : nums1) bits[n] |= 0b110; for (int n : nums2) bits[n] |= 0b101; for (int n : nums3) bits[n] |= 0b011; List<Integer> result = new ArrayList(); for (int i = bits.length - 1; i > 0; i--) if (bits[i] == 0b111) result.add(i); return result; } }
class Solution { public: vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) { vector<int>f(110, 0); for (int n : nums1) f[n] |= 1<<0; for (int n : nums2) f[n] |= 1<<1; for (int n : nums3) f[n] |= 1<<2; vector<int>ret; for (int i = 1; i <= 100; i++) if (f[i] == 3 || f[i] >= 5) ret.push_back(i); return ret; } };
var twoOutOfThree = function(nums1, nums2, nums3) { let newArr = []; newArr.push(...nums1.filter(num => nums2.includes(num) || nums3.includes(num))) newArr.push(...nums2.filter(num => nums1.includes(num) || nums3.includes(num))) return Array.from(new Set(newArr)) };
Two Out of Three
Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer. Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds. &nbsp; Example 1: Input: root = [1,0,2], low = 1, high = 2 Output: [1,null,2] Example 2: Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3 Output: [3,2,null,1] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. 0 &lt;= Node.val &lt;= 104 The value of each node in the tree is unique. root is guaranteed to be a valid binary search tree. 0 &lt;= low &lt;= high &lt;= 104
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: if not root: return root if root.val < low: return self.trimBST(root.right, low, high) if root.val > high: return self.trimBST(root.left, low, high) root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(root.right, low, high) return root
class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { if (root == null) return root; while (root.val < low || root.val > high) { root = root.val < low ? root.right : root.left; if (root == null) return root; } root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; } }
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(!root) return NULL; root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); if(root->val < low){ if(root->right){ TreeNode* temp = root; // delete root; return temp->right; }else{ return NULL; } } if(root->val > high){ if(root->left){ TreeNode* temp = root; // delete root; return temp->left; }else{ return NULL; } } return root; } };
var trimBST = function(root, low, high) { if(!root) return null; const { val, left, right } = root; if(val < low) return trimBST(root.right, low, high); if(val > high) return trimBST(root.left, low, high); root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; };
Trim a Binary Search Tree
You are given an array of integers&nbsp;nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. &nbsp; Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1], k = 1 Output: [1] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -104 &lt;= nums[i] &lt;= 104 1 &lt;= k &lt;= nums.length
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: ans = [] pq = [] for i in range(k): heapq.heappush(pq,(-nums[i],i)) ans.append(-pq[0][0]) for i in range(k,len(nums)): heapq.heappush(pq,(-nums[i],i)) while pq and pq[0][1] < i-k+1 : heapq.heappop(pq) ans.append(-pq[0][0]) return ans
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { Deque<Integer> queue = new LinkedList<>(); int l = 0, r = 0; int[] res = new int[nums.length - k + 1]; int index = 0; while (r < nums.length) { int n = nums[r++]; while (!queue.isEmpty() && n > queue.peekLast()) { queue.pollLast(); } queue.offer(n); while (r - l > k) { int m = nums[l++]; if (m == queue.peekFirst()) { queue.pollFirst(); } } if (r - l == k) { res[index++] = queue.peekFirst(); } } return res; } }
class Solution { public: #define f first #define s second vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> ans; priority_queue<pair<int,int>> pq; for(int i=0;i<k;i++)pq.push({nums[i],i}); ans.push_back(pq.top().f); for(int i=k; i<nums.size(); i++){ pq.push({nums[i],i}); while(!pq.empty() && pq.top().s < i-k+1)pq.pop(); ans.push_back(pq.top().f); } return ans; } };
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var maxSlidingWindow = function(nums, k) { var i=0, j=0, max=0, deque=[], output=[]; while(j<nums.length){ if(deque.length === 0){ deque.push(nums[j]) }else if(deque[deque.length-1] > nums[j]){ deque.push(nums[j]) }else{ while(deque[deque.length-1] < nums[j]){ deque.pop() } deque.push(nums[j]) } if(j-i+1 === k){ if(nums[i] === deque[0]){ output.push(deque.shift()); }else{ output.push(deque[0]) } i++; } j++; } return output };
Sliding Window Maximum
You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. &nbsp; Example 1: Input: flips = [3,2,4,1,5] Output: 2 Explanation: The binary string is initially "00000". After applying step 1: The string becomes "00100", which is not prefix-aligned. After applying step 2: The string becomes "01100", which is not prefix-aligned. After applying step 3: The string becomes "01110", which is not prefix-aligned. After applying step 4: The string becomes "11110", which is prefix-aligned. After applying step 5: The string becomes "11111", which is prefix-aligned. We can see that the string was prefix-aligned 2 times, so we return 2. Example 2: Input: flips = [4,1,2,3] Output: 1 Explanation: The binary string is initially "0000". After applying step 1: The string becomes "0001", which is not prefix-aligned. After applying step 2: The string becomes "1001", which is not prefix-aligned. After applying step 3: The string becomes "1101", which is not prefix-aligned. After applying step 4: The string becomes "1111", which is prefix-aligned. We can see that the string was prefix-aligned 1 time, so we return 1. &nbsp; Constraints: n == flips.length 1 &lt;= n &lt;= 5 * 104 flips is a permutation of the integers in the range [1, n].
class Solution: def numTimesAllBlue(self, flips: List[int]) -> int: l = len(flips) s = 0 c = 0 for i in range(len(flips)): f = flips[i] s = 1 << (f - 1) | s if s == (1 << (i+1))-1: c += 1 return c
class Solution { public int numTimesAllBlue(int[] flips) { int counter=0,total=0,max=Integer.MIN_VALUE; for(int i=0;i<flips.length;i++){ if(max<flips[i])max=flips[i]; if(++counter==max)total++; } return total; } }
class BIT{ public: vector<int>bit; int n; BIT(int n){ bit.resize(n+1,0); this->n=n; } int findSum(int i){ int sum=0; while(i>0){ sum+=bit[i]; i-=(i&(-i)); } return sum; } void update(int i,int val){ while(i<=n){ bit[i]+=val; i+=(i&(-i)); } } }; class Solution { public: int numTimesAllBlue(vector<int>& flips) { int n=flips.size(); BIT tree(n+1); int res=0; string s=string(n,'0'); int maxi=0; for(auto &x:flips){ if(s[x-1]=='1'){ tree.update(x,-1); s[x-1]='0'; } else { s[x-1]='1'; tree.update(x,1); } maxi=max(maxi,x); if(tree.findSum(x)==x && tree.findSum(maxi)==maxi) res++; } return res; } };
var numTimesAllBlue = function(flips) { const flipped = new Array(flips.length).fill(0); let prefixAlignedCount = 0; flips.forEach((i, step) => { flipped[i - 1] = 1; if(isPrefixAligned(step)) { ++prefixAlignedCount; } }) return prefixAlignedCount; function isPrefixAligned(step) { for(let i = 0; i < flips.length; ++i) { if((i < step && flipped[i] === 0) || (i > step && flipped[i] === 1)) { return false; } } return true; } };
Number of Times Binary String Is Prefix-Aligned
There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student. You may perform the following move any number of times: Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position&nbsp;x&nbsp;to x + 1 or x - 1) Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning. &nbsp; Example 1: Input: seats = [3,1,5], students = [2,7,4] Output: 4 Explanation: The students are moved as follows: - The first student is moved from from position 2 to position 1 using 1 move. - The second student is moved from from position 7 to position 5 using 2 moves. - The third student is moved from from position 4 to position 3 using 1 move. In total, 1 + 2 + 1 = 4 moves were used. Example 2: Input: seats = [4,1,5,9], students = [1,3,2,6] Output: 7 Explanation: The students are moved as follows: - The first student is not moved. - The second student is moved from from position 3 to position 4 using 1 move. - The third student is moved from from position 2 to position 5 using 3 moves. - The fourth student is moved from from position 6 to position 9 using 3 moves. In total, 0 + 1 + 3 + 3 = 7 moves were used. Example 3: Input: seats = [2,2,6,6], students = [1,3,2,6] Output: 4 Explanation: Note that there are two seats at position 2 and two seats at position 6. The students are moved as follows: - The first student is moved from from position 1 to position 2 using 1 move. - The second student is moved from from position 3 to position 6 using 3 moves. - The third student is not moved. - The fourth student is not moved. In total, 1 + 3 + 0 + 0 = 4 moves were used. &nbsp; Constraints: n == seats.length == students.length 1 &lt;= n &lt;= 100 1 &lt;= seats[i], students[j] &lt;= 100
class Solution: def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: seats.sort() students.sort() return sum(abs(seat - student) for seat, student in zip(seats, students))
class Solution { public int minMovesToSeat(int[] seats, int[] students) { Arrays.sort(seats); Arrays.sort(students); int diff = 0; for(int i=0; i<seats.length; i++){ diff += Math.abs(students[i]-seats[i]); } return diff; } }
class Solution { public: int minMovesToSeat(vector<int>& seats, vector<int>& students) { sort(seats.begin(), seats.end()); sort(students.begin(), students.end()); int res = 0; for (int i = 0; i < seats.size(); i++) res += abs(seats[i] - students[i]); return res; } };
var minMovesToSeat = function(seats, students) { let sum = 0 seats=seats.sort((a,b)=>a-b) students=students.sort((a,b)=>a-b) for(let i=0;i<seats.length;i++) sum+=Math.abs(seats[i]-students[i]) return sum };
Minimum Number of Moves to Seat Everyone
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. &nbsp; Example 1: Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2 and 4. Example 2: Input: num = 30 Output: 14 Explanation: The 14 integers less than or equal to 30 whose digit sums are even are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. &nbsp; Constraints: 1 &lt;= num &lt;= 1000
class Solution: def countEven(self, num: int) -> int: if num%2!=0: return (num//2) s=0 t=num while t: s=s+(t%10) t=t//10 if s%2==0: return num//2 else: return (num//2)-1
class Solution { public int countEven(int num) { int count = 0; for(int i = 1; i <= num; i++) if(sumDig(i)) count++; return count; } private boolean sumDig(int n) { int sum = 0; while(n > 0) { sum += n % 10; n /= 10; } return (sum&1) == 0 ? true : false; } }
class Solution { public: int countEven(int num) { int temp = num, sum = 0; while (num > 0) { sum += num % 10; num /= 10; } return sum % 2 == 0 ? temp / 2 : (temp - 1) / 2; } };
var countEven = function(num) { let count=0; for(let i=2;i<=num;i++){ if(isEven(i)%2==0){ count++; } } return count }; const isEven = (c) =>{ let sum=0; while(c>0){ sum+=(c%10) c=Math.floor(c/10) } return sum }
Count Integers With Even Digit Sum
You are standing at position 0 on an infinite number line. There is a destination at position target. You can make some number of moves numMoves so that: On each move, you can either go left or right. During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction. Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination. &nbsp; Example 1: Input: target = 2 Output: 3 Explanation: On the 1st move, we step from 0 to 1 (1 step). On the 2nd move, we step from 1 to -1 (2 steps). On the 3rd move, we step from -1 to 2 (3 steps). Example 2: Input: target = 3 Output: 2 Explanation: On the 1st move, we step from 0 to 1 (1 step). On the 2nd move, we step from 1 to 3 (2 steps). &nbsp; Constraints: -109 &lt;= target &lt;= 109 target != 0
class Solution: def reachNumber(self,target): jumpCount = 1 sum = 0 while sum<abs(target): sum+=jump jumpCount+=1 if (sum-target)%2==0: return jumpCount-1 else: if ((sum+jumpCount)-target)%2==0: return jumpCount else: return jumpCount+1
class Solution { public int reachNumber(int target) { int sum =0 ,steps = 0; if(target ==0) return 0; target = Math.abs(target); while(sum< target){ sum+=steps; steps++; } while(((sum-target)%2!=0)){ sum+=steps; steps++; } return steps-1; } }
long long fun(long long a){ //sum of all natural from 1 to a long long b=a*(a+1)/2; return b; } class Solution { public: int reachNumber(int target) { long long i=1,j=pow(10,5),x=abs(target),ans=0; //for -ve or +ve positive of a number the minimum no. of steps from the origin will be same while(i<=j){ // binary search to search if x is continous sum of some natural number starting from 1 long long m=(i+j)/2; if(fun(m)==x){ ans=m; } if(x>fun(m)){ i=m+1; } else{ j=m-1; } } if(ans!=0){ // If we found our ans return it return ans; } else{ //in this for loop i have set the limit too high it can be less then 10^6 as max value j can be is 44723, so loop will never run fully, whatever the value of j will be, loop will maximum run for 3-10 iterations for(int l=j+1;l<100000;l++){ // in the end of binary search we get the value of j(or high end) as the position of the number(in the sequence of continous sum of natural number from 1, i.e. 1, 3,6,10........) whose value is just less than x(searching element) if((fun(l)-x)%2 ==0){ // as the total step will be more than x if we go backward from zero, thing to note is that if we go -ve direction we also have to come back so we covering even distance ans=l;// when the first fun(l) - x is even that l is our minimum jump break; // no need to search further } } } return ans; } };
/** * @param {number} target * @return {number} */ var reachNumber = function(target) { target = Math.abs(target); let steps = 0, sum = 0; while (sum < target) { steps++; sum += steps; } while ((sum - target) % 2 !== 0) { steps++; sum += steps; } return steps; };
Reach a Number
You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n. Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array. The average value of a set of k numbers is the sum of the numbers divided by k. Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. &nbsp; Example 1: Input: rolls = [3,2,4,3], mean = 4, n = 2 Output: [6,6] Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4. Example 2: Input: rolls = [1,5,6], mean = 3, n = 4 Output: [2,3,2,2] Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3. Example 3: Input: rolls = [1,2,3,4], mean = 6, n = 4 Output: [] Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are. &nbsp; Constraints: m == rolls.length 1 &lt;= n, m &lt;= 105 1 &lt;= rolls[i], mean &lt;= 6
class Solution: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n) if rem == 0: if 1 <= missing_val <= 6: return [missing_val] * n elif 1 <= missing_val < 6: return [missing_val + 1] * rem + [missing_val] * (n - rem) return []
class Solution { public int[] missingRolls(int[] rolls, int mean, int n) { int i,m=rolls.length,sum=0; for(i=0;i<m;i++) sum+=rolls[i]; int x=(mean*(m+n))-sum; if(x<=0||n*6<x||((x/n)==0)) { return new int[] {}; } int arr[]=new int[n]; int p=x/n,q=x%n; for(i=0;i<n;i++) { arr[i]=p+(q>0?1:0); q--; } return arr; } }
class Solution { public: vector<int> missingRolls(vector<int>& rolls, int mean, int n) { int size=rolls.size(),sum=accumulate(rolls.begin(),rolls.end(),0),missingSum=0; missingSum=mean*(n+size)-sum; if(missingSum<n || missingSum>6*n) return {}; int rem=missingSum%n; vector<int>ans(n,missingSum/n); for(int i=0;i<rem;i++) ans[i]+=1; return ans; } };
var missingRolls = function(rolls, mean, n) { let res = []; let sum = ((n + rolls.length) * mean) - rolls.reduce((a,b)=>a+b); if(sum>6*n || sum<1*n) return res; let dec = sum % n; let num = Math.floor(sum / n); for(let i = 0; i < n; i++){ if(dec) res.push(num+1), dec--; else res.push(num); } return res; };
Find Missing Observations
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them. &nbsp; Example 1: Input: candyType = [1,1,2,2,3,3] Output: 3 Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. Example 2: Input: candyType = [1,1,2,3] Output: 2 Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types. Example 3: Input: candyType = [6,6,6,6] Output: 1 Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. &nbsp; Constraints: n == candyType.length 2 &lt;= n &lt;= 104 n&nbsp;is even. -105 &lt;= candyType[i] &lt;= 105
class Solution: def distributeCandies(self, candyType: List[int]) -> int: return min(len(set(candyType)), (len(candyType)//2))
class Solution { public int distributeCandies(int[] candyType) { Set<Integer> set = new HashSet<>(); for (int type : candyType) set.add(type); return Math.min(set.size(), candyType.length / 2); } }
class Solution { public: int distributeCandies(vector<int>& candyType) { unordered_set<int> s(candyType.begin(),candyType.end()); return min(candyType.size()/2,s.size()); } }; //if you like the solution plz upvote.
/** * @param {number[]} candyType * @return {number} */ var distributeCandies = function(candyType) { const set = new Set(); candyType.map(e => set.add(e)); return candyType.length/2 > set.size ? set.size : candyType.length/2 };
Distribute Candies
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. &nbsp; Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. &nbsp; Constraints: 0 &lt;= intervals.length &lt;= 104 intervals[i].length == 2 0 &lt;= starti &lt;= endi &lt;= 105 intervals is sorted by starti in ascending order. newInterval.length == 2 0 &lt;= start &lt;= end &lt;= 105
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: intervals.append(newInterval) intervals.sort(key=lambda x: x[0]) result = [] for interval in intervals: if not result or result[-1][1] < interval[0]: result.append(interval) else: result[-1][1] = max(result[-1][1],interval[1]) return result
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { if (newInterval == null || newInterval.length == 0) return intervals; List<int[]> merged = new LinkedList<>(); int i = 0; // add not overlapping while (i < intervals.length && intervals[i][1] < newInterval[0]) { merged.add(intervals[i]); i++; } // add overlapping while (i < intervals.length && intervals[i][0] <= newInterval[1]) { newInterval[0] = Math.min(intervals[i][0], newInterval[0]); newInterval[1] = Math.max(intervals[i][1], newInterval[1]); i++; } merged.add(newInterval); // add rest while (i < intervals.length) { merged.add(intervals[i]); i++; } return merged.toArray(new int[merged.size()][]); } }
class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { vector<vector<int>> output; int n = intervals.size(); int i = 0; while(i < n){ if(newInterval[1] < intervals[i][0]){ output.push_back(newInterval); while(i < n){ output.push_back(intervals[i]); i++; } return output; } else if(newInterval[0] > intervals[i][1]){ output.push_back(intervals[i]); i++; } else{ newInterval[0] = min(newInterval[0], intervals[i][0]); newInterval[1] = max(newInterval[1], intervals[i][1]); i++; } } output.push_back(newInterval);//think about it return output; } };
var insert = function(intervals, newInterval) { //Edge case if (intervals.length === 0) { return [newInterval]; } //Find the index to insert newIntervals let current = 0; while (current < intervals.length && intervals[current][0] < newInterval[0]) { current++; } intervals.splice(current, 0, newInterval); //If newInterval is not the last index, check the element behigh newInterval to see if merge is needed if (current !== intervals.length -1) { let pointer = current + 1; if (intervals[pointer][0] <= newInterval[1]) { while (pointer < intervals.length && intervals[pointer][0] <= newInterval[1]) { pointer++; } newInterval[1] = Math.max(newInterval[1], intervals[pointer - 1][1]); intervals.splice(current + 1, pointer - (current + 1)); } } //If newInterval is not the first index, check the element berfore newInterval to see if merge is needed if (current !== 0) { if (intervals[current - 1][1] >= newInterval[0]) { newInterval[0] = intervals[current - 1][0]; newInterval[1] = Math.max(newInterval[1], intervals[current - 1][1]); intervals.splice(current - 1, 1); } } return intervals; };
Insert Interval
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. &nbsp; Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0. &nbsp; Constraints: 1 &lt;= k &lt;= num.length &lt;= 105 num consists of only digits. num does not have any leading zeros except for the zero itself.
# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict. #as soon as len(delete) == k delete those indexes from the initial string and thats the answer. #if len(delete) < k remove k-len(delete) chars from right and thats the answer class Solution: def removeKdigits(self, s: str, k: int) -> str: if len(s) == k: return '0' stack = [] delete = {} for i in range(len(s)): while stack and s[i] < stack[-1][0]: delete[stack.pop()[1]] = 1 if len(delete) == k: break if len(delete) == k: return self.deleteindexes(s, delete, k) stack.append([s[i], i]) s1 = self.deleteindexes(s, delete, k) return str(int(s1[:len(s1)-k +len(delete)])) def deleteindexes(self, s, delete, k): if not delete: return s if len(delete) == k: return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete]))) else: return ''.join([c for ind, c in enumerate(s) if ind not in delete])
class Solution { public String removeKdigits(String num, int k) { int n = num.length(); if(n == k){ return "0"; } Deque<Character> dq = new ArrayDeque<>(); for(char ch : num.toCharArray()){ while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){ dq.pollLast(); k--; } dq.addLast(ch); } StringBuilder sb = new StringBuilder(); while(!dq.isEmpty() && dq.peekFirst() == '0'){ dq.pollFirst(); } while(!dq.isEmpty()){ sb.append(dq.pollFirst()); } if(k >= sb.length()){ return "0"; } return sb.length() == 0 ? "0" : sb.toString().substring(0,sb.length()-k); } }
// 😉😉😉😉Please upvote if it helps 😉😉😉😉 class Solution { public: string removeKdigits(string num, int k) { // number of operation greater than length we return an empty string if(num.length() <= k) return "0"; // k is 0 , no need of removing / preforming any operation if(k == 0) return num; string res = "";// result string stack <char> s; // char stack s.push(num[0]); // pushing first character into stack for(int i = 1; i<num.length(); ++i) { while(k > 0 && !s.empty() && num[i] < s.top()) { // if k greater than 0 and our stack is not empty and the upcoming digit, // is less than the current top than we will pop the stack top --k; s.pop(); } s.push(num[i]); // popping preceding zeroes if(s.size() == 1 && num[i] == '0') s.pop(); } while(k && !s.empty()) { // for cases like "456" where every num[i] > num.top() --k; s.pop(); } while(!s.empty()) { res.push_back(s.top()); // pushing stack top to string s.pop(); // pop the top element } reverse(res.begin(),res.end()); // reverse the string if(res.length() == 0) return "0"; return res; } };
var removeKdigits = function(num, k) { if(k == num.length) { return '0' } let stack = [] for(let i = 0; i < num.length; i++) { while(stack.length > 0 && num[i] < stack[stack.length - 1] && k > 0) { stack.pop() k-- } stack.push(num[i]) } while(k > 0) { stack.pop() k-- } while(stack[0] == 0 && stack.length > 1) { stack.shift() } return stack.join('') }
Remove K Digits
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note:&nbsp;You are not allowed to use any built-in library method to directly solve this problem. &nbsp; Example 1: Input: num = 26 Output: "1a" Example 2: Input: num = -1 Output: "ffffffff" &nbsp; Constraints: -231 &lt;= num &lt;= 231 - 1
class Solution: def toHex(self, num: int) -> str: ret = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] ans = "" if num < 0: num = pow(2,32) +num if num == 0: return "0" while num > 0: ans = ret[num%16] +ans num = num//16 return ans
class Solution { public String toHex(int num) { if(num == 0) return "0"; boolean start = true; StringBuilder sb = new StringBuilder(); for(int i = 28; i >= 0; i -= 4) { int digit = (num >> i) & 15; if(digit > 9) { char curr = (char)(digit%10 + 'a'); sb.append(curr); start = false; } else if(digit != 0) { char curr = (char)(digit + '0'); sb.append(curr); start = false; } else {//digit == 0 if(start == false) { //avoid case: 00001a sb.append('0'); } } } return sb.toString(); } }
class Solution { public: string toHex(int num) { string hex = "0123456789abcdef"; unsigned int n = num; // to handle neg numbers string ans = ""; if (n == 0) return "0"; while (n > 0) { int k = n % 16; ans += hex[k]; n /= 16; } reverse(ans.begin(), ans.end()); // as we stored it in the opposite order return ans; } };
var toHex = function(num) { let hexSymbols = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; if (num >= 0) { let hex = ""; do { let reminder = num % 16; num = Math.floor(num/16); hex = hexSymbols[reminder] + hex; } while (num > 0) return hex; } else { num = -num; let invertedHex = ""; //FFFFFFFF - hex let needToCarry1 = true; //adding + 1 initially and carrying it on if needed while (num > 0) { let reminder = num % 16; let invertedReminder = 15 - reminder; //inverting if (needToCarry1) { //adding 1 for 2's complement invertedReminder += 1; if (invertedReminder === 16) { //overflow, carrying 1 to the left invertedReminder = 0; needToCarry1 = true; } else { needToCarry1 = false; } } num = Math.floor(num/16); invertedHex = hexSymbols[invertedReminder] + invertedHex; } //formatting as "FFFFFFFF" while (invertedHex.length < 8) { invertedHex = "f" + invertedHex; } return invertedHex; } };
Convert a Number to Hexadecimal
You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 &lt;= i &lt; nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after applying the mentioned operation at most once for each index in it. &nbsp; Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 0 Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 0 &lt;= nums[i] &lt;= 104 0 &lt;= k &lt;= 104
class Solution: def smallestRangeI(self, nums: List[int], k: int) -> int: return max(0, max(nums)-min(nums)-2*k)
class Solution { public int smallestRangeI(int[] nums, int k) { if (nums.length == 1) return 0; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int num: nums) { min = Math.min(min, num); max = Math.max(max, num); } int diff = max - min; return Math.max(0, diff - 2*k); } }
class Solution { public: int smallestRangeI(vector<int>& nums, int k) { int mx = *max_element(nums.begin(), nums.end()); int mn = *min_element(nums.begin(), nums.end()); return max(0, (mx-mn-2*k)); } };
var smallestRangeI = function(nums, k) { let max = Math.max(...nums); let min = Math.min(...nums); return Math.max(0, max - min- 2*k) };
Smallest Range I
Given an integer array&nbsp;nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. &nbsp; Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,2,2,2,2] Output: 5 Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2000 -106 &lt;= nums[i] &lt;= 106
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: if not nums or len(nums) == 0: return 0 def find_pos(sub, val): left, right = 0, len(sub) - 1 while left < right: mid = (left + right) >> 1 if sub[mid] >= val: right = mid else: left = mid + 1 return left sub_list = [] for val in nums: if len(sub_list) == 0 or val > sub_list[-1][-1][0]: # should append a new element at the end cur_count = sum([x[1] for x in sub_list[-1] if val > x[0]]) if len(sub_list) != 0 else 1 sub_list.append([(val, cur_count)]) else: # get the last number to turn it back to a LIS problem cur_sub = [array[-1][0] for array in sub_list] pos = find_pos(cur_sub, val) # if pos == 0, means it is smallest, no need to look the previous level and set it to be 1 cur_count = sum([x[1] for x in sub_list[pos - 1] if val > x[0]]) if pos > 0 else 1 sub_list[pos].append((val, cur_count)) return sum([x[1] for x in sub_list[-1]])
class Solution { public int findNumberOfLIS(int[] nums) { int N = nums.length; int []dp =new int[N]; int []count = new int[N]; Arrays.fill(dp,1);Arrays.fill(count,1); int maxi = 1; for(int i=0;i<N;i++){ for(int j=0;j<i;j++){ if(nums[j] < nums[i] && dp[j]+1 > dp[i]){ dp[i] = dp[j]+1; //inherit a new one count[i]=count[j]; maxi = Math.max(dp[i],maxi); }else if(nums[j] < nums[i] && dp[j]+1 == dp[i]){ //got one as same len, increase count count[i]+=count[j]; } } }//for ends int maxlis=0; for(int i=0;i<N;i++){ if(maxi == dp[i]){ maxlis+=count[i]; } } return maxlis; } }
class Solution { public: int findNumberOfLIS(vector<int>& nums) { int n = nums.size(), maxI=0, inc=0; vector<int> dp(n,1), count(n,1); for(int i=0;i<n;i++) { for(int j=0;j<i;j++){ if(nums[i]>nums[j] && 1+dp[j] > dp[i]) { dp[i] = 1+dp[j]; count[i] = count[j]; } else if(nums[i]>nums[j] && 1+dp[j] == dp[i]) count[i] += count[j]; } maxI = max(maxI, dp[i]); } for(int i=0;i<n;i++) if(maxI == dp[i]) inc += count[i]; return inc; } };
var findNumberOfLIS = function(nums) { const { length } = nums; const dpLength = Array(length).fill(1); const dpCount = Array(length).fill(1); for (let right = 0; right < length; right++) { for (let left = 0; left < right; left++) { if (nums[left] >= nums[right]) continue; if (dpLength[left] + 1 === dpLength[right]) { dpCount[right] += dpCount[left]; } else if (dpLength[left] + 1 > dpLength[right]) { dpLength[right] = dpLength[left] + 1; dpCount[right] = dpCount[left]; } } } const maxLength = Math.max(...dpLength); return dpLength.reduce((result, length, index) => { const count = dpCount[index]; return result + (maxLength === length ? count : 0); }, 0); };
Number of Longest Increasing Subsequence
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4]. Example 2: Input: arr = [5,4,3,2,1] Output: 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]. Example 3: Input: arr = [1,2,3] Output: 0 Explanation: The array is already non-decreasing. We do not need to remove any elements. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 105 0 &lt;= arr[i] &lt;= 109
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: n = len(arr) i = 0 while i < n-1 and arr[i+1] >= arr[i]: i += 1 if i == n-1: return 0 j = n-1 while j >= 0 and arr[j-1] <= arr[j]: j -= 1 ans = min(n, n-i-1, j) for l in range(i+1): r = j while r < n and arr[r] < arr[l]: r += 1 ans = min(ans, r-l-1) return ans
class Solution { public int findLengthOfShortestSubarray(int[] arr) { int firstLast=0,lastFirst=arr.length-1; for(;firstLast<arr.length-1;firstLast++){ if(arr[firstLast]>arr[firstLast+1]) break; } //Base case for a non-decreasing sequence if(firstLast==arr.length-1) return 0; for( ;lastFirst>0;lastFirst--){ if(arr[lastFirst]<arr[lastFirst-1]) break; } //Possibilities 1 or 2 as mentioned above int minLength=Math.min(arr.length-firstLast-1,lastFirst); for(;firstLast>=0;firstLast--){ for(int i=lastFirst;i<arr.length;i++){ if(arr[firstLast]>arr[i]) continue; minLength = Math.min(minLength,i-firstLast-1); break; } } return minLength; } }
// itne me hi thakk gaye? class Solution { public: bool ok(int &size, vector<int> &pref, vector<int> &suff, vector<int> &arr, int &n) { for(int start=0; start<=n-size; start++) { int end = start + size - 1; int left = (start <= 0) ? 0 : pref[start-1]; int right = (end >= n-1) ? 0 : suff[end+1]; int le = (start <= 0) ? -1e9+2 : arr[start-1]; int re = (end >= n-1) ? 1e9+2 : arr[end+1]; if (left + right == n-size && le <= re) { return true; } } return false; } int findLengthOfShortestSubarray(vector<int>& arr) { int n = arr.size(); if (!n || n==1) return 0; vector<int> pref(n, 1); vector<int> suff(n, 1); for(int i=1; i<n; i++) { if (arr[i] >= arr[i-1]) pref[i] = pref[i-1]+1; } for(int i=n-2; i>=0; i--) { if (arr[i] <= arr[i+1]) suff[i] = suff[i+1]+1; } int low = 0; int high = n-1; while(low < high) { int mid = (low + high)/2; if(ok(mid, pref, suff, arr, n)) high = mid; else low = mid+1; if(high - low == 1) break; } if (ok(low, pref, suff, arr, n)) return low; return high; } };
var findLengthOfShortestSubarray = function(arr) { const n = arr.length; if (n <= 1) { return 0; } let prefix = 1; while (prefix < n) { if (arr[prefix - 1] <= arr[prefix]) { prefix++; } else { break; } } if (prefix === n) { return 0; } let suffix = 1; while (suffix < n) { const i = n - 1 - suffix; if (arr[i] <= arr[i + 1]) { suffix++; } else { break; } } let res = Math.min(n - prefix, n - suffix); let left = 0; let right = n - suffix; while (left < prefix && right < n) { if (arr[left] <= arr[right]) { res = Math.min(res, right - left - 1); left++; } else { right++; } } return res; };
Shortest Subarray to be Removed to Make Array Sorted
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. &nbsp; Example 1: Input: s = "00110110", k = 2 Output: true Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively. Example 2: Input: s = "0110", k = 1 Output: true Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. Example 3: Input: s = "0110", k = 2 Output: false Explanation: The binary code "00" is of length 2 and does not exist in the array. &nbsp; Constraints: 1 &lt;= s.length &lt;= 5 * 105 s[i] is either '0' or '1'. 1 &lt;= k &lt;= 20
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: Z = set() for i in range(len(s)-k+1): Z.add(s[i:i+k]) if len(Z) == 2**k: return True return False
class Solution { public boolean hasAllCodes(String s, int k) { HashSet<String> hs=new HashSet(); for(int i=0;i<=s.length()-k;i++){ hs.add(s.substring(i,i+k)); } if(hs.size() == Math.pow(2,k))return true; return false; } }
class Solution { public: bool hasAllCodes(string s, int k) { if (s.size() < k) { return false; } unordered_set<string> binary_codes; for (int i = 0; i < s.size()-k+1; i++) { string str = s.substr(i, k); binary_codes.insert(str); if (binary_codes.size() == (int)pow(2, k)) { return true; } } return false; } };
/** * @param {string} s * @param {number} k * @return {boolean} */ var hasAllCodes = function(s, k) { if (k > s.length) { return false; } /* Max strings can be generated of k chars 0/1. */ const max = Math.pow(2, k); /* * Create a set. * It will contain all unique values. */ const set = new Set(); for(let i = 0; i < s.length - k + 1; i++) { /* Generate substring of size k from index i */ const substr = s.substr(i, k); set.add(substr); /* * if enough of unique strings are generated, * break the loop as there is no point of iterating * as we have found all necessary strings. */ if (set.size === max) { return true; } } return set.size === max; };
Check If a String Contains All Binary Codes of Size K
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. &nbsp; Example 1: Input: s1 = "xx", s2 = "yy" Output: 1 Explanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx". Example 2: Input: s1 = "xy", s2 = "yx" Output: 2 Explanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx". Swap s1[0] and s2[1], s1 = "xy", s2 = "xy". Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings. Example 3: Input: s1 = "xx", s2 = "xy" Output: -1 &nbsp; Constraints: 1 &lt;= s1.length, s2.length &lt;= 1000 s1, s2 only contain 'x' or 'y'.
class Solution: def minimumSwap(self, s1: str, s2: str) -> int: h = defaultdict(int) count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd for i in range(len(s1)): if s1[i] != s2[i]: count += 1 h[s1[i]] += 1 if count % 2 != 0: return -1 res, a, b = 0, h['x'], h['y'] res += a // 2 + b // 2 if a % 2 == 0: return res return res + 2
class Solution { public int minimumSwap(String s1, String s2) { if(s1.length() != s2.length()) return -1; int n = s1.length(); int x = 0 , y = 0; for(int i = 0 ; i < n ; i ++){ char c1 = s1.charAt(i) , c2 = s2.charAt(i); if(c1 == 'x' && c2 == 'y') x++; else if(c1 == 'y' && c2 == 'x') y++; } if(x % 2 == 0 && y % 2 == 0) return x/2 + y/2; else if(x % 2 == 1 && y % 2 == 1) return x/2 + y/2 + 2; return -1; } }
class Solution { public: int minimumSwap(string s1, string s2) { int n = s1.size(); int cnt1=0,cnt2=0,i=0; while(i<n){ int x = s1[i]; int y = s2[i++]; if(x=='x' and y=='y') cnt1++; if(x=='y' and y=='x') cnt2++; } if((cnt1+cnt2)%2==1) return -1; return (cnt1/2) + (cnt2/2) + (cnt1%2 + cnt2%2); } };
var minimumSwap = function(s1, s2) { let count1 = 0; let count2 = 0; for(let i in s1) { if(s1[i] === "x" && s2[i] === "y") { count1++ } if(s1[i] === "y" && s2[i] === "x") { count2++ } } let ans = Math.floor(count1 / 2) + Math.floor(count2 / 2); if(count1 % 2 === 0 && count2 % 2 === 0){ return ans } else if(count1 % 2 !== 0 && count2 % 2 !== 0){ return ans + 2; } else { return -1; } };
Minimum Swaps to Make Strings Equal
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. &nbsp; Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 nums[i] is either 0 or 1. 0 &lt;= k &lt;= nums.length
# TC : O(N) # SC : O(1) class Solution: def longestOnes(self, nums: List[int], k: int) -> int: z_count = 0 #count zeors in nums mx_ones = 0 j = 0 for i in range(len(nums)): if nums[i] == 0: z_count+=1 while z_count>k:#if zeros count cross k decrease count if nums[j] == 0: z_count-=1 j+=1 print(i,j) mx_ones = max(mx_ones, i-j+1) return mx_ones
class Solution { public int longestOnes(int[] nums, int k) { int ans = 0; int j = -1; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { count++; } while (count > k) { j++; if (nums[j] == 0) { count--; } } int len = i - j; if (len > ans) ans = len; } return ans; } }
class Solution { public: int longestOnes(vector<int>& nums, int k) { // max length of subarray with at most k zeroes int i=0; int j=0; int cnt = 0; int ans = 0; int n = nums.size(); while(j<n) { if(nums[j]==0) cnt++; if(cnt<=k) { ans = max(ans , j-i+1); j++; } else //cnt>k { while(cnt>k) { if(nums[i]==0) cnt--; i++; } j++; } } return ans; } };
* @param {number[]} nums * @param {number} k * @return {number} */ var longestOnes = function(nums, k) { let left = 0; let oneCount = 0; let maxLength = 0; for (let right = 0; right < nums.length; right ++) { if (nums[right]) { // so if the element is a 1 since 0 is falsy oneCount++ } if ((right - left + 1 - oneCount) > k) { // check if we've used all of our replacements if (nums[left]) { // start shrinking the window if its a 1 we subtract a count from oneCount oneCount-- } left++ } maxLength = Math.max(maxLength, right - left + 1); // update maxLength each iteration for largest window } return maxLength };
Max Consecutive Ones III
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1. Return the length of the longest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node. &nbsp; Example 1: Input: edges = [3,3,4,2,3] Output: 3 Explanation: The longest cycle in the graph is the cycle: 2 -&gt; 4 -&gt; 3 -&gt; 2. The length of this cycle is 3, so 3 is returned. Example 2: Input: edges = [2,-1,3,1] Output: -1 Explanation: There are no cycles in this graph. &nbsp; Constraints: n == edges.length 2 &lt;= n &lt;= 105 -1 &lt;= edges[i] &lt; n edges[i] != i
class Solution: def longestCycle(self, edges: List[int]) -> int: preorder = [-1 for _ in range(len(edges))] self.ans = -1 self.pre = 0 def dfs(self, i: int, st: int) -> None: preorder[i] = self.pre self.pre += 1 if edges[i] == -1: return elif preorder[edges[i]] == -1: dfs(self, edges[i], st) return elif preorder[edges[i]] >= st: self.ans = max(self.ans, preorder[i] - preorder[edges[i]] + 1) return for i in range(len(edges)): if preorder[i] == -1 and edges[i] != -1: dfs(self, i, self.pre) return self.ans
class Solution { public int longestCycle(int[] edges) { int[] map = new int[edges.length]; int result = -1; for (int i = 0; i < edges.length; i++) result = Math.max(result, helper(i, 1, edges, map)); return result; } int helper(int index, int total, int[] edges, int[] map) { if (index == -1 || map[index] == -1) return -1; if (map[index] != 0) return total - map[index]; map[index] = total; int result = helper(edges[index], total + 1, edges, map); map[index] = -1; return result; } }
class Solution { public: int maxLength = -1; void getcycle(vector<int> &edges,int si,vector<bool>& visit,vector<int>& store){ if(si == -1)return ; if(visit[si]){ int count = -1; for(int i =0;i<store.size();i++){ if(store[i]==si){ count = i; break; } } if(count==-1)return; int size = (store.size()-count); maxLength = max(maxLength,size); return ; } visit[si] = true; store.push_back(si); getcycle(edges,edges[si],visit,store); return ; } int longestCycle(vector<int>& edges) { vector<bool> visit(edges.size(),0); for(int i =0;i<edges.size();i++){ if(visit[i])continue; vector<int> store; getcycle(edges,i,visit,store); } return maxLength; } };
/** * @param {number[]} edges * @return {number} */ function getCycleTopology(edges){ const indeg = new Array(edges.length).fill(0); const queue = []; const map = {}; for(const src in edges){ const des = edges[src] if(des >= 0){ indeg[des] ++; } map[src] ? map[src].push(des) : map[src] = [des] } for(const node in indeg){ if(indeg[node] === 0){ queue.push(node) } } while(queue.length > 0){ const node = queue.shift(); for(const connectedNode of map[node]){ if(connectedNode !== -1){ indeg[connectedNode] --; if(indeg[connectedNode] === 0){ queue.push(connectedNode); } } } } return indeg } class DisjointSet{ constructor(n){ this.n = n; this.root = new Array(n).fill(0).map((_,i) => i); this.rank = new Array(n).fill(1); } find(x){ if(x === this.root[x]) return x; return this.root[x] = this.find(this.root[x]); } union(x,y){ const x_root = this.find(x); const y_root = this.find(y); if(this.rank[x_root] < this.rank[y_root]){ [this.rank[x_root] , this.rank[y_root]] = [this.rank[y_root] , this.rank[x_root]]; } this.root[y_root] = x_root; if(this.rank[x_root] === this.rank[y_root]) this.rank[x_root] ++; } _getGroupsComponentCounts(){ let groups = {}; for(const node of this.root){ const node_root = this.find(node); groups[node_root] = groups[node_root] +1 || 1 } return groups } getLongestGroupComponentLength(){ let longestLength = 1; const lengths = this._getGroupsComponentCounts(); for(const length of Object.values(lengths)){ if(length > 1){ longestLength = Math.max(longestLength, length); } } return longestLength > 1 ? longestLength : -1; } } var longestCycle = function(edges) { const djs = new DisjointSet(edges.length); let res = -1 // topology sort results topology array. // component with greater than 0 is cyclic component. // now we need to get groups of cycle since we can't distinguish each cycles with current datas. const cycleComponent = getCycleTopology(edges); //with edges info and cycle component data, we can now distinguish each cycle group by union finde // because each cycle r independent with each other. for(const src in edges){ const des = edges[src]; if(cycleComponent[src] && cycleComponent[des]){ djs.union(src, des); } } res = djs.getLongestGroupComponentLength() return res };
Longest Cycle in a Graph
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. &nbsp; Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -&gt; 4, push(5), pop() -&gt; 5, pop() -&gt; 3, pop() -&gt; 2, pop() -&gt; 1 Example 2: Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] Output: false Explanation: 1 cannot be popped before 2. &nbsp; Constraints: 1 &lt;= pushed.length &lt;= 1000 0 &lt;= pushed[i] &lt;= 1000 All the elements of pushed are unique. popped.length == pushed.length popped is a permutation of pushed.
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] i=0 for num in pushed: stack.append(num) #we are pushing the number to the stack while len(stack) >0 and stack[len(stack)-1] == popped[i] : #if the last element of the stack is equal to the popped element stack.pop() i+=1 #we are incrementing i return True if len(stack) ==0 else False
class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { Stack<Integer> st = new Stack<>(); // Create a stack int j = 0; // Intialise one pointer pointing on popped array for(int val : pushed){ st.push(val); // insert the values in stack while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j]; st.pop(); // then pop out j++; // increment j } } return st.isEmpty(); // check if stack is empty return true else false } }
class Solution { public: bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { stack<int> st; // Create a stack int j = 0; // Intialise one pointer pointing on popped array for(auto val : pushed){ st.push(val); // insert the values in stack while(st.size() > 0 && st.top() == popped[j]){ // if st.peek() values equal to popped[j]; st.pop(); // then pop out j++; // increment j } } return st.size() == 0; // check if stack is empty return true else false } };
var validateStackSequences = function(pushed, popped) { let stack = []; let j = 0; for(let i=0; i<pushed.length; i++){ stack.push(pushed[i]); while(stack.length != 0 && popped[j]== stack[stack.length-1]){ stack.pop(); j++ } } return stack.length<1 };
Validate Stack Sequences
You are given a 0-indexed positive integer array nums and a positive integer k. A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Both the numbers num1 and num2 exist in the array nums. The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation. Return the number of distinct excellent pairs. Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array. &nbsp; Example 1: Input: nums = [1,2,3,1], k = 3 Output: 5 Explanation: The excellent pairs are the following: - (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3. - (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. - (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3. So the number of excellent pairs is 5. Example 2: Input: nums = [5,1,1], k = 10 Output: 0 Explanation: There are no excellent pairs for this array. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 109 1 &lt;= k &lt;= 60
class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: hamming = sorted([self.hammingWeight(num) for num in set(nums)]) ans = 0 for h in hamming: ans += len(hamming) - bisect.bisect_left(hamming, k - h) return ans def hammingWeight(self, n): ans = 0 while n: n &= (n - 1) ans += 1 return ans
class Solution { public long countExcellentPairs(int[] nums, int k) { HashMap<Integer,Set<Integer>> map = new HashMap<>(); for(int i : nums){ int x = Integer.bitCount(i); map.putIfAbsent(x,new HashSet<>()); map.get(x).add(i); } long ans = 0; HashSet<Integer> vis = new HashSet<>(); for(int i : nums){ if(vis.contains(i)) continue; int need = Math.max(0,k-Integer.bitCount(i)); for(int key : map.keySet()) // runs at max 30 times if(key >= need) ans += (long) map.get(key).size(); vis.add(i); } return ans; } }
class Solution { public: typedef long long ll; int setbits(int n){ int cnt = 0; while(n){ cnt += (n%2); n /= 2; } return cnt; } long long countExcellentPairs(vector<int>& nums, int k) { unordered_set<int> s(nums.begin(),nums.end()); vector<int> v; for(auto& i: s){ int x = setbits(i); v.push_back(x); } sort(v.begin(),v.end()); ll ans = 0; for(int i=0;i<v.size();i++){ auto it = lower_bound(v.begin(),v.end(),k-v[i]); ans += (v.end()-it); } return ans; } };
var countExcellentPairs = function(nums, k) { const map = new Map(); const set = new Set(); const l = nums.length; let res = 0; for (let num of nums) { let temp = num.toString(2).split("1").length - 1; if (!map.has(temp)) { map.set(temp, new Set([num])); } else { map.get(temp).add(num); } } for (let num of nums) { let temp = num.toString(2).split("1").length - 1; if(!set.has(num)) { let gap = Math.max(0, k - temp) for (let key of map.keys()) { if (key >= gap) { res += map.get(key).size; } } set.add(num); }else { continue; } } return res; };
Number of Excellent Pairs
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| &lt;= d. &nbsp; Example 1: Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 Output: 2 Explanation: For arr1[0]=4 we have: |4-10|=6 &gt; d=2 |4-9|=5 &gt; d=2 |4-1|=3 &gt; d=2 |4-8|=4 &gt; d=2 For arr1[1]=5 we have: |5-10|=5 &gt; d=2 |5-9|=4 &gt; d=2 |5-1|=4 &gt; d=2 |5-8|=3 &gt; d=2 For arr1[2]=8 we have: |8-10|=2 &lt;= d=2 |8-9|=1 &lt;= d=2 |8-1|=7 &gt; d=2 |8-8|=0 &lt;= d=2 Example 2: Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3 Output: 2 Example 3: Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6 Output: 1 &nbsp; Constraints: 1 &lt;= arr1.length, arr2.length &lt;= 500 -1000 &lt;= arr1[i], arr2[j] &lt;= 1000 0 &lt;= d &lt;= 100
class Solution: def findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int: result = 0 array2 = sorted(array2) for num in array1: flag = True low = 0 high = len(array2)-1 while low <= high: mid = (low + high) // 2 if abs(array2[mid] - num) <= d: flag = False break elif array2[mid] > num: high = mid - 1 else: low = mid + 1; if flag == True: result = result + 1 return result
class Solution { public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { int x=0,val=0; for(int i:arr1){ for(int j:arr2){ if(Math.abs(i-j)<=d){ x--; break; } } x++; } return x; } }
class Solution { public: int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) { sort(arr2.begin(),arr2.end()); int ans = 0; for(int i : arr1){ int id = lower_bound(arr2.begin(),arr2.end(),i) - arr2.begin(); int closest = d+1; if(id != arr2.size()){ closest = min(abs(arr2[id]-i), closest); } if(id != 0){ closest = min(abs(arr2[id-1]-i), closest); } if(closest > d) ans++; } return ans; } };
/** * @param {number[]} arr1 * @param {number[]} arr2 * @param {number} d * @return {number} */ var findTheDistanceValue = function(arr1, arr2, d) { const arr2Sorted = arr2.sort((a, b) => a - b); let dist = 0; for (const num of arr1) { if (isDistanceValid(num, d, arr2Sorted)) { dist += 1; } } return dist; }; function isDistanceValid(number, dist, array) { let left = 0; let right = array.length - 1; while (left <= right) { const mid = Math.floor((right + left) / 2); if (Math.abs(number - array[mid]) <= dist) { return false; } if (array[mid] < number) { left = mid + 1; } if (array[mid] > number) { right = mid - 1; } } return true; }
Find the Distance Value Between Two Arrays
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. &nbsp; Example 1: Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' were long pressed. Example 2: Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' must have been pressed twice, but it was not in the typed output. &nbsp; Constraints: 1 &lt;= name.length, typed.length &lt;= 1000 name and typed consist of only lowercase English letters.
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: #dic for memoization dic = {} def dfs(i, j): if (i, j) in dic: return dic[(i, j)] #see if there is any case where both i and j reach to the end, cuz that will be the true condition #I only need one True if i >= len(name): return j == len(typed) #we iterated through the end of typed, and not yet for name if j >= len(typed): return False #if the characters don't match, return False if name[i] != typed[j]: dic[(i, j)] = False return False #if the two characters match #two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1)) #return if any of them is True, which means that i, j reach to the end as aforementioned dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1) return dic[(i, j)] #start from index 0, 0 return dfs(0, 0)
class Solution { public boolean isLongPressedName(String name, String typed) { int i = 0; int j = 0; int m = name.length(); int n = typed.length(); while(j < n) { if(i < m && name.charAt(i) == typed.charAt(j)) { i++; j++; } else if(j > 0 && typed.charAt(j) == typed.charAt(j-1)) { j++; } else { return false; } } return i == m; } }
class Solution { public: bool isLongPressedName(string name, string typed) { int j = 0, i = 0; for( ; i<name.length() && j<typed.length() ; i++) { if(name[i]!=typed[j++]) return false; if(i<name.length() && name[i]!= name[i+1]) { while(j<typed.length() && typed[j] == name[i]) j++; } } return (i == name.length() && j == typed.length()); } };
var isLongPressedName = function(name, typed) { let i = 0; let j = 0; while (j < typed.length) { if (i < name.length && name[i] === typed[j]) i++; else if (typed[j] !== typed[j - 1]) return false; // this needs when name is traversed but there is tail of characters in typed j++; // Base case. keep going through typed anyway hitting first condition from time to time: (i < name.length && name[i] === typed[j]) } return i === name.length; };
Long Pressed Name
You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li &lt;= j &lt;= ri is colored white. You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. Return the maximum number of white tiles that can be covered by the carpet. &nbsp; Example 1: Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10 Output: 9 Explanation: Place the carpet starting on tile 10. It covers 9 white tiles, so we return 9. Note that there may be other places where the carpet covers 9 white tiles. It can be shown that the carpet cannot cover more than 9 white tiles. Example 2: Input: tiles = [[10,11],[1,1]], carpetLen = 2 Output: 2 Explanation: Place the carpet starting on tile 10. It covers 2 white tiles, so we return 2. &nbsp; Constraints: 1 &lt;= tiles.length &lt;= 5 * 104 tiles[i].length == 2 1 &lt;= li &lt;= ri &lt;= 109 1 &lt;= carpetLen &lt;= 109 The tiles are non-overlapping.
class Solution: def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: tiles.sort() #j: window index j = cover = res = 0 for i in range(len(tiles)): #slide the window as far as we can to cover fully the intervals with the carpet while j<len(tiles) and tiles[j][1]-tiles[i][0] + 1 <= carpetLen: cover += tiles[j][1]-tiles[j][0] + 1 j += 1 #process the remnant, that is, when the tiles[j] is covered by the carpet partially(not fully) if j<len(tiles) and tiles[j][0]-tiles[i][0] + 1 <= carpetLen: res = max(res, cover + carpetLen-(tiles[j][0]-tiles[i][0])) else: res = max(res, cover) #when the tiles[j] is covered partially, the interval is not added to the variable cover if i!=j: cover -= tiles[i][1]-tiles[i][0]+1 j = max(j, i+1) return res
class Solution { public int maximumWhiteTiles(int[][] tiles, int carpetLen) { Arrays.sort(tiles,(a,b)->{return a[0]-b[0];}); int x = 0; int y = 0; long maxCount = 0; long count = 0; while(y < tiles.length && x <= y) { long start = tiles[x][0]; long end = tiles[y][1]; if(end-start+1 <= carpetLen) { count += tiles[y][1] - tiles[y][0]+1; maxCount = Math.max(maxCount,count); y++; } else { long midDist = start+carpetLen-1; long s = tiles[y][0]; long e = tiles[y][1]; if(midDist <= e && midDist >= s) maxCount = Math.max(maxCount,count+midDist-s+1); count -= tiles[x][1] - tiles[x][0] + 1; x++; } } return (int)maxCount; } }
class Solution { public: int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) { long long n = tiles.size() , ans = INT_MIN; sort(tiles.begin(),tiles.end()); vector<long long> len(n) , li(n); //len array stores the prefix sum of tiles //li array stores the last index tiles[i] for(int i=0;i<n;i++){ len[i] = (long long)(tiles[i][1] - tiles[i][0] + 1); len[i]+=(i==0) ? 0 : len[i-1]; li[i] = tiles[i][1]; } for(int i=0 ; i<n ; i++){ //sp means starting tile index //ep means ending tile index long long sp = tiles[i][0] , ep = tiles[i][0] + (long long)carpetLen-1 , tc=0; int idx = lower_bound(li.begin(),li.end(),ep) - li.begin(); //logic to take count of tiles covered if(idx==n){ tc = len[n-1]; tc-=(i==0) ? 0 : len[i-1]; }else{ tc = ep<tiles[idx][0] ? 0 : ep - (long long)tiles[idx][0] + 1; idx--; if(idx>=0){ tc+=len[idx]; tc-=(i==0) ? 0 : len[i-1]; } } ans = max(ans,tc); } return (int)ans; } };
/** * @param {number[][]} tiles * @param {number} carpetLen * @return {number} */ var maximumWhiteTiles = function(tiles, carpetLen) { const sorted = tiles.sort((a, b) => a[0]-b[0]) let res = 0 let total = 0 let right = 0 for (let tile of sorted){ const start = tile[0] const end = start + carpetLen - 1 while(right < sorted.length && tiles[right][1] < end){ total += tiles[right][1] - tiles[right][0] + 1 right+=1 } if(right === sorted.length || sorted[right][0] > end){ res = Math.max(res, total) } else{ res = Math.max(res, total + (end-tiles[right][0] + 1)) } total -= tile[1] - tile[0] + 1 } return res };
Maximum White Tiles Covered by a Carpet
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. &nbsp; Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -104 &lt;= nums[i] &lt;= 104 nums is sorted in non-decreasing order. &nbsp; Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l,r = 0, len(nums)-1 pointer = 0 arr = [0] *len(nums) pointer = r while l<=r: if abs(nums[r]) > abs(nums[l]): arr[pointer] = nums[r] **2 r-=1 pointer-=1 else: arr[pointer] = nums[l] **2 l+=1 pointer-=1 return arr
class Solution { public int[] sortedSquares(int[] nums) { int s=0; int e=nums.length-1; int p=nums.length-1; int[] a=new int[nums.length]; while(s<=e){ if(nums[s]*nums[s]>nums[e]*nums[e]){ a[p--]=nums[s]*nums[s]; s++; } else{ a[p--]=nums[e]*nums[e]; e--; } } return a; } }
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { for(int i=0;i<nums.size();i++){ nums[i] = nums[i]*nums[i]; } sort(nums.begin(),nums.end()); return nums; } };
var sortedSquares = function(nums) { let left = 0; let right = nums.length - 1; const arr = new Array(nums.length); let arrIndex = arr.length - 1; while (left <= right) { if (Math.abs(nums[left]) > Math.abs(nums[right])) { arr[arrIndex] = nums[left] * nums[left]; left++; } else { arr[arrIndex] = nums[right] * nums[right]; right--; } arrIndex--; } return arr; };
Squares of a Sorted Array
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1). &nbsp; Example 1: Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] Output: 13 Explanation: There are two falling paths with a minimum sum as shown. Example 2: Input: matrix = [[-19,57],[-40,-5]] Output: -59 Explanation: The falling path with a minimum sum is shown. &nbsp; Constraints: n == matrix.length == matrix[i].length 1 &lt;= n &lt;= 100 -100 &lt;= matrix[i][j] &lt;= 100
class Solution: def minFallingPathSum(self, matrix: List[List[int]]) -> int: for row in range(1, len(matrix)): for col in range(0, len(matrix[row])): if col == 0: matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col]) elif col == len(matrix[row]) - 1: matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col]) else: matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col], matrix[row-1][col+1]) return min(matrix[-1])
class Solution { public int min(int[][] matrix, int[][]dp, int i, int j) { int a,b,c; if(i==0) return matrix[i][j]; if(dp[i][j] != Integer.MAX_VALUE) return dp[i][j]; if(j==0) { dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1))+matrix[i][j]; } else if(j==matrix.length -1) { dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j-1))+matrix[i][j]; } else { dp[i][j] = Math.min(Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1)),min(matrix, dp, i-1, j-1))+matrix[i][j]; } return dp[i][j]; } public int minFallingPathSum(int[][] matrix) { int dp[][] = new int[matrix.length][matrix.length]; if(matrix.length == 1) return matrix[0][0]; for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix.length;j++) dp[i][j] = Integer.MAX_VALUE; int min=Integer.MAX_VALUE; for(int i=0;i<matrix.length; i++) { min = Math.min(min, min(matrix, dp, matrix.length-1,i)); } return min; } }
class Solution { public: int check( int i , int j , int n ){ if( i <0 || j<0 || i>=n || j>=n ) return 0; return 1; } int solve(vector<vector<int>>&mat , int i , int j , int n , vector<vector<int>>&dp ){ if(not check( i , j , n )) return 999999; if(i == n-1 && j < n )return mat[i][j]; if(dp[i][j]!= -1 ) return dp[i][j]; int op_1 = mat[i][j] + solve(mat , i+1, j - 1 , n , dp ); int op_2 = mat[i][j] + solve(mat , i+1 , j , n , dp ); int op_3 = mat[i][j] + solve(mat , i+1 , j + 1 , n , dp ); return dp[i][j] = min( {op_1 , op_2 , op_3} ); } int minFallingPathSum(vector<vector<int>>& matrix) { int n = matrix[0].size(); // vector<vector<int>>dp(n+1 , vector<int>(n +1 , -1 )); // int ans = INT_MAX; // for(int i = 0 ; i<n ; ++i ) // ans = min( ans , solve( matrix , 0, i , n , dp )); vector<vector<int>>dp(n , vector<int>(n, 0)); for( int i =0 ; i<n ; ++i ) dp[0][i] = matrix[0][i]; for( int i =1 ; i<n ; ++i ){ for( int j = 0 ; j<n ; ++j ){ if(j-1>=0 && j+1 < n ) dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] , dp[i-1][j] , dp[i-1][j+1] }); else if(j == 0 ) dp[i][j] = matrix[i][j] + min( { dp[i-1][j] , dp[i-1][j+1] }); else if(j == n-1 ) dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] , dp[i-1][j] }); } } int ans = INT_MAX; for( int i = 0 ; i<n ; ++i ) ans = min( ans , dp[n-1][i]); return ans ; } };
var minFallingPathSum = function(matrix) { let n = matrix.length; let m = matrix[0].length; let dp = new Array(n).fill(0).map(() => new Array(m).fill(0)); // tabulation // bottom-up approach // base case - when i will be 0, dp[0][j] will be matrix[0][j] for(let j = 0; j < m; j++) dp[0][j] = matrix[0][j] for(let i = 1; i < n; i++) { for(let j = 0 ; j < m; j++) { let up = matrix[i][j] + dp[i - 1][j]; let upLeft = matrix[i][j]; if((j - 1) >= 0) upLeft += dp[i - 1][j - 1]; // if not out of bound else upLeft += 10000; // big enough number let upRight = matrix[i][j]; if((j + 1) < m) upRight += dp[i - 1][j + 1]; // if not out of bound else upRight += 10000; // big enough number dp[i][j] = Math.min(up, upLeft, upRight); } } return Math.min(...dp[n - 1]); };
Minimum Falling Path Sum
You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i &lt; j and j - i != nums[j] - nums[i]. Return the total number of bad pairs in nums. &nbsp; Example 1: Input: nums = [4,1,3,3] Output: 5 Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4. The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1. The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1. The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2. The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0. There are a total of 5 bad pairs, so we return 5. Example 2: Input: nums = [1,2,3,4,5] Output: 0 Explanation: There are no bad pairs. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 109
class Solution: def countBadPairs(self, nums: List[int]) -> int: nums_len = len(nums) count_dict = dict() for i in range(nums_len): nums[i] -= i if nums[i] not in count_dict: count_dict[nums[i]] = 0 count_dict[nums[i]] += 1 count = 0 for key in count_dict: count += math.comb(count_dict[key], 2) return math.comb(nums_len, 2) - count
class Solution { public long countBadPairs(int[] nums) { HashMap<Integer, Integer> seen = new HashMap<>(); long count = 0; for(int i = 0; i < nums.length; i++){ int diff = i - nums[i]; if(seen.containsKey(diff)){ count += (i - seen.get(diff)); }else{ count += i; } seen.put(diff, seen.getOrDefault(diff, 0) + 1); } return count; } }
class Solution { public: long long countBadPairs(vector<int>& nums) { //j - i != nums[j] - nums[i] means nums[i]-i != nums[j]-j map<long long,long long >mp; for(int i=0;i<nums.size();i++) { nums[i] = nums[i]-i; mp[nums[i]]++; } long long n = nums.size(); long long totalPair = n*(n-1)/2; for(auto& it:mp) { if(it.second>1) { totalPair -= (it.second)*(it.second-1)/2; } } return totalPair; } };
/** * @param {number[]} nums * @return {number} */ var countBadPairs = function(nums) { let map={},goodPair=0; for(let i=0;i<nums.length;i++){ let value = nums[i]-i; if(map[value]!==undefined){ goodPair += map[value]; map[value]++; }else{ map[value]=1; } } let n = nums.length; let totalPairs = n*(n-1)/2; return totalPairs-goodPair; };
Count Number of Bad Pairs
A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings. Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s. &nbsp; Example 1: Input: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: s = "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: s = "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s[i] is either '(' or ')'. s is a valid parentheses string.
class Solution: def removeOuterParentheses(self, s: str) -> str: c=0 res='' for i in s: if i==')' and c==1: c=c-1 elif i=='(' and c==0: c=c+1 elif i=='(': res=res+'(' c=c+1 elif i==')': res=res+')' c=c-1 return res
class Solution { public String removeOuterParentheses(String s) { // if '(' check stack size > 0 add ans else not add ans // if ')' check stack size > 0 add ans else not add ans Stack<Character> st = new Stack<>(); StringBuilder sb = new StringBuilder(); for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if(ch == '('){ if(st.size() > 0){ sb.append(ch); } st.push(ch); } else{ st.pop(); if(st.size() > 0){ sb.append(ch); } } } return sb.toString(); } }
class Solution { public: stack<char>p; int count=0; string removeOuterParentheses(string s) { string ans={}; for(auto &i:s){ if(i=='(' && count==0){ p.push(i); count++; } else if (i=='(' && count!=0){ ans+='('; p.push(i); count++; } else{ count--; p.pop(); if(count>0) ans+=')'; } } return ans; } };
var removeOuterParentheses = function(s) { let open = -1, ans = "", stack = []; for(let c of s) { if(c == '(') { // open for top level open if(open != -1) ans += c; stack.push(open) open++; } else { open = stack.pop(); // close for top level open if(open != -1) ans += c; } } return ans; };
Remove Outermost Parentheses
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. &nbsp; Example 1: Input: nums = [7,2,5,10,8], m = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. Example 2: Input: nums = [1,2,3,4,5], m = 2 Output: 9 Example 3: Input: nums = [1,4,4], m = 3 Output: 4 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt;= 106 1 &lt;= m &lt;= min(50, nums.length)
class Solution: def splitArray(self, nums: List[int], m: int) -> int: lo, hi = max(nums), sum(nums) while lo < hi: mid = (lo+hi)//2 tot, cnt = 0, 1 for num in nums: if tot+num<=mid: tot += num else: tot = num cnt += 1 if cnt>m: lo = mid+1 else: hi = mid return hi
class Solution { int[] nums; public int splitArray(int[] nums, int m) { this.nums = nums; int low = 0, high = 0, min = Integer.MAX_VALUE; for(int i=0;i<nums.length;i++){ low = Math.max(low, nums[i]); high += nums[i]; } while(low <= high) { int mid = (low + high) / 2; if(required_no_of_chunks(mid, m)){ min = Math.min(min, mid); high = mid - 1; } else low = mid + 1; } return min; } private boolean required_no_of_chunks(int mid, int m){ int chunks = 0, i=0; while(i < nums.length){ int val = 0; while(i < nums.length && nums[i] + val <= mid) val += nums[i++]; chunks++; } return chunks <= m; } }
class Solution { public: int splitArray(vector<int>& nums, int m) { long long low = 0; long long res =0; long long high = 1000000005; while(low<=high){ long long mid = (low+high)/2; int cnt = 1; long long current_sum = 0; int can = 1; for(auto num: nums){ if(num > mid){ can = 0; break; } if(current_sum+num>mid){ cnt ++; current_sum = 0; } current_sum += num; } if(can==1){ if(cnt>m){ low = mid+1; } else{ res = mid; high = mid-1; } } else{ low = mid+1; } } return res; } };
var splitArray = function(nums, m) { const n = nums.length; var mat = []; var sumArr = [nums[0]]; for(let i=1; i<n; i++){ sumArr.push(sumArr[i-1]+nums[i]);//find prefix sum } mat.push(sumArr); for(let i=0; i<n-1;i++){//form prefix matrix, i.e. every row i shows prefix sum starting from i let arr = new Array(n).fill(0); for(let j=i+1; j<n; j++){ arr[j] = sumArr[j] - sumArr[i]; } mat.push(arr); } let memo = new Map(); let recursion = (m,lastPartition) => {// recursive partition finder if(memo[m+'_'+lastPartition]!==undefined){ return memo[m+'_'+lastPartition];//memoised } if(m==1){//base case, only 1 partition left memo[m+'_'+lastPartition] = mat[lastPartition][mat[0].length-1]; return memo[m+'_'+lastPartition]; } let min = Infinity; let maxSum = -Infinity; let lastval = Infinity; for(let i = lastPartition; i<=n-m; i++){//for mth partition, find the min sum for all possible partition placements while(i>0 && i<n-m && mat[lastPartition][i] == lastval) i++;//if a large set of values are repeating, i.e. a lot of 0s in original array, skip them lastval = mat[lastPartition][i]; maxSum = Math.max(mat[lastPartition][i],recursion(m-1,i+1));//max of current subarray sum with max from the rest of the partitions min = Math.min(min, maxSum);//minimum sum for all the possible partition values } memo[m+'_'+lastPartition] = min; return memo[m+'_'+lastPartition]; } return recursion(m,0); };
Split Array Largest Sum
Given a 2D grid of 0s and 1s, return the number of elements in&nbsp;the largest square&nbsp;subgrid that has all 1s on its border, or 0 if such a subgrid&nbsp;doesn't exist in the grid. &nbsp; Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1 &nbsp; Constraints: 1 &lt;= grid.length &lt;= 100 1 &lt;= grid[0].length &lt;= 100 grid[i][j] is 0 or 1
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)] for i in range(m): for j in range(n): if i > 0: if grid[i][j] == 1: dp[i][j][1] = dp[i - 1][j][1] + 1 if j > 0: if grid[i][j] == 1: dp[i][j][0] = dp[i][j - 1][0] + 1 for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): if i < m - 1: if grid[i][j] == 1: dp[i][j][2] = dp[i + 1][j][2] + 1 if j < n - 1: if grid[i][j] == 1: dp[i][j][3] = dp[i][j + 1][3] + 1 mside = min(m, n) for l in range(mside - 1, -1, -1): for i in range(m - l): for j in range(n - l): if min(dp[i][j][2], dp[i][j][3], dp[i + l][j + l][0], dp[i + l][j + l][1]) >= l + 1: return (l + 1) * (l + 1) return 0
class Solution { public int largest1BorderedSquare(int[][] grid) { int m=grid.length; int n=grid[0].length; // rows[r][c] is the length of the line ended at [r,c] on row r int[][] rows=new int[m][n]; // the length of the line ended at [r,c] on colume c int[][] cols=new int[m][n]; int res=0; for(int r=0;r<m;r++){ for(int c=0;c<n;c++){ if(grid[r][c]==0){ rows[r][c]=0; cols[r][c]=0; }else{ rows[r][c]=c==0?1:rows[r][c-1]+1; cols[r][c]=r==0?1:cols[r-1][c]+1; if(res>=rows[r][c]||res>=cols[r][c]){ continue; } res=Math.max(res,getD(rows,cols,r,c)); } } } return res*res; } // get the dimension of the largest square which bottom-right point is [row,col] private int getD(int[][] rows,int[][] cols,int row,int col){ int len=Math.min(rows[row][col],cols[row][col]); for(int i=len-1;i>=0;i--){ if(rows[row-i][col]>i && cols[row][col-i]>i){ return i+1; } } return 1; } }
class Solution { public: int largest1BorderedSquare(vector<vector<int>>& g) { int n=g.size(); int m=g[0].size(); int ver[n][m]; // to store lenght of continuous 1's vertically int hor[n][m]; // to store lenght of continuous 1's horizontally // fill vertical table for(int i=n-1;i>=0;i--){ for(int j=0;j<m;j++){ if(g[i][j]==1){ if(i==n-1) ver[i][j]=1; else ver[i][j]=ver[i+1][j]+1; } else ver[i][j]=0; } } // fill horizontal table for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ if(g[i][j]==1){ if(j==m-1) hor[i][j]=1; else hor[i][j]=hor[i][j+1]+1; } else hor[i][j]=0; } } // Iterate through the all i and j and find best solution int ans=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(!g[i][j]) continue; int temp=1; int k=min(hor[i][j],ver[i][j]); for(int p=1;p<k;p++){ int mn = min(hor[i+p][j],ver[i][j+p]); if(mn>=p+1) temp=p+1; } ans=max(ans,temp); } } ans*=ans; return ans; } };
var largest1BorderedSquare = function(grid) { let m = grid.length, n = grid[0].length; let top = Array(m).fill(0).map(() => Array(n).fill(0)); let left = Array(m).fill(0).map(() => Array(n).fill(0)); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1; top[i][j] = i > 0 ? top[i - 1][j] + 1 : 1; } } } let ans = 0; for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { let size = Math.min(top[i][j], left[i][j]); for (let k = size; k > 0; k--) { let bottomLeftTop = top[i][j - k + 1]; let topRightLeft = left[i - k + 1][j]; if (bottomLeftTop >= k && topRightLeft >= k) { ans = Math.max(ans, k * k); break; } } } } return ans; };
Largest 1-Bordered Square
Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array, return the new length of the array. You must write an algorithm that uses only constant extra space. &nbsp; Example 1: Input: chars = ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". Example 2: Input: chars = ["a"] Output: Return 1, and the first character of the input array should be: ["a"] Explanation: The only group is "a", which remains uncompressed since it's a single character. Example 3: Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12". &nbsp; Constraints: 1 &lt;= chars.length &lt;= 2000 chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
class Solution: def compress(self, chars: List[str]) -> int: stri = '' stack = [chars.pop(0)] while chars: p = chars.pop(0) if p in stack: stack.append(p) else: stri = stri + stack[-1] + str(len(stack) if len(stack) > 1 else '') stack = [p] o = list(stri + stack[-1] + str(len(stack) if len(stack) > 1 else '')) for i in o: chars.append(i)
class Solution { public int compress(char[] chars) { int index = 0; int i = 0; while (i < chars.length) { int j = i; while (j < chars.length && chars[j] == chars[i]) { j++; } chars[index++] = chars[i]; if (j - i > 1) { String count = j - i + ""; for (char c : count.toCharArray()) { chars[index++] = c; } } i = j; } return index; } } // TC: O(n), SC: O(1)
class Solution { public: void add1(vector<int>& arr) { if(arr.back() < 9) { arr.back()++; return ; } reverse(begin(arr),end(arr)); int carry = 1; for(int i=0;i<arr.size();i++) { if(arr[i] < 9) {arr[i]++;carry=0;break;} arr[i] = 0; carry = 1; } if(carry == 1) arr.push_back(1); reverse(begin(arr),end(arr)); } int compress(vector<char>& chars) { int i=0; for(int j=0;j<chars.size();j++) { if(j == chars.size()-1 or chars[j] != chars[j+1]) { chars[i++] = chars[j]; } else { vector<int> cnt{0}; char ch = chars[j]; while(j < chars.size()and chars[j] == ch) { j++; add1(cnt); } j--; // bcoz j will be incremented in for loop updation condition. chars[i++] = ch; for(auto& it:cnt) chars[i++] = '0'+it; } } chars.erase(chars.begin()+i,chars.end()); return i; }
var compress = function(chars) { for(let i = 0; i < chars.length; i++){ let count = 1 while(chars[i] === chars[i+count]){ delete chars[i+count] count++ } if(count > 1){ let count2 = 1 String(count).split('').forEach((a) =>{ chars[i+count2] = a count2++ }) } i = i + count -1 } return chars.flat().filter((x) => x).length };
String Compression
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t. &nbsp; Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 → 1. &nbsp; Constraints: The number of nodes in the tree is n. 2 &lt;= n &lt;= 105 1 &lt;= Node.val &lt;= n All the values in the tree are unique. 1 &lt;= startValue, destValue &lt;= n startValue != destValue
class Solution: def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: def find(n: TreeNode, val: int, path: List[str]) -> bool: if n.val == val: return True if n.left and find(n.left, val, path): path += "L" elif n.right and find(n.right, val, path): path += "R" return path s, d = [], [] find(root, startValue, s) find(root, destValue, d) while len(s) and len(d) and s[-1] == d[-1]: s.pop() d.pop() return "".join("U" * len(s)) + "".join(reversed(d))
class Solution { private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) { if(currNode == null) return false; if(currNode.val == destVal) return true; if(DFS(currNode.left, path, destVal)) path.append("L"); else if(DFS(currNode.right, path, destVal)) path.append("R"); return path.length() > 0; } public String getDirections(TreeNode root, int startValue, int destValue) { StringBuilder startToRoot = new StringBuilder(); StringBuilder endToRoot = new StringBuilder(); DFS(root, startToRoot, startValue); DFS(root, endToRoot, destValue); int i = startToRoot.length(), j = endToRoot.length(); int cnt = 0; while(i > 0 && j > 0 && startToRoot.charAt(i-1) == endToRoot.charAt(j-1)) { cnt++; i--; j--; } String sPath = "U".repeat(startToRoot.length() - cnt); String ePath = endToRoot.reverse().toString().substring(cnt, endToRoot.length()); return sPath + ePath; } }
class Solution { public: bool search(TreeNode* root, int target, string &s){ if(root==NULL) { return false; } if(root->val==target) { return true; } bool find1=search(root->left,target, s+='L'); // search on left side if(find1) return true; s.pop_back(); // backtracking step bool find2= search(root->right,target, s+='R'); // search on right side if(find2) return true; s.pop_back(); // backtracking step return false; } TreeNode* lca(TreeNode* root ,int n1 ,int n2) { if(root==NULL) return NULL; if(root->val==n1 or root->val==n2) return root; TreeNode* left=lca(root->left,n1,n2); TreeNode* right=lca(root->right,n1,n2); if(left!=NULL && right!=NULL) return root; if(left) return left; if(right) return right; return NULL; // not present in tree } string getDirections(TreeNode* root, int startValue, int destValue) { TreeNode* temp=lca(root,startValue,destValue); string s1,s2; search(temp,startValue,s1); search(temp,destValue,s2); for(auto &it:s1){ it='U'; } return s1+s2; } };
var getDirections = function(root, startValue, destValue) { const getPath = (node, value, acc='') => { if (node === null) { return ''; } else if (node.val === value) { return acc; } else { return getPath(node.left, value, acc + 'L') + getPath(node.right, value, acc + 'R') } } // generate the paths let startPath = getPath(root, startValue); let destPath = getPath(root, destValue); // find the lowest common ancestor let i = 0; for (; i < startPath.length && i < destPath.length && startPath[i] === destPath[i]; i++); // output the final path let output = ''; for (let j = i; j < startPath.length; j++) { output += 'U'; } return output + destPath.substring(i); };
Step-By-Step Directions From a Binary Tree Node to Another
On day 1, one person discovers a secret. You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 6, delay = 2, forget = 4 Output: 5 Explanation: Day 1: Suppose the first person is named A. (1 person) Day 2: A is the only person who knows the secret. (1 person) Day 3: A shares the secret with a new person, B. (2 people) Day 4: A shares the secret with a new person, C. (3 people) Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people) Day 6: B shares the secret with E, and C shares the secret with F. (5 people) Example 2: Input: n = 4, delay = 1, forget = 3 Output: 6 Explanation: Day 1: The first person is named A. (1 person) Day 2: A shares the secret with B. (2 people) Day 3: A and B share the secret with 2 new people, C and D. (4 people) Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people) &nbsp; Constraints: 2 &lt;= n &lt;= 1000 1 &lt;= delay &lt; forget &lt;= n
```class Solution: def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int: table = [0]*(forget+1) table[1] = 1 days = 1 while days<=n-1: count = 0 for k in range(forget-1,-1,-1): if k+1>delay: table[k+1] = table[k] count+=table[k] elif k+1<=delay: table[k+1] = table[k] table[1] = count days+=1 count = 0 for k in range(1,forget+1): count+=table[k] return count%(pow(10,9)+7) TC---O(forget*n) sc---O(forget)
class Solution { public int peopleAwareOfSecret(int n, int delay, int forget) { long mod = 1000000007L; long[] shares = new long[n + 1]; long[] forgets = new long[n + 1]; if (delay < n) { shares[delay + 1] = 1; } if (forget < n) { forgets[forget + 1] = 1; } long shareToday = 0; long peopleKnow = 1; for (int i = delay; i <= n; i++) { shareToday += shares[i] % mod; shareToday -= forgets[i] % mod; peopleKnow -= forgets[i] % mod; peopleKnow += shareToday % mod; if (i + delay < n + 1) { shares[i + delay] += shareToday % mod; } if (i + forget < n + 1) { forgets[i + forget] += shareToday % mod; } } return (int) (peopleKnow % mod); } }
static int MOD=1e9+7; class Solution { public: int delay,forget; vector<long> memo; // Total number of people who would have found out about the secret by the nth day. long dp(int n) { if(!n) return 0; if(memo[n]!=-1) // Return cached result if exists. return memo[n]; // Current contribution of 1 person who knows the secret long result=1; for(int i=delay;i<forget;i++) // Number of people that the secret will be forwarded to if(n-i>=0) result=(result+dp(n-i))%MOD; return memo[n]=result; } int peopleAwareOfSecret(int n, int delay, int forget) { this->delay=delay; this->forget=forget; memo.resize(n+1,-1); return (dp(n)-dp(n-forget)+MOD)%MOD; // Subtract the people who found out by the `n-forget` day as observed. } };
/** * @param {number} n * @param {number} delay * @param {number} forget * @return {number} */ var peopleAwareOfSecret = function(n, delay, forget) { const dp=new Array(n+1).fill(0); let numberOfPeopleSharingSecret = 0; let totalNumberOfPeopleWithSecret = 0; const MOD = 1000000007n; dp[1]=1; // as on day one only one person knows the secret for(let i=2;i<=n;i++){ const numberOfNewPeopleSharingSecret = dp[Math.max(i-delay,0)]; const numberOfPeopleForgettingSecret = dp[Math.max(i-forget,0)]; numberOfPeopleSharingSecret = BigInt(numberOfPeopleSharingSecret) + ( BigInt(numberOfNewPeopleSharingSecret) - BigInt(numberOfPeopleForgettingSecret) + BigInt(MOD) ) % BigInt(MOD); dp[i] = numberOfPeopleSharingSecret; } for(let i=n-forget+1;i<=n;i++){ totalNumberOfPeopleWithSecret = (BigInt(totalNumberOfPeopleWithSecret) + BigInt(dp[i])) % BigInt(MOD); } return totalNumberOfPeopleWithSecret; };
Number of People Aware of a Secret