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
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.   Example 1: Input: n = 3, k = 2, row = 0, column = 0 Output: 0.06250 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. Example 2: Input: n = 1, k = 0, row = 0, column = 0 Output: 1.00000   Constraints: 1 <= n <= 25 0 <= k <= 100 0 <= row, column <= n
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: x_dir = [2, 1, -1, -2, -2, -1, 1, 2] y_dir = [1, 2, 2, 1, -1, -2, -2, -1] cache = {} def kMoves(i, j, moves): if i >= n or j >= n or i < 0 or j < 0: return 0 if moves == k: return 1 if (i, j, moves) in cache: return cache[(i, j, moves)] totMoves = 0 for ind in range(8): totMoves += kMoves(i+x_dir[ind], j+y_dir[ind], moves+1)*(1/8) cache[(i, j, moves)] = totMoves return totMoves return kMoves(row, column, 0)
class Solution { public double knightProbability(int n, int k, int row, int column) { double [][]curr=new double[n][n]; double [][]next=new double[n][n]; curr[row][column]=1; int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}}; for(int p=1;p<=k;p++){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(curr[i][j]!=0){ for(int d=0;d<8;d++){ int ni=i+dir[d][0]; int nj=j+dir[d][1]; if(ni<0 || nj<0 || ni>=n || nj>=n){ continue; } next[ni][nj]+=curr[i][j]/8.0; } } } } curr=next; next=new double[n][n]; } double sum=0.0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ sum+=curr[i][j]; } } return sum; } }
class Solution { public: // declare a dp double dp[30][30][105]; // x and y co-ordinates of 8 directions vector<int> dx = {-2, -2, -1, 1, 2, 2, 1, -1}; vector<int> dy = {-1, 1, 2, 2, 1, -1, -2, -2}; double dfs(int i, int j, int n, int moves) { // base case if we have reached out of grid if(i < 0 || i >= n || j < 0 || j >= n) return 0; // if no moves are remaining if(moves <= 0) return 1; // if already calculated if(dp[i][j][moves] != 0) return dp[i][j][moves]; // find total possible ways of staying on chess board double ans = 0; for(int k = 0; k < 8; k++) { int new_row = i + dx[k]; int new_col = j + dy[k]; ans += dfs(new_row, new_col, n, moves - 1); } // for each cell there are 8 possible moves, so probablity will be no. of successfull moves / 8 // store the result and return return dp[i][j][moves] = ans / 8.0; } double knightProbability(int n, int k, int row, int column) { // initialize the dp with 0 memset(dp, 0, sizeof(dp)); return dfs(row, column, n, k); } };
var knightProbability = function(n, k, row, column) { if (k === 0) return 1; const dirs = [[-2, -1], [-1, -2], [1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1]]; const dp = Array(k + 1) .fill('') .map(_ => Array(n).fill('').map(_ => Array(n).fill(0))); const isOut = (pos) => pos < 0 || pos > n - 1; const move = (x = row, y = column, step = k) => { if (step === 0) return 1; const moves = dp[step][x][y]; if (moves !== 0) return moves; for (const [mvoeX, moveY] of dirs) { const nextX = x + mvoeX; const nextY = y + moveY; if (isOut(nextX) || isOut(nextY)) continue; dp[step][x][y] += move(nextX, nextY, step - 1); } return dp[step][x][y]; }; move(); return dp[k][row][column] / 8 ** k; };
Knight Probability in Chessboard
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces. &nbsp; Example 1: Input: text = " this is a sentence " Output: "this is a sentence" Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces. Example 2: Input: text = " practice makes perfect" Output: "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string. &nbsp; Constraints: 1 &lt;= text.length &lt;= 100 text consists of lowercase English letters and ' '. text contains at least one word.
class Solution(object): def reorderSpaces(self, text): word_list = text.split() words, spaces = len(word_list), text.count(" ") if words > 1: q, r = spaces//(words-1), spaces%(words-1) return (" " * q).join(word_list) + " " * r else: return "".join(word_list) + " " * spaces
class Solution { public String reorderSpaces(String text) { int spaces = 0; //count the spacex for(char c: text.toCharArray()){ if(c==' ') spaces++; } //form word array String[] words = text.trim().split("\\s+"); int nWords = words.length; StringBuilder sb = new StringBuilder(); int spacesToApply=0,extraSpaces=0; //if there is only 1 word, then all spaces will be at the end if(nWords == 1){ extraSpaces=spaces; } //if there are multiple words, find the spaces to apply between words and also any extra space else{ spacesToApply = spaces / (nWords-1); extraSpaces = spaces % (nWords-1); } //append every word and then apply spaces for(int i=0;i<words.length-1;i++){ sb.append(words[i]); for(int j=0;j<spacesToApply;j++) sb.append(" "); } //now append last word separately, bcz we dont want to apply spaces after last word sb.append(words[nWords-1]); //if there are any extra spaces that cannot be distributed among words, add them here for(int j=0;j<extraSpaces;j++) sb.append(" "); return sb.toString(); } }
class Solution { public: string reorderSpaces(string text) { int ct=0; // Collection of words vector<string> v; for (int i=0; i<text.size(); i++){ // Calculate the numbert of spaces while(i<text.size() && text[i] == ' '){ ct++; i++; } // Extract the words and collect them string tp=""; while(i<text.size() && text[i] != ' '){ tp+=text[i]; i++; } i--; // Adding word to the collection if(tp.size()) v.push_back(tp); } text = ""; // Combining the words with equal number of white spaces for(int i=0; i<v.size()-1; i++){ text += v[i]; int j=ct/(v.size()-1); while(j--) text += ' '; } text += v[v.size()-1]; // Adding remaining extra spaces at the end int j=(v.size() > 1)?ct % (v.size()-1):ct; while(j--) text += ' '; return text; } };
var reorderSpaces = function(text) { let arr = text.split(" "); let totalSpace = arr.length-1; arr = arr.filter(w => w !== ''); let spaceBetween = arr.length > 1 ? Math.floor(totalSpace / (arr.length-1)) : 0; let spaceLeftOver = arr.length > 1 ? totalSpace % (arr.length-1) : totalSpace; return (arr.join(" ".repeat(spaceBetween)) + " ".repeat(spaceLeftOver)); // Time Complexity: O(n) // Space Complexity: O(n) };
Rearrange Spaces Between Words
Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). &nbsp; Example 1: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: true Example 2: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] Output: false Example 3: Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1] Output: true &nbsp; Constraints: p1.length == p2.length == p3.length == p4.length == 2 -104 &lt;= xi, yi &lt;= 104
class Solution: def validSquare(self, p1, p2, p3, p4): def cal(A, B): return abs(A[0] - B[0]) + abs(A[1] - B[1]) d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)] d.sort() return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5]
class Solution { // This method returns true if the given 4 points form a square, false otherwise public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { // We use a set to store the distances between the points Set<Integer> set = new HashSet(); // Calculate the distances between all pairs of points and add them to the set set.add(distanceSquare(p1,p2)); set.add(distanceSquare(p1,p3)); set.add(distanceSquare(p1,p4)); set.add(distanceSquare(p2,p3)); set.add(distanceSquare(p2,p4)); set.add(distanceSquare(p3,p4)); // A square must have 4 equal sides, so the set must contain 2 different values (the lengths of the sides and the diagonals) // The set should not contain 0, as that would mean that two points have the same coordinates return !set.contains(0) && set.size() == 2; } // This method calculates the distance between two points and returns its square private int distanceSquare(int[] a, int[] b){ // We use the Pythagorean theorem to calculate the distance between the points return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]); } }
class Solution { public: bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) { vector<vector<int>> p{p1, p2, p3, p4}; unsigned short ans{0}; double scal; vector<double> bar(2); /* compute the barycenter */ bar[0] = (p1[0] + p2[0] + p3[0] + p4[0]) / 4.; bar[1] = (p1[1] + p2[1] + p3[1] + p4[1]) / 4.; const double length = pow(p1[0]-bar[0],2) + pow(p1[1] - bar[1],2); for (size_t i=0; i<4; i++) {if ((pow(p[i][0]-bar[0], 2) + pow(p[i][1] - bar[1], 2)) != length) return false; for (size_t j=i+1; j<4;j++){ scal = (bar[0] - p[i][0])*(bar[0] - p[j][0]) + (bar[1] - p[i][1])*(bar[1]- p[j][1]); ans += (scal==0.)?1:0;}} return ans==4; } };
var validSquare = function(p1, p2, p3, p4) { const distance = (a, b) => { const [aX, aY] = a; const [bX, bY] = b; return (aX - bX) ** 2 + (aY - bY) ** 2; }; const set = new Set([ distance(p1, p2), distance(p1, p3), distance(p1, p4), distance(p2, p3), distance(p2, p4), distance(p3, p4), ]); return !set.has(0) && set.size === 2; };
Valid Square
You are given a 0-indexed integer array nums. The array nums is beautiful if: nums.length is even. nums[i] != nums[i + 1] for all i % 2 == 0. Note that an empty array is considered beautiful. You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged. Return the minimum number of elements to delete from nums to make it beautiful. &nbsp; Example 1: Input: nums = [1,1,2,3,5] Output: 1 Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful. Example 2: Input: nums = [1,1,2,2,3,3] Output: 2 Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 105
class Solution: def minDeletion(self, nums: List[int]) -> int: # Greedy ! # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0 # at the begining, we consider the num on the even index # when we delete a num, we need consider the num on the odd index # then repeat this process # at the end we check the requirement 1: nums.length is even or not n = len(nums) count = 0 # flag is true then check the even index # flag is false then check the odd index flag = True for i in range(n): # check the even index if flag: if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]: count += 1 flag = False # check the odd index elif not flag: if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]: count += 1 flag = True curLength = n - count return count if curLength % 2 == 0 else count + 1
class Solution { public int minDeletion(int[] nums) { int deletion = 0, n = nums.length; for (int i=0; i<n-1; ) { int newIndex = i-deletion; if ((newIndex % 2 == 0) && nums[i] == nums[i+1]) deletion++; else i++; } return ((n-deletion) % 2 == 0) ? deletion : deletion+1; } }
INTUITION 1. since we have to find the minimum deletions, we dont have to actually delete the elements , we just have to count those elements. 2. Now if we delete the element and shift all the elements towards left , it will cause time limit exceeded. 3. To handle above case we can observe one thing that, if we delete some element at a certain position then the indices of all the elements towards the right will get inverted means the odd index will become even and the even will become odd. 4. In the end checking if the vector size if even or odd, if it is even simply return or else if it is odd then decrement result by 1 since we have to remove one element to have the vector size even. class Solution { public: int minDeletion(vector<int>& nums) { int res=0,n=nums.size(),i; int flag=1; for(i=0;i<nums.size()-1;i++){ if(i%2==0 and nums[i]==nums[i+1] and flag){ res++; flag=0; } else if(i%2==1 and nums[i]==nums[i+1] and flag==0){ res++; flag=1; } } int x=n-res; if(x%2==0){ return res; } return res+1; } };
var minDeletion = function(nums) { const n = nums.length; const res = []; for (let i = 0; i < n; ++i) { const num = nums[i]; if (res.length % 2 === 0 || res.at(-1) != num) { res.push(num); } } if (res.length % 2 === 1) res.pop(); return n - res.length; };
Minimum Deletions to Make Array Beautiful
Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. &nbsp; Example 1: Input: nums = [23,2,4,6,7], k = 6 Output: true Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. Example 2: Input: nums = [23,2,6,4,7], k = 6 Output: true Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. Example 3: Input: nums = [23,2,6,4,7], k = 13 Output: false &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 109 0 &lt;= sum(nums[i]) &lt;= 231 - 1 1 &lt;= k &lt;= 231 - 1
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: psum = {0:-1} currentSum = 0 for i in range(len(nums)): currentSum += nums[i] remainder = currentSum % k if remainder not in psum: psum[remainder] = i else: if i - psum[remainder] > 1: return True return False
class Solution { public boolean checkSubarraySum(int[] nums, int k) { boolean t[]=new boolean[nums.length+1]; Arrays.fill(t,false); return help(nums.length,nums,k,0,0,t); } public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){ if(size>=2&&sum%k==0){ return true; } if(i==0){ return false; } if(t[i-1]!=false){ return t[i-1]; } if(size>0){ return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t); } return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t)||help(i-1,nums,k,sum,size,t); } } --------------------------------------------------------------------------------------------- class Solution { public boolean checkSubarraySum(int[] nums, int k) { int sum=0; HashMap<Integer,Integer>h=new HashMap<>(); h.put(0,-1); for(int i=0;i<nums.length;i++){ sum+=nums[i]; sum=k==0?sum:sum%k; if(h.containsKey(sum)&& i-h.get(sum)>=2){ return true; } h.put(sum,h.getOrDefault(sum,i)); } return false; } }
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { unordered_set<int> s; int sum = 0; int pre = 0; for(int i = 0; i < nums.size(); i++) { sum += nums[i]; int remainder = sum%k; if (s.find(remainder) != s.end()) { return true; } s.insert(pre); pre = remainder; } return false; }
var checkSubarraySum = function(nums, k) { const hash = new Map([[0, -1]]); let sum = 0; for (let index = 0; index < nums.length; index++) { sum += nums[index]; const r = sum % k; if (hash.has(r)) { if (index - hash.get(r) > 1) return true; } else hash.set(r, index); } return false; };
Continuous Subarray Sum
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. &nbsp; Example 1: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. &nbsp; Constraints: 1 &lt;= tickets.length &lt;= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi
class Solution: def findTicketsAdjList(self, tickets): ticket = {} for src,dest in tickets: if src in ticket: ticket[src].append(dest) else: ticket[src] = [dest] for src,dest in ticket.items(): if len(dest)>1: ticket[src] = sorted(ticket[src], reverse=True) return ticket def reconstructItinerary(self, source, tickets, itinerary): if source in tickets: while tickets[source]: destination = tickets[source].pop() self.reconstructItinerary(destination, tickets, itinerary) itinerary.append(source) return itinerary def findItinerary(self, tickets: List[List[str]]) -> List[str]: if len(tickets)==1: if "JFK" not in tickets[0]: return [] ticketsAdj = self.findTicketsAdjList(tickets) if "JFK" not in ticketsAdj: return [] itinerary = [] itinerary = self.reconstructItinerary("JFK", ticketsAdj, itinerary) return itinerary[::-1]
class Solution { LinkedList<String> res = new LinkedList<>(); public List<String> findItinerary(List<List<String>> tickets) { HashMap<String,PriorityQueue<String>> map= new HashMap<>(); for(int i=0;i<tickets.size();i++){ String a=tickets.get(i).get(0); String b=tickets.get(i).get(1); if(!map.containsKey(a)){ PriorityQueue<String> temp = new PriorityQueue(); map.put(a,temp); } map.get(a).add(b); } dfs("JFK",map); return res; } private void dfs(String departure,HashMap<String,PriorityQueue<String>> map){ PriorityQueue<String> arrivals= map.get(departure); while(arrivals!=null &&!arrivals.isEmpty()){ dfs(arrivals.poll(),map); } res.addFirst(departure); } }
class Solution { public: vector<string> findItinerary(vector<vector<string>>& tickets) { unordered_map<string, multiset<string>> myMap; stack<string> myStack; vector<string> ans; for (int i=0; i<tickets.size(); ++i) { myMap[tickets[i][0]].insert(tickets[i][1]); } myStack.push({"JFK"}); while (!myStack.empty()) { string top = myStack.top(); if (!myMap[top].empty()) { myStack.push(*myMap[top].begin()); myMap[top].erase(myMap[top].begin()); } else { ans.insert(ans.begin(), top); myStack.pop(); } } return ans; } }; // Time : O(E) // Space : O(V + E)
function dfs(edges,s=`JFK`,ans=[`JFK`]){ //run dfs, starting node being `JFK` if(!edges[s] || edges[s].length==0){ //if currenctly reached node has its adjacent list empty let isAllTravelled=1; Object.values(edges).forEach(ele=> {if(ele.length>0) isAllTravelled=0}) // check if every edge has been travelled i.e all adjacentLists should be empty if(!isAllTravelled) return false; //returns false when there are more edges to travel , but from current node we cannot move anywhere else else return ans; // return true if from current node we cannot move anywhere else and all the edges have been travelled as well } let myAL= edges[s].sort(); // sort the Adjacency List of current node lexicographically for(let i=0;i<myAL.length;i++){ // start by taking the lexicographically smallest node and run dfs ans.push(myAL[i]); // add current node into answer array edges[s]= [...edges[s].slice(0,edges[s].indexOf(myAL[i])),...edges[s].slice(edges[s].indexOf(myAL[i])+1)]; // remove the currently edges travelled from adjacency List let xx= dfs(edges,myAL[i],ans); //here runs the dfs if(!xx){ // if dfs result of current node could not travel all edges from current node ans.pop(); // pop out current accounted node from answer edges[s].push(myAL[i]); //put back the edge into adjacency list assmuing we should not visit this edge at this point as it doesnt leads to answer from here currenlt } else return xx ; // if dfs result of current node could travel all edges from current node return the answer array } } var findItinerary = function(tickets) { let edges={}; //our adjacency list tickets.forEach(ticket=>{ if(!edges[ticket[0]]){ edges[ticket[0]]=[]; } edges[ticket[0]].push(ticket[1]); }) let ans= dfs(edges); // run dfs return ans; };
Reconstruct Itinerary
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class: SummaryRanges() Initializes the object with an empty stream. void addNum(int val) Adds the integer val to the stream. int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. &nbsp; Example 1: Input ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []] Output [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] Explanation SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // return [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] &nbsp; Constraints: 0 &lt;= val &lt;= 104 At most 3 * 104 calls will be made to addNum and getIntervals. &nbsp; Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
class SummaryRanges: def __init__(self): self.intervals = [] def addNum(self, val: int) -> None: left, right = 0, len(self.intervals) - 1 while left <= right: mid = (left + right) // 2 e = self.intervals[mid] if e[0] <= val <= e[1]: return elif val < e[0]:right = mid - 1 else:left = mid + 1 pos = left self.intervals.insert(pos, [val, val]) if pos + 1 < len(self.intervals) and val + 1 == self.intervals[pos+1][0]: self.intervals[pos][1] = self.intervals[pos+1][1] del self.intervals[pos+1] if pos - 1 >= 0 and val - 1 == self.intervals[pos-1][1]: self.intervals[pos-1][1] = self.intervals[pos][1] del self.intervals[pos] def getIntervals(self) -> List[List[int]]: return self.intervals
class SummaryRanges { Map<Integer, int[]> st; Map<Integer, int[]> end; Set<Integer> pending; int[][] prev = new int[0][]; Set<Integer> seen = new HashSet<>(); int INVALID = -1; public SummaryRanges() { st = new HashMap<>(); end= new HashMap<>(); pending = new HashSet<>(); } public void addNum(int val) { // [TC: O(1)] if (!seen.contains(val)){ // only add if not seen. pending.add(val); // pending processing list } } public int[][] getIntervals() { // [TC: O(pending list length (= k)) best case (all merges), O(n)+O(klogk) worst case (all inserts)] Set<int[]> addSet = new HashSet<>(); for (int n : pending){ if (st.containsKey(n+1)&&end.containsKey(n-1)){ // merge intervals on both ends, a new interval form -> add to addSet int[] s = st.get(n+1); int[] e = end.get(n-1); int[] m = new int[]{e[0], s[1]}; st.remove(n+1); end.remove(n-1); st.put(m[0], m); end.put(m[1], m); s[0]=e[0]=INVALID; addSet.remove(s); // may be in addSet, remove them addSet.remove(e); addSet.add(m); }else if (st.containsKey(n+1)){ // merge with the next interval, no other action required. st.get(n+1)[0]--; st.put(n, st.get(n+1)); st.remove(n+1); }else if (end.containsKey(n-1)){ // merge with the previous interval, no other action required. end.get(n-1)[1]++; end.put(n, end.get(n-1)); end.remove(n-1); }else{ // new interval -> add to AddSet int[] m = new int[]{n, n}; addSet.add(m); st.put(n, m); end.put(n, m); } } seen.addAll(pending); pending.clear(); // remember to clear the pending list. if (!addSet.isEmpty()){ // IF there is no new intervals to insert, we SKIP this. List<int[]> addList = new ArrayList<>(addSet); addList.sort(Comparator.comparingInt(o -> o[0])); int i = 0, j = 0; // two pointers because both prev & addList are sorted. List<int[]> ans = new ArrayList<>(); while(i < prev.length || j < addList.size()){ if (i < prev.length && prev[i][0]==INVALID){ i++; }else if (j == addList.size() || i < prev.length && prev[i][0]<addList.get(j)[0]){ ans.add(prev[i++]); }else if (i == prev.length || prev[i][0]>addList.get(j)[0]){ ans.add(addList.get(j++)); } } prev = ans.toArray(new int[0][]); } return prev; } }
class SummaryRanges { public: struct DSU { map<int, int>parent; map<int, int>sz; int find_parent(int a) { if(!parent.count(a)) { parent[a] = a; sz[a] = 1; } if(parent[a] == a) return a; return parent[a] = find_parent(parent[a]); } void union_sets(int a, int b) { if(!parent.count(a)) { parent[a] = a; sz[a] = 1; } if(!parent.count(b)) { parent[b] = b; sz[b] = 1; } a = find_parent(a); b = find_parent(b); if(a == b) return; parent[b] = a; sz[a] += sz[b]; } void add(int a) { if(!parent.count(a)) { parent[a] = a; sz[a] = 1; } else return; if(parent.count(a + 1)) { union_sets(a, a + 1); } if(parent.count(a - 1)) { union_sets(a - 1, a); } } vector<vector<int>>getIntervals() { vector<vector<int>>intervals; for(auto [a, b]: parent) { if(a == b) { intervals.push_back({a, a + sz[a] - 1}); } } return intervals; } }; DSU dsu; SummaryRanges() { this->dsu = DSU(); } void addNum(int val) { dsu.add(val); } vector<vector<int>> getIntervals() { return dsu.getIntervals(); } };
var SummaryRanges = function() { this.tree = null // { val, left?, right? } }; /** * @param {number} val * @return {void} */ SummaryRanges.prototype.addNum = function(val) { if (!this.tree) { this.tree = { val } } else { let node = this.tree let parent, side while (node) { if (node.val === val) { return } parent = node side = node.val > val ? 'left' : 'right' node = node[side] } parent[side] = { val } } }; /** * @return {number[][]} */ SummaryRanges.prototype.getIntervals = function() { // travel from left to right // generate intervals // > (x === last[1] + 1) ? update last[1] : create a new one const travel = (node, check) => { if (!node) { return } travel(node.left, check) check(node.val) travel(node.right, check) } const result = [] const check = val => { if (!result.length || val > result[result.length - 1][1] + 1) { result.push([val, val]) } else { result[result.length - 1][1] = val } } travel(this.tree, check) return result }; /** * Your SummaryRanges object will be instantiated and called as such: * var obj = new SummaryRanges() * obj.addNum(val) * var param_2 = obj.getIntervals() */
Data Stream as Disjoint Intervals
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: The next instruction will move the robot off the grid. There are no more instructions left to execute. Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s. &nbsp; Example 1: Input: n = 3, startPos = [0,1], s = "RRDDLU" Output: [1,5,4,3,1,0] Explanation: Starting from startPos and beginning execution from the ith instruction: - 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid. - 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1). - 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0). - 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0). - 4th: "LU". Only one instruction "L" can be executed before it moves off the grid. - 5th: "U". If moving up, it would move off the grid. Example 2: Input: n = 2, startPos = [1,1], s = "LURD" Output: [4,1,0,0] Explanation: - 0th: "LURD". - 1st: "URD". - 2nd: "RD". - 3rd: "D". Example 3: Input: n = 1, startPos = [0,0], s = "LRUD" Output: [0,0,0,0] Explanation: No matter which instruction the robot begins execution from, it would move off the grid. &nbsp; Constraints: m == s.length 1 &lt;= n, m &lt;= 500 startPos.length == 2 0 &lt;= startrow, startcol &lt; n s consists of 'L', 'R', 'U', and 'D'.
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: result = [] for idx in range(len(s)): count, row, col = 0, startPos[0],startPos[1] while idx < len(s): if s[idx] == 'D': row += 1 if row >= n: break count += 1 elif s[idx] == 'U': row -= 1 if row < 0: break count += 1 elif s[idx] == 'R': col += 1 if col >= n: break count += 1 else: col -= 1 if col < 0: break count += 1 idx += 1 result.append(count) return result
class Solution { public int[] executeInstructions(int n, int[] startPos, String s) { //Make array of length equal to string length int ans[]=new int[s.length()]; //Now use two for loops for(int i=0;i<s.length();i++){ //countmoves will keep on counting the valid moves from i to s.length int countMoves=0; int yIndex=startPos[0]; int xIndex=startPos[1]; for(int j=i;j<s.length();j++){ if(s.charAt(j)=='R'){ xIndex++; } if(s.charAt(j)=='L'){ xIndex--; } if(s.charAt(j)=='U'){ yIndex--; } if(s.charAt(j)=='D'){ yIndex++; } if(xIndex<0 || xIndex>=n || yIndex<0 || yIndex>=n){ break; } else{ countMoves++; } } ans[i]=countMoves; } return ans; } }
class Solution { public: vector<int> executeInstructions(int n, vector<int>& start, string s) { int m=s.size(); vector<int> ans(m); for(int l=0;l<m;l++){ int count=0; int i=start[0],j=start[1]; for(int k=l;k<m;k++){ if(s[k]=='L'){ if(j-1>=0){ j--; count++; } else break; } else if(s[k]=='R'){ if(j+1<n){ j++; count++; } else break; } else if(s[k]=='U'){ if(i-1>=0){ i--; count++; } else break; } else{ if(i+1<n){ i++; count++; } else break; } } ans[l]=count; } return ans; } };
// Time: O(n^2) var executeInstructions = function(n, startPos, s) { let answers = []; for (i = 0; i < s.length; i++) { let movement = 0; let [row, col] = startPos; for (j = i; j < s.length; j++) { if (s[j] == "R") col++; else if (s[j] == "L") col--; else if (s[j] == "D") row++; else row--; if(row>n-1 || col > n-1 || row < 0 || col < 0) { break; } movement++; } answers[i] = movement; } return answers; };
Execution of All Suffix Instructions Staying in a Grid
Given a weighted undirected connected graph with n&nbsp;vertices numbered from 0 to n - 1,&nbsp;and an array edges&nbsp;where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes&nbsp;ai&nbsp;and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles&nbsp;and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a&nbsp;critical edge. On&nbsp;the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. &nbsp; Example 1: Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] Output: [[0,1],[2,3,4,5]] Explanation: The figure above describes the graph. The following figure shows all the possible MSTs: Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. Example 2: Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] Output: [[],[0,1,2,3]] Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical. &nbsp; Constraints: 2 &lt;= n &lt;= 100 1 &lt;= edges.length &lt;= min(200, n * (n - 1) / 2) edges[i].length == 3 0 &lt;= ai &lt; bi &lt; n 1 &lt;= weighti&nbsp;&lt;= 1000 All pairs (ai, bi) are distinct.
class Solution: def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]: def find(v, parent): if parent[v] != v: parent[v] = find(parent[v], parent) return parent[v] def union(u,v, parent): parent[find(u,parent)] = find(v,parent) edges = [(u,v,w,i) for i, (u,v,w) in enumerate(edges)] edges.sort(key = lambda e:e[2]) def find_mst_without_this_edge(idx): parent = list(range(n)) res = 0 for i, (u, v, w, _) in enumerate(edges): if i == idx: continue if find(u, parent) != find(v, parent): res += w union(u, v, parent) root = find(0, parent) return res if all(find(i, parent) == root for i in range(n)) else float('inf') def find_mst_with_this_edge(idx): parent = list(range(n)) u0, v0, w0, _ = edges[idx] res = w0 union(u0,v0,parent) for i, (u, v, w, _) in enumerate(edges): if i == idx: continue if find(u, parent) != find(v, parent): res += w union(u, v, parent) root = find(0, parent) return res if all(find(i, parent) == root for i in range(n)) else float('inf') base_mst_wgt = find_mst_without_this_edge(-1) cri, pcri = set(), set() for i in range(len(edges)): wgt_excl = find_mst_without_this_edge(i) if wgt_excl > base_mst_wgt: cri.add(edges[i][3]) else: wgt_incl = find_mst_with_this_edge(i) if wgt_incl == base_mst_wgt: pcri.add(edges[i][3]) return [cri, pcri]
class Solution { static class UnionFind{ int[]parent; int[]rank; int comp = 0; UnionFind(int n){ parent = new int[n]; rank = new int[n]; comp = n; for(int i=0;i<n;i++){ parent[i] = i; rank[i] = 0; } } int find(int x){ if(parent[x] == x){ return x; }else{ parent[x] = find(parent[x]); return parent[x]; } } boolean union(int X,int Y){ int x = find(X); int y = find(Y); if(x == y){ return false; } if(rank[x] < rank[y]){ parent[x] = y; }else if(rank[y] < rank[x]){ parent[y] = x; }else{ parent[y] = x; rank[x]++; } comp--; return true; } boolean isConnected(){ return comp == 1; } } static class Edge implements Comparable<Edge>{ int u; int v; int wt; Edge(int u,int v,int wt){ this.u = u; this.v = v; this.wt = wt; } public int compareTo(Edge o){ return this.wt - o.wt; } } public int buildMST(int n,int[][]edges,int[]edgeSkip,int[]edgePick){ PriorityQueue<Edge> pq = new PriorityQueue<>(); for(int[]edge : edges){ if(edge == edgeSkip){ continue; }else if(edge == edgePick){ continue; } int u = edge[0]; int v = edge[1]; int wt = edge[2]; pq.add(new Edge(u,v,wt)); } UnionFind uf = new UnionFind(n); int cost = 0; if(edgePick != null){ uf.union(edgePick[0],edgePick[1]); cost += edgePick[2]; } while(pq.size() > 0){ Edge rem = pq.remove(); if(uf.union(rem.u,rem.v) == true){ cost += rem.wt; } } if(uf.isConnected() == true){ return cost; }else{ return Integer.MAX_VALUE; } } public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { int mstCost = buildMST(n,edges,null,null); ArrayList<Integer> critical = new ArrayList<>(); ArrayList<Integer> pcritical = new ArrayList<>(); for(int i=0;i<edges.length;i++){ int []edge = edges[i]; int mstCostWithoutEdge = buildMST(n,edges,edge,null); if(mstCostWithoutEdge > mstCost){ critical.add(i); //Critical edge index }else{ int mstCostWithEdge = buildMST(n,edges,null,edge); if(mstCostWithEdge > mstCost){ //redundant }else{ pcritical.add(i); //pseduo critical edge index } } } List<List<Integer>> res = new ArrayList<>(); res.add(critical); res.add(pcritical); return res; } }
class UnionFind{ private: vector<int> parent_; vector<int> rank_; int sets_; public: UnionFind(int n) { init(n); } void init(int n) { sets_ = n; parent_.resize(n); rank_.resize(n); iota(parent_.begin(),parent_.end(),0); fill(rank_.begin(),rank_.end(),1); } int find(int u) { return parent_[u] == u ? u: parent_[u] = find(parent_[u]); } bool join(int u,int v) { u = find(u); v = find(v); if(u==v) { return false; } if(rank_[u]<rank_[v]) { swap(u,v); } rank_[u] += rank_[v]; parent_[v] = u; sets_ --; return true; } bool united() { return sets_ == 1; } }; class Solution { public: vector<int> edges_idx_; int kruskal(const int n, const int removed_edge_idx,const int init_edge_idx, const vector<vector<int>> &edges) { UnionFind graph(n); int edges_size = edges.size(); int total = 0; if(init_edge_idx != -1) { graph.join(edges[init_edge_idx][0],edges[init_edge_idx][1]); total += edges[init_edge_idx][2]; } for(int i = 0; i<edges_size; ++i) { int edge_idx = edges_idx_[i]; if(edge_idx == removed_edge_idx) { continue; } int u = edges[edge_idx][0]; int v = edges[edge_idx][1]; if(graph.join(u,v)) { total+= edges[edge_idx][2]; } } return graph.united() ? total : INT_MAX; } vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& edges) { int edges_size = edges.size(); edges_idx_.resize(edges_size); iota(edges_idx_.begin(),edges_idx_.end(),0); sort(edges_idx_.begin(),edges_idx_.end(),[&edges](int a, int b){ return edges[a][2] < edges[b][2]; }); int mst = kruskal(n,-1,-1,edges); vector<int> critical; vector<int> psudo; for(int i = 0; i< edges_size; ++i) { int edge_idx = edges_idx_[i]; int total = kruskal(n,-1,edge_idx,edges); if(total == mst) { total = kruskal(n,edge_idx,-1,edges); if(total > mst) { critical.push_back(edge_idx); } else{ psudo.push_back(edge_idx); } } } return {critical,psudo}; } };
/** * @param {number} n * @param {number[][]} edges * @return {number[][]} */ var findCriticalAndPseudoCriticalEdges = function(n, edges) { // find and union utils const find = (x, parent) => { if (parent[x] === -1) { return x } const y = find(parent[x], parent) parent[x] = y return y } const union = (a, b, parent) => { a = find(a, parent) b = find(b, parent) if (a === b) { return false } parent[a] = b return true } // sort and group edges by cost const map = {} edges.forEach(([a, b, cost], i) => { map[cost] = map[cost] || [] map[cost].push([a, b, i]) }) const costs = Object.keys(map).sort((a, b) => a - b) // check by group const check = (edges, parent) => { let nextParent let count // travel with a skipped point // if skip === -1, skip nothing and update count and nextParent. const travel = skip => { const p = [...parent] const result = [] edges.forEach(([a, b, i]) => { if (i === skip) { return } if (union(a, b, p)) { result.push(i) } }) if (skip === -1) { count = result.length nextParent = p } return result } // get default count and nextParent. travel(-1) // special case: there is only one edge in this group if (edges.length === 1) { if (count === 0) { return [[], [], 0, parent] } return [[edges[0][2]], [], 1, nextParent] } // aList -> critical, bList -> pseudo const aList = {} const bList = {} edges.forEach(([a, b, i]) => { if (find(a, parent) === find(b, parent)) { return } const result = travel(i) result.length < count ? aList[i] = true : bList[i] = true }) return [Object.keys(aList), Object.keys(bList), count, nextParent] } // init traversal state const critical = [] const pseudo = [] let count = 0 let parent = new Array(n).fill(-1) // travel by cost group until all points visited for (let i = 0; i < costs.length; i++) { const [aList, bList, newCount, nextParent] = check(map[costs[i]], parent) critical.push(...aList) pseudo.push(...bList) count += newCount parent = nextParent if (count === n - 1) { break } } return [critical, pseudo] };
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 &lt;= a, b, c, d&nbsp;&lt; n a, b, c, and d are distinct. nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order. &nbsp; Example 1: Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] Example 2: Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 200 -109 &lt;= nums[i] &lt;= 109 -109 &lt;= target &lt;= 109
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: if len(nums) < 4: return [] nums.sort() res = [] for i in range(len(nums)): for j in range(i + 1, len(nums)): l = j+1 r = len(nums)-1 while l < r: sum_ = nums[i]+nums[j]+nums[l]+nums[r] a = [nums[i], nums[j], nums[l], nums[r]] if sum_ == target and a not in res: res.append(a) if sum_ > target: r -= 1 else: l += 1 while l < r and nums[l-1] == nums[l]: l += 1 return res # An Upvote will be encouraging
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> llans = new LinkedList<>(); if(nums == null || nums.length <= 2){ return llans; } for(int i=0;i<nums.length-3;i++){ for(int j=i+1;j<nums.length-2;j++){ int l = j+1; int r = nums.length-1; long ressum = target - nums[i]; ressum = ressum - nums[j]; while(l<r){ if(nums[l]+nums[r] == ressum){ List<Integer> ll = new LinkedList<>(); ll.add(nums[i]); ll.add(nums[j]); ll.add(nums[l]); ll.add(nums[r]); llans.add(ll); while( l<r && nums[l]==nums[l+1]){l++;} while( l<r && nums[r]==nums[r-1]){r--;} l++; r--; } else if(nums[l]+nums[r] < ressum){ l++; } else{ r--; } } while( j<nums.length-1 && nums[j]==nums[j+1]){ j++;} } while( i<nums.length-1 && nums[i]==nums[i+1]){ i++;} } return llans; } }
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int n = nums.size(); vector<vector<int> > answer; if(n<4) return answer; sort(nums.begin(),nums.end()); for(int i=0;i<n;){ for(int j=i+1;j<n;){ int left = j+1; int right = n-1; long long int x = (long long int)target - (long long int)nums[i] - (long long int)nums[j]; while(left<right){ if(x == nums[left]+nums[right]){ vector<int> vect{nums[i] , nums[j] , nums[left] , nums[right]}; answer.push_back(vect); //skipping duplicates while moving right int k = 1; while((left+k)<n && nums[left+k]==nums[left]) ++k; if((left+k)>=n) break; else left = left+k; //skipping duplicates while moving left k = 1; while((right-k)>=0 && nums[right-k]==nums[right]) ++k; if((right-k)<0) break; else right = right-k; } else{ if(x>nums[left]+nums[right]){ //skipping duplicates while moving right int k = 1; while((left+k)<n && nums[left+k]==nums[left]) ++k; if((left+k)>=n) break; else left = left+k; } else{ //skipping duplicates while moving left int k = 1; while((right-k)>=0 && nums[right-k]==nums[right]) ++k; if((right-k)<0) break; else right = right-k; } } } //skipping duplicates while moving right int k = 1; while((j+k)<n && nums[j+k]==nums[j]) ++k; if((j+k)>=n) break; else j = j+k; } //skipping duplicates while moving right int k = 1; while((i+k)<n && nums[i+k]==nums[i]) ++k; if((i+k)>=n) break; else i = i+k; } return answer; } };
var fourSum = function(nums, target) { nums.sort((a, b) => a - b); const res = []; for(let i=0; i<nums.length-3; i++) { for(let j=i+1; j<nums.length-2; j++) { let min = j + 1; let max = nums.length - 1; while(min < max) { const sum = nums[i] + nums[j] + nums[min] + nums[max]; if(sum === target) { res.push([nums[min], nums[max], nums[i], nums[j]]); while(nums[min] === nums[min+1]) min++; while(nums[max] === nums[max-1]) max--; min++; max--; } else if(sum > target) max--; else min++ } while(nums[j] === nums[j+1]) j++; } while(nums[i] === nums[i+1]) i++; } return res; };
4Sum
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0. &nbsp; Example 1: Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]] Output: 4 Example 2: Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] Output: 2 &nbsp; Constraints: 1 &lt;= points.length &lt;= 500 points[i].length == 2 0 &lt;= xi, yi &lt;= 4 * 104 All the given points are unique.
class Solution: def minAreaRect(self, points: List[List[int]]) -> int: points = sorted(points, key=lambda item: (item[0], item[1])) cols = defaultdict(list) for x,y in points: cols[x].append(y) lastx = {} ans = float('inf') for x in cols: col = cols[x] for i, y1 in enumerate(col): for j in range(i): y2 = col[j] if (y2,y1) in lastx: ans = min(ans, abs((x-lastx[y2,y1])*(y2-y1))) lastx[y2,y1] = x return 0 if ans==float('inf') else ans
class Solution { public int minAreaRect(int[][] points) { Map<Integer, Set<Integer>> map = new HashMap<>(); // Group the points by x coordinates for (int[] point : points) { if (!map.containsKey(point[0])) map.put(point[0], new HashSet<>()); map.get(point[0]).add(point[1]); } int min = Integer.MAX_VALUE; for (int i = 0; i < points.length - 1; i++) { int x1 = points[i][0]; int y1 = points[i][1]; for (int j = i + 1; j < points.length; j++) { int x2 = points[j][0]; int y2 = points[j][1]; if (x1 == x2 || y1 == y2) // We are looking for diagonal point, so if j is neighbour point, then continue continue; // Note - We are calculating area first (before checking whether these points form the correct rectangle), because // cost of checking rectangle is very higher than calculating area. So if area less than the prev area (min), then only // it makes sense to check rectangle and override min (if these points forms the correct rectangle) int area = Math.abs(x1 - x2) * Math.abs(y1 - y2); if (area < min) { boolean isRectangle = map.get(x1).contains(y2) && map.get(x2).contains(y1); if (isRectangle) min = area; } } } return min == Integer.MAX_VALUE ? 0 : min; } }
class Solution { public: int minAreaRect(vector<vector<int>>& points) { unordered_map<int, unordered_set<int>> pts; for(auto p : points) { pts[p[0]].insert(p[1]); } int minArea = INT_MAX; int n = points.size(); for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { auto p1 = points[i]; auto p2 = points[j]; if(pts[p1[0]].size()<2 || pts[p2[0]].size()<2) continue; // added to avoid extra loop if(p1[0]!=p2[0] && p1[1]!=p2[1]){ if(pts[p1[0]].count(p2[1])>0 && pts[p2[0]].count(p1[1])>0) { minArea = min(minArea, (abs(p1[0]-p2[0]) * abs(p1[1]-p2[1])) ); } } } } return minArea == INT_MAX ? 0 : minArea; } };
var minAreaRect = function(points) { const mapOfPoints = new Map(); let minArea = Infinity; for(const [x,y] of points) { let keyString = `${x}:${y}` mapOfPoints.set(keyString, [x, y]); } for(const [xLeftBottom, yLeftBottom] of points) { for(const [xRightTop, yRightTop] of points) { if(!foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop)) continue; let leftTopCorner = `${xLeftBottom}:${yRightTop}`; let rightBottomCorner = `${xRightTop}:${yLeftBottom}`; if(mapOfPoints.has(leftTopCorner) && mapOfPoints.has(rightBottomCorner)) { const x2 = mapOfPoints.get(rightBottomCorner)[0]; const x1 = xLeftBottom; const y1 = yLeftBottom; const y2 = mapOfPoints.get(leftTopCorner)[1] const area = calculateArea(x1, x2, y1, y2); minArea = Math.min(minArea,area); } } } return minArea === Infinity ? 0 : minArea; }; function calculateArea(x1, x2, y1, y2) { return ((x2-x1) * (y2-y1)) } function foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop) { return (xRightTop > xLeftBottom && yRightTop > yLeftBottom); }
Minimum Area Rectangle
Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. &nbsp; Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: Input: nums = [2,3] Output: [2,3] &nbsp; Constraints: 2 &lt;= nums.length &lt;= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 &lt;= nums[i] &lt;= 1000 &nbsp; Follow Up: Could you solve it in-place?
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: arr = [None]*len(nums) even,odd = 0,1 for i in(nums): if i % 2 == 0: arr[even] = i even +=2 for i in (nums): if i % 2 != 0: arr[odd] = i odd+=2 return arr
class Solution { public int[] sortArrayByParityII(int[] nums) { int[] ans = new int[nums.length]; int even_pointer = 0; int odd_pointer = 1; for(int i = 0; i < nums.length; i++){ if(nums[i] % 2 == 0){ ans[even_pointer] = nums[i]; even_pointer += 2; } else{ ans[odd_pointer] = nums[i]; odd_pointer += 2; } } return ans; } }
class Solution { public: vector<int> sortArrayByParityII(vector<int>& nums) { vector<int>ans(nums.size()); int even_idx=0; int odd_idx=1; for(int i=0;i<nums.size();i++) { if((nums[i]%2)==0) //the num is even { ans[even_idx]=nums[i]; even_idx+=2; } else //the num is odd { ans[odd_idx]=nums[i]; odd_idx+=2; } } return ans; } };
var sortArrayByParityII = function(nums) { let arrEven = [] let arrOdd = [] let result = [] for(let i in nums){ nums[i]%2==0 ? arrEven.push(nums[i]) : arrOdd.push(nums[i]) } for(let i in arrEven){ result.push(arrEven[i]) result.push(arrOdd[i]) } return result };
Sort Array By Parity II
Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD&nbsp;as shown in the examples. &nbsp; Example 1: Input: date1 = "2019-06-29", date2 = "2019-06-30" Output: 1 Example 2: Input: date1 = "2020-01-15", date2 = "2019-12-31" Output: 15 &nbsp; Constraints: The given dates are valid&nbsp;dates between the years 1971 and 2100.
from datetime import date class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days)
class Solution { public int daysBetweenDates(String date1, String date2) { String[] d1 = date1.split("-"); String[] d2 = date2.split("-"); return (int)Math.abs( daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2])) - daysFrom1971(Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2]))); } private int daysFrom1971(int year, int month, int day) { int total = 0; // count years first total += (year - 1971) * 365; for (int i = 1972; i < year; i += 4) { if (isLeapYear(i)) total++; } int feb = isLeapYear(year) ? 29 : 28; // sum months and days switch (month) { case 12: total += 30; // 11 case 11: total += 31; // 10 case 10: total += 30; // 9 case 9: total += 31; // 8 case 8: total += 31; // 7 case 7: total += 30; // 6 case 6: total += 31; // 5 case 5: total += 30; // 4 case 4: total += 31; // 3 case 3: total += feb; // 2 case 2: total += 31; case 1: total += day; } return total; } private boolean isLeapYear(int i) { return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0); } }
class Solution { public: int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; bool isLeap(int y) { return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)); } int calc(string s) { int y = stoi(s.substr(0, 4)); int m = stoi(s.substr(5, 2)); int d = stoi(s.substr(8)); for (int i = 1971; i < y; i++) d += isLeap(i) ? 366 : 365; d += accumulate(begin(days), begin(days) + m - 1, 0); d += (m > 2 && isLeap(y)) ? 1 : 0; return d; } int daysBetweenDates(string date1, string date2) { int ans = abs(calc(date2) - calc(date1)); return ans; } };
var daysBetweenDates = function(date1, date2) { let miliSecondInaDay = 24*60*60*1000; if(date1>date2) return (new Date(date1) - new Date(date2)) / miliSecondInaDay else return (new Date(date2) - new Date(date1)) / miliSecondInaDay };
Number of Days Between Two Dates
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. &nbsp; Example 1: Input: a = 2, b = [3] Output: 8 Example 2: Input: a = 2, b = [1,0] Output: 1024 Example 3: Input: a = 1, b = [4,3,3,8,5,2] Output: 1 &nbsp; Constraints: 1 &lt;= a &lt;= 231 - 1 1 &lt;= b.length &lt;= 2000 0 &lt;= b[i] &lt;= 9 b does not contain leading zeros.
class Solution: def superPow(self, a: int, b: List[int]) -> int: mod = 1337 ans = 1 for power in b: ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod return ans
import java.math.BigInteger; class Solution { public int superPow(int a, int[] b) { StringBuilder bigNum = new StringBuilder(); Arrays.stream(b).forEach(i -> bigNum.append(i)); return BigInteger.valueOf(a) .modPow(new BigInteger(bigNum.toString()), BigInteger.valueOf(1337)) .intValue(); } }
class Solution { public: int binaryExp(int a, int b, int M) { int ans = 1; a %= M; while(b) { if(b&1) ans = (ans * a)%M; a = (a*a)%M, b = b>>1; } return ans; } int superPow(int a, vector<int>& b) { int bmod = 0; for(auto it : b) { bmod = (bmod * 10 + it)%1140; } return binaryExp(a, bmod, 1337); } };
var superPow = function(a, b) { const MOD = 1337; const pow = (num, n) => { let result = 1; for (let index = 0; index < n; index++) { result = result * num % MOD; } return result; }; return b.reduceRight((result, n) => { a %= MOD; const powNum = result * pow(a, n) % MOD; a = pow(a, 10); return powNum; }, 1); };
Super Pow
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right. &nbsp; Example 1: Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] Example 2: Input: preorder = [1,3] Output: [1,null,3] &nbsp; Constraints: 1 &lt;= preorder.length &lt;= 100 1 &lt;= preorder[i] &lt;= 1000 All the values of preorder are unique.
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: if not preorder: return None node = preorder.pop(0) root = TreeNode(node) l = [] r = [] for val in preorder: if val < node: l.append(val) else: r.append(val) root.left = self.bstFromPreorder(l) root.right = self.bstFromPreorder(r) return root
class Solution { public TreeNode bstFromPreorder(int[] preorder) { return bst(preorder, 0, preorder.length-1); } public TreeNode bst(int[] preorder, int start, int end){ if(start > end) return null; TreeNode root = new TreeNode(preorder[start]); int breakPoint = start+1; while(breakPoint <= end && preorder[breakPoint] < preorder[start]){ breakPoint++; } root.left = bst(preorder, start+1, breakPoint-1); root.right = bst(preorder, breakPoint, end); 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: TreeNode* help(int &i,vector<int>& preorder, int bound ){ if(i==preorder.size() || preorder[i] > bound) return NULL; TreeNode* root = new TreeNode(preorder[i++]); root->left = help(i,preorder,root->val); root->right = help(i,preorder,bound); return root; } TreeNode* bstFromPreorder(vector<int>& preorder) { int i=0; return help(i,preorder,INT_MAX); } };
var bstFromPreorder = function(preorder) { let head = new TreeNode(preorder[0]); for (let i = 1, curr; i<preorder.length; i++) { curr = head; while (1) { if (preorder[i]>curr.val) if (curr.right !=null) { curr = curr.right; } else { curr.right = new TreeNode(preorder[i]); break; } else if (curr.left !=null) { curr = curr.left; } else { curr.left = new TreeNode(preorder[i]); break; } } } return head; };
Construct Binary Search Tree from Preorder Traversal
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. &nbsp; Example 1: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Example 2: Input: s = "a" Output: [["a"]] &nbsp; Constraints: 1 &lt;= s.length &lt;= 16 s contains only lowercase English letters.
""" we can approach this problem using manacher's algorithm with backtracking and recursion """ class Solution: def partition(self, s: str) -> List[List[str]]: lookup = {"": [[]]} def lps(s): if s in lookup: return lookup[s] final_res = [] result_set = set() for k in range(len(s)): i, j = k, k # check for odd length palindromes while i>= 0 and j < len(s) and s[i] == s[j]: # palindrome found res = [] for partition in lps(s[:i]): res.append(partition + [s[i:j+1]]) for partition in res: for part in lps(s[j+1:]): temp = partition + part if tuple(temp) not in result_set: result_set.add(tuple(temp)) final_res.append(temp) i-=1 j+=1 # check for even length palindromes i, j = k, k+1 while i >= 0 and j < len(s) and s[i] == s[j]: # palindrome found res = [] for partition in lps(s[:i]): res.append(partition + [s[i:j+1]]) for partition in res: for part in lps(s[j+1:]): temp = partition + part if tuple(temp) not in result_set: result_set.add(tuple(temp)) final_res.append(temp) i-=1 j+=1 lookup[s] = final_res return final_res return lps(s)
// Plaindrome Partitioning // Leetcode : https://leetcode.com/problems/palindrome-partitioning/ class Solution { public List<List<String>> partition(String s) { List<List<String>> result = new ArrayList<>(); if(s == null || s.length() == 0) return result; helper(s, 0, new ArrayList<String>(), result); return result; } private void helper(String s, int start, List<String> list, List<List<String>> result){ if(start == s.length()){ result.add(new ArrayList<>(list)); return; } for(int i = start; i < s.length(); i++){ if(isPalindrome(s, start, i)){ list.add(s.substring(start, i+1)); helper(s, i+1, list, result); list.remove(list.size()-1); } } } private boolean isPalindrome(String s, int start, int end){ while(start < end){ if(s.charAt(start++) != s.charAt(end--)) return false; } return true; } }
class Solution { public: bool check(string k) { string l=k; reverse(l.begin(),l.end()); if(k==l)return true; return false; } void solve(string &s,vector<vector<string>>&ans, vector<string>temp,int pos) { if(pos>=s.size()){ans.push_back(temp); return;} string m; for(int i=pos;i<s.size();i++) { m+=s[i]; if(check(m)) {temp.push_back(m); solve(s,ans,temp,i+1); temp.pop_back();} } } vector<vector<string>> partition(string s) { vector<vector<string>>ans; vector<string>temp; solve(s,ans,temp,0); return ans; } };
var partition = function(s) { let result = [] backtrack(0, [], s, result) return result }; function backtrack(i, partition, s, result){ if(i === s.length){ result.push([...partition]) return } for(let j=i;j<s.length;j++){ let str = s.slice(i,j+1) if(isPal(str)){ partition.push(str) backtrack(j+1, partition, s, result) partition.pop() } } } function isPal(str){ return JSON.stringify(str.split('').reverse()) === JSON.stringify(str.split('')) }
Palindrome Partitioning
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. &nbsp; Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Example 2: Input: arr = [1,1] Output: 1 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 104 0 &lt;= arr[i] &lt;= 105
class Solution: def findSpecialInteger(self, arr: List[int]) -> int: l=len(arr) c=(l//4)+1 d={} for i in arr: if i in d: d[i]+=1 else: d[i]=1 if d[i]>=c: return i
class Solution { public int findSpecialInteger(int[] arr) { if (arr.length == 1) { return arr[0]; } int count = (int) Math.ceil(arr.length / 4); System.out.println(count); Map<Integer, Integer> map = new HashMap<>(); for (Integer i : arr) { map.put(i, map.getOrDefault(i, 0) + 1); if (map.get(i) > count) { return i; } } return -1; } }
class Solution { public: int findSpecialInteger(vector<int>& arr) { int freq = 0.25 * arr.size(); map<int,int>m; for(int i: arr) m[i]++; int k; for(auto i: m) { if(i.second > freq) { k = i.first; break; } } return k; } };
function binarySearch(array, target, findFirst) { function helper(start, end) { if (start > end) { return -1; } const middle = Math.floor((start + end) / 2); const value = array[middle]; if (value === target) { if (findFirst) { if (middle === 0 || array[middle - 1] !== value) { return middle; } return helper(start, middle - 1); } else { if (middle === array.length -1 || array[middle + 1] !== value) { return middle; } return helper(middle + 1, end); } } else if (value < target) { return helper(middle + 1, end); } return helper(start, middle - 1); } return helper(0, array.length - 1) } const findFirstOccurance = (array, target) => binarySearch(array, target, true); const findLastOccurance = (array, target) => binarySearch(array, target, false); var findSpecialInteger = function(arr) { for (const i of [Math.floor(arr.length / 4), Math.floor(arr.length / 2), Math.floor(3 * arr.length / 4)]) { const firstOccurance = findFirstOccurance(arr, arr[i]); const lastOccurance = findLastOccurance(arr, arr[i]); if (lastOccurance - firstOccurance + 1 > arr.length / 4) { return arr[i] } } return -1; };
Element Appearing More Than 25% In Sorted Array
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box. &nbsp; Example 1: Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1] Explanation: This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. Example 2: Input: grid = [[-1]] Output: [-1] Explanation: The ball gets stuck against the left wall. Example 3: Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] Output: [0,1,2,3,4,-1] &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 100 grid[i][j] is 1 or -1.
class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: m,n=len(grid),len(grid[0]) for i in range(m): grid[i].insert(0,1) grid[i].append(-1) res=[] for k in range(1,n+1): i , j = 0 , k struck = False while i<m: if grid[i][j]==1: if grid[i][j+1]==1: j+=1 else: struck=True break else: if grid[i][j-1]==-1: j-=1 else: struck=True break i+=1 if struck: res.append(-1) else: res.append(j-1) return res
class Solution { public int dfs(int[][] grid, int i, int j){ if(i==grid.length) return j; if(j<0 || j>=grid[0].length) return -1; if(grid[i][j]==1 && j+1<grid[0].length && grid[i][j+1]==1) return dfs(grid,i+1,j+1); else if(grid[i][j]==-1 && j-1>=0 && grid[i][j-1]==-1) return dfs(grid,i+1,j-1); return -1; } public int[] findBall(int[][] grid) { int m = grid[0].length; int[] ar = new int[m]; for(int j=0;j<m;j++) ar[j]=dfs(grid,0,j); return ar; } }
class Solution { public: int util(vector<vector<int>>&grid,bool top,int i,int j) { if(top==0&&i==grid.size()-1)return j; if(top==1) { if(grid[i][j]==1) { if(j+1>=grid[0].size()||grid[i][j+1]==-1)return -1; return util(grid,!top,i,j+1); } else { if(j-1<0||grid[i][j-1]==1)return -1; return util(grid,!top,i,j-1); } } else { return util(grid,!top,i+1,j); } } vector<int> findBall(vector<vector<int>>& grid) { vector<int>ans(grid[0].size(),-1); for(int i=0;i<grid[0].size();i++) { ans[i]=util(grid,true,0,i); } return ans; } };
var findBall = function(grid) { let m = grid.length, n = grid[0].length, ans = [] for (let start = 0; start < n; start++) { // Iterate through the different starting conditions let j = start for (let i = 0; i < m; i++) { // Then iterate downward from grid[i][j] let dir = grid[i][j] // Compare the direction of the current cell to the direction if (dir === grid[i][j+dir]) j += dir // of the cell on the slant side and move that way if matched else i = m, j = -1 // Otherwise jump to the loop's end and set j to the fail value } ans[start] = j // Update the answer } return ans // Return the completed answer };
Where Will the Ball Fall
You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. &nbsp; Example 1: Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with nums = [1,2,3,4]: - Remove numbers 1 and 4, then nums = [2,3] - Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations. Example 2: Input: nums = [3,1,3,4,3], k = 6 Output: 1 Explanation: Starting with nums = [3,1,3,4,3]: - Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 109 1 &lt;= k &lt;= 109
class Solution: def maxOperations(self, nums: List[int], k: int) -> int: nums.sort() left = 0 right = len(nums) - 1 ans = 0 while left < right: cur = nums[left] + nums[right] if cur == k: ans += 1 left += 1 right -= 1 elif cur < k: left += 1 else: right -= 1 return ans
class Solution { public int maxOperations(int[] nums, int k) { HashMap<Integer,Integer>map=new HashMap<>(); int count=0; for(int i=0;i<nums.length;i++){ //to check if that k-nums[i] present and had some value left or already paired if(map.containsKey(k-nums[i])&&map.get(k-nums[i])>0){ count++; map.put(k-nums[i],map.get(k-nums[i])-1); }else{ //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1 //and if some value is present then it return that value "similar to map.get(i)" and I added 1 on it map.put(nums[i],map.getOrDefault(nums[i],0)+1); } } return count; } }
class Solution { public: int maxOperations(vector<int>& nums, int k) { unordered_map<int, int> Map; for (auto &num: nums) Map[num]++; // count freq of nums int ans = 0; for(auto it=Map.begin(); it!=Map.end(); ++it){ int num = it->first, count = it->second; if(k - num == num) ans += count/2; // if num is half of k add half of it's count in ans else if(Map.count(k - num)){ // find k-num in nums and add min freq of num or k-num to ans int Min = min(count, Map[k-num]); ans += Min; Map[num] -= Min; Map[k-num] -= Min; } } return ans; } };
var maxOperations = function(nums, k) { let freq = new Map(),count=0; for (let i = 0; i < nums.length; i++) { if (freq.get(k-nums[i])) { if(freq.get(k-nums[i])==1) freq.delete(k-nums[i]) else freq.set(k-nums[i],freq.get(k-nums[i])-1) count++; }else freq.set(nums[i],freq.get(nums[i])+1||1) } return count; };
Max Number of K-Sum Pairs
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] &gt;= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. &nbsp; Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. &nbsp; Constraints: 1 &lt;= g.length &lt;= 3 * 104 0 &lt;= s.length &lt;= 3 * 104 1 &lt;= g[i], s[j] &lt;= 231 - 1
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() cont = 0 c = 0 k = 0 while k< len(s) and c < len(g): if s[k] >= g[c]: c+=1 k+=1 cont+=1 else: k+=1 return cont
class Solution { public int findContentChildren(int[] g, int[] s) { int i =0,j=0,c=0; Arrays.sort(g); Arrays.sort(s); for(;i< g.length;i++) { // System.out.println(s[j]+" "+g[i]); while(j<s.length) { if(s[j]>=g[i] ) { // System.out.println(s[j]+" "+g[i]); j++;c++; break; } j++; } } return c; } }
class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { int n=g.size(); int m=s.size(); if(n==0 or m==0)return 0; sort(g.begin(),g.end()); sort(s.begin(),s.end()); int i=0,j=0; while(i<m and j<n) { if(s[i]>=g[j]) j++; i++; } return j; } };
var findContentChildren = function(g, s) { g.sort(function(a, b) { return b - a; }); s.sort(function(a, b) { return a - b; }); let content = 0; for (let curG of g) { for (let curS of s) { if (curS >= curG) { s.pop(); content++; break; } } } return content; }
Assign Cookies
Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: Each substring is balanced. Return the maximum number of balanced strings you can obtain. &nbsp; Example 1: Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. Example 2: Input: s = "RLRRRLLRLL" Output: 2 Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced. Example 3: Input: s = "LLLLRRRR" Output: 1 Explanation: s can be split into "LLLLRRRR". &nbsp; Constraints: 2 &lt;= s.length &lt;= 1000 s[i] is either 'L' or 'R'. s is a balanced string.
class Solution: def balancedStringSplit(self, s: str) -> int: r_count=l_count=t_count=0 for i in s: if i=='R': r_count+=1 elif i=='L': l_count+=1 if r_count==l_count: t_count+=1 r_count=0 l_count=0 continue return t_count
class Solution { public int balancedStringSplit(String s) { int nl = 0; int nr = 0; int count = 0; for (int i = 0; i < s.length(); ++i) { if (s.substring(i,i+1).equals("L")) ++nl; else ++nr; if (nr == nl) { ++count; } } return count; } }
class Solution { public: int balancedStringSplit(string s) { int left = 0; int right = 0; int cnt = 0; for(int i=0 ; i<s.size() ; i++){ if(s[i] == 'L'){ left++; } if(s[i] == 'R'){ right++; } if(left - right == 0){ cnt++; } } return cnt; } }
var balancedStringSplit = function(s) { let r_count = 0; let l_count = 0; let ans =0; for(let i = 0 ; i < s.length;i++){ if(s[i]==='R') r_count++; else l_count++; if(l_count==r_count) { l_count=0 r_count=0; ans++ } } return ans };
Split a String in Balanced Strings
You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i &gt; 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. &nbsp; Example 1: Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0] Output: true Explanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0]. These subarrays are disjoint as they share no common nums[k] element. Example 2: Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2] Output: false Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups. [10,-2] must come before [1,2,3,4]. Example 3: Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7] Output: false Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint. They share a common elements nums[4] (0-indexed). &nbsp; Constraints: groups.length == n 1 &lt;= n &lt;= 103 1 &lt;= groups[i].length, sum(groups[i].length) &lt;= 103 1 &lt;= nums.length &lt;= 103 -107 &lt;= groups[i][j], nums[k] &lt;= 107
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: groups = ['-'.join(str(s) for s in group) for group in groups] nums = '-'.join(str(s) for s in nums) j = k = 0 while k < len(groups): group = groups[k] i = nums.find(group, j) if i == -1: return False if i == 0 or i > 0 and nums[i-1] == '-': j = i + len(group) k += 1 else: j += 1 return True
class Solution { public int search(int[] group, int[] nums, int start, int end ) { int i=start, j=0; while(i<end && j<group.length) { if(nums[i] == group[j]) { i++; j++; if(j == group.length) return i; } else { i = i - j + 1; j = 0; } } return -1; } public boolean canChoose(int[][] groups, int[] nums) { int start=0, end =nums.length; for(int[] group : groups) { start = search(group, nums, start, end); if(start == -1) return false; } return true; } }
class Solution { public: //Idea is to use KMP Longest Prefix Suffix array to match if one array is subarray of another array. bool canChoose(vector<vector<int>>& groups, vector<int>& nums) { int m = nums.size(); int index = 0; for(auto group : groups){ int n = group.size(); //Step-1 Generate LPS vector<int>lps(n,0); for(int i = 1;i<n; i++){ int j = lps[i-1]; while(j>0 && group[i] != group[j]){ j = lps[j-1]; } if(group[i] == group[j]){ j++; } lps[i] = j; } //Step 2 - Matching int j = 0; while(index<m){ if(nums[index]==group[j]){ j++; index++; } if(j==n) break; else if(index <m && nums[index] != group[j]){ if(j >0){ j=lps[j-1]; }else{ index++; } } } if(j != n) return false; } return true; } };
/** * @param {number[][]} groups * @param {number[]} nums * @return {boolean} */ var canChoose = function(groups, nums) { let i=0; for(let start=0;i<groups.length&&groups[i].length+start<=nums.length;start++){ if(search(groups[i], nums, start)){ start+=groups[i].length-1; i++; } } return i==groups.length; function search(group, nums, start){ for(let i =0;i<group.length;i++){ if(group[i]!=nums[i+start]) return false; } return true; } };
Form Array by Concatenating Subarrays of Another Array
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. &nbsp; Example 1: Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] Example 2: Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]] Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] Example 3: Input: nums1 = [1,2], nums2 = [3], k = 3 Output: [[1,3],[2,3]] Explanation: All possible pairs are returned from the sequence: [1,3],[2,3] &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 105 -109 &lt;= nums1[i], nums2[i] &lt;= 109 nums1 and nums2 both are sorted in ascending order. 1 &lt;= k &lt;= 104
import heapq class Solution: def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: ans = [] heapq.heapify(ans) for i in range(min(k,len(nums1))): for j in range(min(k,len(nums2))): pairs = [nums1[i],nums2[j]] if len(ans)<k: heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs]) else: if nums1[i]+nums2[j]>-ans[0][0]: break heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs]) heapq.heappop(ans) res = [] for i in range(len(ans)): res.append(ans[i][1]) return res
class Solution { public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) { PriorityQueue<int []> pq = new PriorityQueue<>( (a, b) -> (a[0] + a[1]) - (b[0] + b[1]) ); for(int i = 0; i < nums1.length && i < k; i++){ pq.add(new int[]{nums1[i], nums2[0], 0}); } List<List<Integer>> res = new ArrayList<>(); for(int i = 0; i < k && !pq.isEmpty(); i++){ int [] curr = pq.poll(); res.add(Arrays.asList(curr[0], curr[1])); int idx2 = curr[2]; if(idx2 < nums2.length - 1){ pq.add(new int[]{curr[0], nums2[idx2 + 1], idx2 + 1}); } } return res; } }
class Solution { public: vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { priority_queue<pair<int,pair<int,int>>> pq; int m=nums1.size(),n=nums2.size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ int sum=nums1[i]+nums2[j]; if(pq.size()<k){ pq.push({sum,{nums1[i],nums2[j]}}); }else if(sum<pq.top().first){ pq.pop(); pq.push({sum,{nums1[i],nums2[j]}}); }else break; } } vector<vector<int>> ans; while(!pq.empty()){ auto p=pq.top().second; pq.pop(); ans.push_back({p.first,p.second}); } return ans; } };
/** * @param {number[]} nums1 * @param {number[]} nums2 * @param {number} k * @return {number[][]} */ var kSmallestPairs = function(nums1, nums2, k) { const h = new MinHeap(); h.sortKey = 'id'; for(i =0; i<nums1.length; i++) h.push({id: nums1[i]+nums2[0], i: i, j: 0}); let res = []; while(k--){ const t = h.pop(); if(!t) return res; let {i, j} =t; res.push([nums1[i], nums2[j]]); if(j< nums2.length-1) h.push({id: nums1[i]+nums2[j+1], i, j: j+1}); } return res; }; /* This is a heap class that I wrote it myself, neat? IDK bad? IDK bug? IDK (tested a few times for both min and max heaps) so use it at your own risk :) */ class Heap{ constructor(arr = [], sortKey=null){ this.heap = []; this.sortKey = sortKey; if(arr && arr.length) this.buildHeap(arr); } push(val){ this.heap.push(val); this.heapUp(this.heap.length-1); } pop(){ if(!this.heap.length) return null; if(this.heap.length==1) return this.heap.pop(); const res = this.heap[0]; this.heap[0] = this.heap.pop(); this.heapDown(0); return res; } id(i){ if(this.sortKey!==null) return this.heap[i][this.sortKey]; return this.heap[i]; } swap(i, j){ const t = this.heap[i]; this.heap[i] = this.heap[j]; this.heap[j] = t; } /*for child class to implement*/ heapUp(i){ //heap up } heapDown(i){ //heap down } buildHeap(list){ //build heap for(let i of list) this.push(i); } toString(){ return this.heap; } } class MinHeap extends Heap{ heapUp(i){ const pI = (i-1)>>1; if(pI<0) return; if(this.id(i)<this.id(pI)){ this.swap(i, pI); return this.heapUp(pI); } } heapDown(i){ const lI = i*2+1; const rI = i*2+2; if(lI>=this.heap.length) return; const v = Math.min(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MAX_VALUE:this.id(rI)); if(v==this.id(i)) return; if(v==this.id(lI)){ this.swap(i, lI); return this.heapDown(lI); } this.swap(i, rI); this.heapDown(rI); } } class MaxHeap extends Heap{ heapUp(i){ const pI = (i-1)>>1; if(pI<0) return; if(this.id(i)>this.id(pI)){ this.swap(i, pI); return this.heapUp(pI); } } heapDown(i){ const lI = i*2+1; const rI = i*2+2; if(lI>=this.heap.length) return; const v = Math.max(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MIN_VALUE:this.id(rI)); if(v==this.id(i)) return; if(v==this.id(lI)){ this.swap(i, lI); return this.heapDown(lI); } this.swap(i, rI); this.heapDown(rI); } }
Find K Pairs with Smallest Sums
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. &nbsp; Example 1: Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. Example 2: Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1] Example 3: Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 200]. Node.val is either 0 or 1.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def dfs(node): if not node: return None left = dfs(node.left) right = dfs(node.right) if node.val == 0 and not left and not right: return None else: node.left = left node.right = right return node return dfs(root)
class Solution { public TreeNode pruneTree(TreeNode root) { if(root == null) return root; root.left = pruneTree(root.left); root.right = pruneTree(root.right); if(root.left == null && root.right == null && root.val == 0) return null; else return root; } }
class Solution { public: TreeNode* pruneTree(TreeNode* root) { if(!root) return NULL; root->left = pruneTree(root->left); root->right = pruneTree(root->right); if(!root->left && !root->right && root->val==0) return NULL; return root; } };
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var pruneTree = function(root) { let rec = function(node){ if(node==null) return null; if(node.val===0 && node.left == null && node.right == null){ return null } node.left = rec(node.left); node.right = rec(node.right); // For updated tree structure if threre are leaf nodes with zero value present, if yes then return null otherewise return node itself. if(node.val===0 && node.left == null && node.right == null){ return null } return node; } rec (root); if(root.val == 0 && root.left == null && root.right == null) return null return root; };
Binary Tree Pruning
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign. For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not. You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence. Note that all prices will contain at most 10 digits. &nbsp; Example 1: Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50 Output: "there are $0.50 $1.00 and 5$ candies in the shop" Explanation: The words which represent prices are "$1" and "$2". - A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50". - A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00". Example 2: Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100 Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$" Explanation: Applying a 100% discount on any price will result in 0. The words representing prices are "$3", "$5", "$6", and "$9". Each of them is replaced by "$0.00". &nbsp; Constraints: 1 &lt;= sentence.length &lt;= 105 sentence consists of lowercase English letters, digits, ' ', and '$'. sentence does not have leading or trailing spaces. All words in sentence are separated by a single space. All prices will be positive numbers without leading zeros. All prices will have at most 10 digits. 0 &lt;= discount &lt;= 100
class Solution: def discountPrices(self, sentence: str, discount: int) -> str: s = sentence.split() # convert to List to easily update m = discount / 100 for i,word in enumerate(s): if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format num = int(word[1:]) * (1-m) # discounted price w = "$" + "{:.2f}".format(num) #correctly format s[i] = w #Change inside the list return " ".join(s) #Combine the updated list ```
class Solution { public String discountPrices(String sentence, int discount) { String x[] = sentence.split(" "); StringBuilder sb = new StringBuilder(); for (String s : x) { if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + " "); else sb.append(s + " "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } boolean isPrice(String s) { return s.startsWith("$") && s.substring(1).matches("\\d+"); } String calc(double num, double discount) { double ans = num - (double) ((double) num * discount / 100.00); return "$" + String.format("%.2f", ans); } }
class Solution { public: string discountPrices(string sentence, int discount) { // doit is a function auto doit = [&](string word) { int n(size(word)); if (word[0] != '$' or n == 1) return word; long long price = 0; for (int i=1; i<n; i++) { if (!isdigit(word[i])) return word; price = price*10 + (word[i]-'0'); } stringstream ss2; double discountPercentage = (100 - discount) / 100.0; ss2 << fixed << setprecision(2) << (discountPercentage * price); return "$" + ss2.str(); }; string word, res; stringstream ss(sentence); while (ss >> word) { res += doit(word)+" "; } res.pop_back(); return res; } };
var discountPrices = function(sentence, discount) { let isNum = (num) => { if(num.length <= 1 || num[0] != '$') return false; for(let i = 1; i < num.length; ++i) if(!(num[i] >= '0' && num[i] <= '9')) return false; return true; }; let x = sentence.split(' '); discount = 1 - (discount/100); for(let i = 0; i < x.length; ++i) !isNum(x[i]) || (x[i] = `$${(Number(x[i].slice(1))*discount).toFixed(2)}`); return x.join(' '); };
Apply Discount to Prices
You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through, 1 means the cell contains a cherry that you can pick up and pass through, or -1 means the cell contains a thorn that blocks your way. Return the maximum number of cherries you can collect by following the rules below: Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1). After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells. When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0. If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected. &nbsp; Example 1: Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]] Output: 5 Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2). 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]]. Then, the player went left, up, up, left to return home, picking up one more cherry. The total number of cherries picked up is 5, and this is the maximum possible. Example 2: Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]] Output: 0 &nbsp; Constraints: n == grid.length n == grid[i].length 1 &lt;= n &lt;= 50 grid[i][j] is -1, 0, or 1. grid[0][0] != -1 grid[n - 1][n - 1] != -1
class Solution: def cherryPickup(self, grid): n = len(grid) dp = [[-1] * (n + 1) for _ in range(n + 1)] dp[1][1] = grid[0][0] for m in range(1, (n << 1) - 1): for i in range(min(m, n - 1), max(-1, m - n), -1): for p in range(i, max(-1, m - n), -1): j, q = m - i, m - p if grid[i][j] == -1 or grid[p][q] == -1: dp[i + 1][p + 1] = -1 else: dp[i + 1][p + 1] = max(dp[i + 1][p + 1], dp[i][p + 1], dp[i + 1][p], dp[i][p]) if dp[i + 1][p + 1] != -1: dp[i + 1][p + 1] += grid[i][j] + (grid[p][q] if i != p else 0) return max(0, dp[-1][-1])
class Solution { public int cherryPickup(int[][] grid) { int m = grid.length, n = grid[0].length; //For O(N^3) Dp sapce solution dp2 = new Integer[m][n][m]; int ans=solve2(0,0,0,grid,0,m,n); if(ans==Integer.MIN_VALUE) return 0; return ans; } private Integer[][][] dp2; private int solve2(int x1, int y1, int x2, int[][] g, int cpsf, int m, int n){ int y2 = x1+y1+-x2; if(x1>=m||x2>=m||y1>=n||y2>=n||g[x1][y1]==-1||g[x2][y2]==-1) return Integer.MIN_VALUE; if(x1==m-1&&y1==n-1) return g[x1][y1]; //If both p1 and p2 reach (m-1,n-1) if(dp2[x1][y1][x2]!=null) return dp2[x1][y1][x2]; int cherries=0; //If both p1 and p2 are at same position then we need to add the cherry only once. if(x1==x2&&y1==y2){ cherries+=g[x1][y1]; } //If p1 and p2 are at different positions then repective cherries can be added. else{ cherries+=g[x1][y1]+g[x2][y2]; } //4 possibilites for p1 and p2 from each point int dd=solve2(x1+1,y1,x2+1,g,cpsf+cherries,m,n); //both moves down int dr=solve2(x1+1,y1,x2,g,cpsf+cherries,m,n); //p1 moves down and p2 moves right int rr=solve2(x1,y1+1,x2,g,cpsf+cherries,m,n); //both moves right int rd=solve2(x1,y1+1,x2+1,g,cpsf+cherries,m,n); //p1 moves right and p2 moves down //We take maximum of 4 possiblities int max=Math.max(Math.max(dd,dr), Math.max(rr,rd)); if(max==Integer.MIN_VALUE) return dp2[x1][y1][x2]=max; return dp2[x1][y1][x2]=cherries+=max; } }
class Solution { public: int solve(int r1,int c1,int r2,vector<vector<int>>& grid, vector<vector<vector<int>>> &dp) { //Calculating c2 : /* (r1 + c1) = (r2 + c2) c2 = (r1 + c1) - r2 */ int c2 = (r1+c1)-r2 ; //Base condition if(r1 >= grid.size() || r2 >= grid.size() || c1 >= grid[0].size() || c2 >= grid[0].size() || grid[r1][c1] == -1 || grid[r2][c2] == -1) { return INT_MIN; } if(r1 == grid.size()-1 && c1 == grid[0].size()-1) { return grid[r1][c1] ; } if(dp[r1][c1][r2] != -1) { return dp[r1][c1][r2]; } int ch = 0; if(r1 == r2 && c1 == c2) { ch += grid[r1][c1]; //if both players are at the same place than collect cherry only one time. } else { ch += grid[r1][c1] + grid[r2][c2]; } cout<<ch<<"\n"; //Trying all the possible paths for both the players int hh = solve(r1, c1+1, r2, grid, dp); int vh = solve(r1+1, c1, r2, grid, dp); int vv = solve(r1+1, c1, r2+1, grid, dp); int hv = solve(r1, c1+1, r2+1, grid, dp); //collecting maximum cherries from possible paths ch += max(max(hh, vh),max(vv, hv)) ; dp[r1][c1][r2] = ch; return ch; } int cherryPickup(vector<vector<int>>& grid) { int n = grid.size(); vector<vector<vector<int>>>dp(n, vector<vector<int>>(n, vector<int>(n,-1))); int ans = solve(0,0,0,grid,dp) ; if(ans == INT_MIN || ans <0) { return 0; } return ans; } };
var cherryPickup = function(grid) { let result = 0, N = grid.length, cache = {}, cherries; const solve = (x1, y1, x2, y2) => { if(x1 === N -1 && y1 === N-1) return grid[x1][y1] !== -1 ? grid[x1][y1] : -Infinity; if(x1 > N -1 || y1 > N-1 || x2 > N-1 || y2 > N-1 || grid[x1][y1] === -1 ||grid[x2][y2] === -1) return -Infinity; let lookup_key = `${x1}:${y1}:${x2}:${y2}`; if(cache[lookup_key]) return cache[lookup_key]; if(x1 === x2 && y1 === y2) cherries = grid[x1][y1]; else cherries = grid[x1][y1] + grid[x2][y2]; result = cherries + Math.max(solve(x1 + 1, y1, x2 + 1, y2), solve(x1, y1 + 1, x2, y2 + 1), solve(x1 + 1, y1, x2, y2 + 1), solve(x1, y1 + 1, x2 + 1, y2)); cache[lookup_key] = result; return result; }; result = solve(0, 0, 0, 0); return result > 0 ? result : 0; };
Cherry Pickup
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). &nbsp; Example 1: Input: n = 4, rounds = [1,3,1,2] Output: [1,2] Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --&gt; 2 --&gt; 3 (end of round 1) --&gt; 4 --&gt; 1 (end of round 2) --&gt; 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. Example 2: Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2] Output: [2] Example 3: Input: n = 7, rounds = [1,3,5,7] Output: [1,2,3,4,5,6,7] &nbsp; Constraints: 2 &lt;= n &lt;= 100 1 &lt;= m &lt;= 100 rounds.length == m + 1 1 &lt;= rounds[i] &lt;= n rounds[i] != rounds[i + 1] for 0 &lt;= i &lt; m
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: hash_map = {} for i in range(0 , len(rounds)-1): if i == 0: start = rounds[i] elif rounds[i] == n: start = 1 else: start = rounds[i] + 1 end = rounds[i+1] if start <= end: for i in range(start , end + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 else: for i in range(start , n + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 for i in range(1 , end + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 k = list(hash_map.keys()) v = list(hash_map.values()) ans = [] m = -1 i = 0 j = 0 while i < len(k) and j < len(v): if len(ans) == 0: ans.append(k[i]) m = v[j] elif m < v[j]: ans = [] ans.append(k[i]) m = v[j] elif m == v[j]: ans.append(k[i]) i += 1 j += 1 ans = sorted(ans) return ans
class Solution { public List<Integer> mostVisited(int n, int[] rounds) { int[]psum=new int[n+2]; psum[rounds[0]]+=1; psum[rounds[1]+1]-=1; if(rounds[0]>rounds[1]) psum[1]+=1; for(int i=2;i<rounds.length;i++){ psum[rounds[i-1]+1]+=1; psum[rounds[i]+1]-=1; if(rounds[i-1]>rounds[i]) psum[1]+=1; } int max_=0; for(int i=1;i<=n;i++){ psum[i]+=psum[i-1]; if(psum[i]>max_) max_=psum[i]; } List<Integer>ans=new ArrayList<>(); for(int i=1;i<=n;i++){ if(psum[i]==max_) ans.add(i); } return ans; } }
class Solution { public: vector<int> mostVisited(int n, vector<int>& rounds) { vector <int> ans; int size = rounds.size(); if(rounds[0] <= rounds[size-1]) { for(int i=rounds[0]; i<= rounds[size-1]; i++) { ans.push_back(i); } return ans; } else { for(int i=1; i<= rounds[size-1]; i++) { ans.push_back(i); } for(int i=rounds[0]; i<=n; i++) { ans.push_back(i); } } return ans; } };
var mostVisited = function(n, rounds) { const first = rounds[0]; const last = rounds[rounds.length - 1]; const result = []; if (first <= last) { for (let i = last; i >= first; i--) result.unshift(i) } else { for (let i = 1; i <= last; i++) result.push(i); for (let i = first; i <= n; i++) result.push(i); } return result; };
Most Visited Sector in a Circular Track
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. &nbsp; Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s consists of only uppercase English letters. 0 &lt;= k &lt;= s.length
class Solution: def characterReplacement(self, s: str, k: int) -> int: # Initialize variables window_start = 0 max_length = 0 max_count = 0 char_count = {} # Traverse the string s for window_end in range(len(s)): # Increment the count of the current character char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1 # Update the maximum count seen so far max_count = max(max_count, char_count[s[window_end]]) # Shrink the window if required if window_end - window_start + 1 > max_count + k: char_count[s[window_start]] -= 1 window_start += 1 # Update the maximum length of the substring with repeating characters seen so far max_length = max(max_length, window_end - window_start + 1) return max_length
class Solution { public int characterReplacement(String s, int k) { HashMap<Character,Integer> map=new HashMap<>(); int i=-1; int j=-1; int ans=0; while(true){ boolean f1=false; boolean f2=false; while(i<s.length()-1){ //acquire i++; f1=true; char ch=s.charAt(i); map.put(ch,map.getOrDefault(ch,0)+1); int count=0; for(char key:map.keySet()){ count=Math.max(count,map.get(key)); } int replace=(i-j) - count; if(replace<=k) { ans=Math.max(i-j,ans); } else break; } while(j<i){ //release f2=true; j++; char ch=s.charAt(j); isremove(map,ch); int count=0; for(char key:map.keySet()){ count=Math.max(count,map.get(key)); } int replace=(i-j) - count; if(replace<=k){ ans=Math.max(i-j,ans); break; } else continue; } if(f1==false && f2==false) break; } return ans; } static void isremove(HashMap<Character,Integer> map,char ch){ if(map.get(ch)==1) map.remove(ch); else map.put(ch,map.get(ch)-1); } }
class Solution { public: int characterReplacement(string s, int k) { int n = s.length(); if(n == k) return n; if(n == 1) return 1; int res = 0; int maxCnt = 0; unordered_map<char,int> mp; for(int l = 0, r = 0; r < n; r++) { mp[s[r]]++; maxCnt = max(maxCnt,mp[s[r]]); while(r - l + 1 - maxCnt > k){ mp[s[l]]--; l++; } res = max(r - l + 1, res); } return res; } };
// O(n) time | O(26) -> O(1) space - only uppercase English letters var characterReplacement = function(s, k) { const sLen = s.length, charCount = {}; if (k >= sLen) return sLen; let maxLen = 0, windowStart = 0, maxRepeatChar = 0; for (let windowEnd = 0; windowEnd < sLen; windowEnd++) { // increment charCount charCount[s[windowEnd]] ? charCount[s[windowEnd]]++ : charCount[s[windowEnd]] = 1; // calc max repeating char maxRepeatChar = Math.max(maxRepeatChar, charCount[s[windowEnd]]); // calc number of char that is not (or has fewer chars) repeating in window const remainingChar = windowEnd - windowStart + 1 - maxRepeatChar; // slide window by incrementing start of window if (remainingChar > k) { // decrement charCount charCount[s[windowStart]]--; windowStart++; } // calc maxLen maxLen = Math.max(maxLen, windowEnd - windowStart + 1); } return maxLen; };
Longest Repeating Character Replacement
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order. &nbsp; Example 1: Input: nums = [10,6,5,8] Output: [10,8] Explanation: - 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. - 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. - 5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned. Example 2: Input: nums = [1,3,5,3] Output: [1,5] Explanation: - 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. - 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. - 3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 106
class Solution: def findLonely(self, nums: List[int]) -> List[int]: m = Counter(nums) return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]
class Solution { public List<Integer> findLonely(int[] nums) { Arrays.sort(nums); ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i < nums.length - 1; i++) { if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) { list.add(nums[i]); } } if (nums.length == 1) { list.add(nums[0]); } if (nums.length > 1) { if (nums[0] + 1 < nums[1]) { list.add(nums[0]); } if (nums[nums.length - 2] + 1 < nums[nums.length - 1]) { list.add(nums[nums.length - 1]); } } return list; } }
class Solution { public: vector<int> findLonely(vector<int>& nums) { int n=nums.size(); unordered_map<int,int> ump; vector<int> sol; for(int i=0;i<n;i++) { ump[nums[i]]++; } for(auto a: ump) { if(a.second==1 and !ump.count(a.first+1) and !ump .count(a.first-1)) sol.push_back(a.first); } return sol; } };
var findLonely = function(nums) { let countMap = new Map(); let result = []; for (let num of nums) { countMap.set(num, (countMap.get(num) || 0) + 1); } for (let num of nums) { if (!countMap.has(num - 1) && !countMap.has(num + 1) && countMap.get(num) === 1) { result.push(num); } } return result; };
Find All Lonely Numbers in the Array
You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0"). Find the number of unique good subsequences of binary. For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros. Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. &nbsp; Example 1: Input: binary = "001" Output: 2 Explanation: The good subsequences of binary are ["0", "0", "1"]. The unique good subsequences are "0" and "1". Example 2: Input: binary = "11" Output: 2 Explanation: The good subsequences of binary are ["1", "1", "11"]. The unique good subsequences are "1" and "11". Example 3: Input: binary = "101" Output: 5 Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. The unique good subsequences are "0", "1", "10", "11", and "101". &nbsp; Constraints: 1 &lt;= binary.length &lt;= 105 binary consists of only '0's and '1's.
class Solution: def numberOfUniqueGoodSubsequences(self, binary: str) -> int: # zero_as_last: the count of S0, good sequence ending in 0 # one_as_last : the count of S1: good sequence ending in 1 # zero_exist: existence flag of 0 in given binary dp = {"zero_as_last": 0, "one_as_last": 0, "zero_exist": 0} for bit in map(int, binary): if bit: # current good = ( S0 concate with 1 ) + ( S1 concate with 1 ) + 1 alone # + "1" is allowed because leading 1 is valid by description dp["one_as_last"] = dp["zero_as_last"] + dp["one_as_last"] + 1 else: # current good = ( S0 concate with 0 ) + ( S1 concate with 0 ) # + "0" is NOT allowed because leading 0 is invalid by description dp["zero_as_last"] = dp["zero_as_last"] + dp["one_as_last"] # check the existence of 0 dp["zero_exist"] |= (1-bit) return sum( dp.values() ) % ( 10**9 + 7 )
class Solution { public int numberOfUniqueGoodSubsequences(String binary) { int initialZeroCount= 0; while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++; if(initialZeroCount == binary.length()) return 1; long[] dp = new long[binary.length()]; dp[initialZeroCount] = 1; int lastOne = 0, lastZero = 0; long mod = (long) Math.pow(10, 9)+7; for(int i=initialZeroCount+1;i<binary.length();i++){ int j = binary.charAt(i) == '1' ? lastOne : lastZero; long dup = j > 0 ? dp[j-1] : 0; dp[i] = 2 * dp[i-1] - dup; if(dp[i] < 0) dp[i] += mod; dp[i] %= mod; if(binary.charAt(i) == '0') lastZero = i; else lastOne = i; } int hasZero = 0; if(binary.contains("0")) hasZero = 1; return (int) (dp[binary.length()-1] + hasZero); } }
class Solution { int MOD = 1000000007; public: int numberOfUniqueGoodSubsequences(string binary) { int zero = 0; long long ones = 0; long long zeros = 0; for (int i = binary.size() - 1; i >= 0; --i) { if (binary[i] == '1') { ones = (ones + zeros + 1) % MOD; } else { zero = 1; zeros = (ones + zeros + 1) % MOD; } } return (ones + zero) % MOD; } };
const MOD = 1000000007; var numberOfUniqueGoodSubsequences = function(binary) { let endsZero = 0; let endsOne = 0; let hasZero = 0; for (let i = 0; i < binary.length; i++) { if (binary[i] === '1') { endsOne = (endsZero + endsOne + 1) % MOD; } else { endsZero = (endsZero + endsOne) % MOD; hasZero = 1; } } return (endsZero + endsOne + hasZero) % MOD; };
Number of Unique Good Subsequences
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337. &nbsp; Example 1: Input: n = 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Example 2: Input: n = 1 Output: 9 &nbsp; Constraints: 1 &lt;= n &lt;= 8
class Solution: def largestPalindrome(self, n: int) -> int: return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n] def isPalindrome(x): return str(x) == str(x)[::-1] def solve(n): best = 0 for i in range(10**n-1, 0, -1): for j in range(max(i, (best-1)//i+1), 10**n): if isPalindrome(i*j): #print(i, j, i*j) best = i*j return best
class Solution { public int largestPalindrome(int n) { if(n == 1 ){ return 9; } if(n == 2){ return 987; } if(n == 3){ return 123; } if(n == 4){ return 597; } if(n == 5){ return 677; } if(n == 6){ return 1218; } if(n == 7){ return 877; } return 475; } }
class Solution { public: int largestPalindrome(int n) { if(n==1) { return 9; } int hi=pow(10,n)-1; int lo=pow(10,n-1); int kk=1337; for(int i=hi;i>=lo;i--) { string s=to_string(i); string k=s; reverse(k.begin(),k.end()); s+=k; long long int ll=stol(s); for(int j=hi;j>=sqrtl(ll);j--) { if(ll%j==0) { return ll%kk; } } } return 0; } };
/** * @param {number} n * @return {number} */ var largestPalindrome = function(n) { if (n === 1) return 9; let hi = BigInt(Math.pow(10, n) - 1); let num = hi; while(num > 0) { num -= 1n; const palindrome = BigInt(String(num) + String(num).split('').reverse().join('')); for (let i = hi; i >= 2n; i -= 2n) { const j = palindrome / i; if (j > hi) break; if (palindrome % i === 0n) { return String(palindrome % 1337n); }; } } };
Largest Palindrome Product
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct. &nbsp; Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5 &nbsp; Constraints: 1 &lt;= hour &lt;= 12 0 &lt;= minutes &lt;= 59
class Solution: def angleClock(self, hour: int, minutes: int) -> float: x = abs(minutes * 6 -(hour * 30 + minutes/2)) return min(360-x , x)
class Solution { public double angleClock(int hour, int minutes) { // Position of hour hand in a circle of 0 - 59 double hrPos = 5 * (hour % 12); // Adjust hour hand position according to minute hand hrPos += (5 * minutes/60.0); double units = Math.abs(minutes - hrPos); // Take the min of distance between minute & hour hand and hour & minute hand return Math.min(units, 60-units) * 6; } }
class Solution { public: double angleClock(int hour, int minutes) { double hourAngle = 30*(double(hour) + double(minutes/60.0)); double minuteAngle = 6 * (double)minutes; return 180 - abs(180 - abs(minuteAngle - hourAngle)); } };
var angleClock = function(hour, minutes) { const angle = Math.abs((hour * 30) - 5.5 * minutes) return angle > 180 ? 360 - angle : angle };
Angle Between Hands of a Clock
A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -&gt; "1" 'B' -&gt; "2" ... 'Z' -&gt; "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). Example 3: Input: s = "06" Output: 0 Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s contains only digits and may contain leading zero(s).
class Solution: def numDecodings(self, s: str) -> int: if s[0] == '0' or '00' in s: return 0 l = len(s) if l == 1: return 1 elif l == 2: if s[1] == '0': if s[0] == '1' or s[0] == '2': return 1 else: return 0 else: if int(s) <= 26: return 2 else: return 1 dp = [1] if s[1] == '0': if s[0] == '1' or s[0] == '2': dp.append(1) else: return 0 else: if int(s[:2]) <= 26: dp.append(2) else: dp.append(1) for i in range(2, l): num = 0 if s[i] == '0': if s[i-1] != '1' and s[i-1] != '2': return 0 else: num = dp[i-2] elif s[i-1] == '1' or (s[i-1] == '2' and int(f'{s[i-1]}{s[i]}') <= 26): num = dp[i-1]+dp[i-2] else: num = dp[i-1] dp.append(num) return dp[l-1]
class Solution { public int numDecodings(String s) { int[]dp = new int[s.length() + 1]; dp[0] = 1; dp[1] = s.charAt(0) == '0' ? 0 : 1; for(int i = 2;i<=s.length();i++) { int oneDigit = Integer.valueOf(s.substring(i-1,i)); int twoDigit = Integer.valueOf(s.substring(i-2,i)); if(oneDigit >= 1) { dp[i] += dp[i - 1]; } if(twoDigit >= 10 && twoDigit <= 26) { dp[i] += dp[i - 2]; } } return dp[s.length()]; } }
class Solution { public: int numDecodings(string s) { if(s[0] == 0) return 0; int n = s.length(); vector<int> dp(n+1, 0); //Storing DP[n-1] if(s[n-1] == '0' ) dp[n-1] = 0; else dp[n-1] = 1; if(n == 1) return dp[0]; //Storing DP[n-2] if(s[n-2] == '0') dp[n-2] = 0; else { string temp ; temp.push_back(s[n-2]); temp.push_back(s[n-1]); int x = stoi(temp); if(x<27) dp[n-2] = 1; dp[n-2] += dp[n-1]; } for(int i = n-3; i>=0 ; i--) { if(s[i] == '0') continue; string temp ; temp.push_back(s[i]); temp.push_back(s[i+1]); int x = stoi(temp); if(x<27) dp[i] = dp[i+2]; dp[i]+=dp[i+1]; } return dp[0]; } };
var numDecodings = function(s) { let dp = Array(s.length).fill(0); // dp[i] means, the total ways of decode for substring up to i dp[0] = (s[0] !== '0') ? 1 : 0; for(let i = 1; i < s.length; i++){ //case1 if(s[i] !== '0'){ dp[i] = dp[i - 1]; } //case2 if(s[i-1] === '1' || (s[i-1] === '2' && parseInt(s[i]) <= 6)){ dp[i] += dp[i - 2] ?? 1; } } return dp[s.length - 1]; };
Decode Ways
Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false. &nbsp; Example 1: Input: s = "1001" Output: false Explanation: The ones do not form a contiguous segment. Example 2: Input: s = "110" Output: true &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s[i]​​​​ is either '0' or '1'. s[0] is&nbsp;'1'.
class Solution: def checkOnesSegment(self, s: str) -> bool: return "01" not in s
class Solution { public boolean checkOnesSegment(String s) { return !s.contains("01"); } }
class Solution { public: bool checkOnesSegment(string s) { for(int i = 1; i < s.size(); i++){ if(s[i - 1] == '0' and s[i] == '1'){ return false; } } return true; } };
var checkOnesSegment = function(s) { return s.indexOf("01") == -1 };
Check if Binary String Has at Most One Segment of Ones
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer. &nbsp; Example 1: Input: nums = [2,1,4,3], left = 2, right = 3 Output: 3 Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. Example 2: Input: nums = [2,9,2,5,6], left = 2, right = 8 Output: 7 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 109 0 &lt;= left &lt;= right &lt;= 109
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: n = len(nums) stack = [] next_greater = [n] * n prev_greater = [-1] * n for i in range(n): while len(stack) > 0 and nums[i] > nums[stack[-1]]: curr = stack.pop() next_greater[curr] = i if len(stack) > 0: prev_greater[i] = stack[-1] stack.append(i) res = 0 for i in range(n): if left <= nums[i] <= right: l = prev_greater[i] r = next_greater[i] res += (i - l) * (r - i) return res
class Solution { public int numSubarrayBoundedMax(int[] nums, int left, int right) { int res = 0; int s = -1; int e = -1; for(int i=0;i<nums.length;i++){ if(nums[i] >= left && nums[i] <= right){ e = i; }else if(nums[i] > right){ e = s = i; } res += (e - s); } return res; } }
class Solution { public: int numSubarrayBoundedMax(vector<int>& nums, int left, int right) { int ans = 0; // store ans int j=-1; // starting window int sub = 0; // if current element is less than left bound then count how may element before current element which is less than left and must be continues(it means any element which is greater than left bound reset the count to 0 ) for(int i=0;i<nums.size();i++){ if(nums[i]>right){ j = i; sub = 0; } else if(nums[i]<left){ sub++; } else sub = 0; ans = ans + i - j - sub; } return ans; } };
var numSubarrayBoundedMax = function(nums, left, right) { // si is start index // ei is end index let si=0, ei=0, finalCount=0, currentCount=0; while(ei<nums.length){ // moving ei till length of array if(left<=nums[ei] && nums[ei]<=right) // considering case number falls in the range { currentCount= ei-si+1; // to get the subarrays b/w start index and end index finalCount+=currentCount; // add current count of subarrays to final count which we will return at end } if(nums[ei]<left){ finalCount+=currentCount; // in this case when num is smaller than left range we won't calculate subarrays but just include the current count in final count. } if(nums[ei]>right){ si=ei+1; // in this case when num is greater than right range we need to move our start index to end+1 because there won't be any subarrays that will fall in range. currentCount=0; // we will set current count 0 in such case. } ei++; } return finalCount; };
Number of Subarrays with Bounded Maximum
Implement the class SubrectangleQueries&nbsp;which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1.&nbsp;updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2). 2.&nbsp;getValue(int row, int col) Returns the current value of the coordinate (row,col) from&nbsp;the rectangle. &nbsp; Example 1: Input ["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"] [[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]] Output [null,1,null,5,5,null,10,5] Explanation SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); // The initial rectangle (4x3) looks like: // 1 2 1 // 4 3 4 // 3 2 1 // 1 1 1 subrectangleQueries.getValue(0, 2); // return 1 subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5); // After this update the rectangle looks like: // 5 5 5 // 5 5 5 // 5 5 5 // 5 5 5 subrectangleQueries.getValue(0, 2); // return 5 subrectangleQueries.getValue(3, 1); // return 5 subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10); // After this update the rectangle looks like: // 5 5 5 // 5 5 5 // 5 5 5 // 10 10 10 subrectangleQueries.getValue(3, 1); // return 10 subrectangleQueries.getValue(0, 2); // return 5 Example 2: Input ["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"] [[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]] Output [null,1,null,100,100,null,20] Explanation SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]); subrectangleQueries.getValue(0, 0); // return 1 subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100); subrectangleQueries.getValue(0, 0); // return 100 subrectangleQueries.getValue(2, 2); // return 100 subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20); subrectangleQueries.getValue(2, 2); // return 20 &nbsp; Constraints: There will be at most 500&nbsp;operations considering both methods:&nbsp;updateSubrectangle and getValue. 1 &lt;= rows, cols &lt;= 100 rows ==&nbsp;rectangle.length cols == rectangle[i].length 0 &lt;= row1 &lt;= row2 &lt; rows 0 &lt;= col1 &lt;= col2 &lt; cols 1 &lt;= newValue, rectangle[i][j] &lt;= 10^9 0 &lt;= row &lt; rows 0 &lt;= col &lt; cols
class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): self.rectangle = rectangle def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: for i in range(row1,row2+1): for j in range(col1,col2+1): self.rectangle[i][j] = newValue def getValue(self, row: int, col: int) -> int: return self.rectangle[row][col]
class SubrectangleQueries { int[][] rectangle; public SubrectangleQueries(int[][] rectangle) { this.rectangle = rectangle; } public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { for(int i=row1;i<=row2;i++){ for(int j=col1;j<=col2;j++){ rectangle[i][j] = newValue; } } } public int getValue(int row, int col) { return this.rectangle[row][col]; } } /** * Your SubrectangleQueries object will be instantiated and called as such: * SubrectangleQueries obj = new SubrectangleQueries(rectangle); * obj.updateSubrectangle(row1,col1,row2,col2,newValue); * int param_2 = obj.getValue(row,col); */
class SubrectangleQueries { public: vector<vector<int>> rect; SubrectangleQueries(vector<vector<int>>& rectangle) { rect= rectangle; } void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { for(int i=row1; i<=row2; ++i){ for(int j=col1; j<=col2; ++j){ rect[i][j]= newValue; } } } int getValue(int row, int col) { return rect[row][col]; } };
/** * @param {number[][]} rectangle */ var SubrectangleQueries = function(rectangle) { this.rectangle = rectangle; }; /** * @param {number} row1 * @param {number} col1 * @param {number} row2 * @param {number} col2 * @param {number} newValue * @return {void} */ SubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) { for(let i=row1; i<=row2; i++){ for(let j=col1; j<=col2; j++){ this.rectangle[i][j] = newValue; } } }; /** * @param {number} row * @param {number} col * @return {number} */ SubrectangleQueries.prototype.getValue = function(row, col) { return this.rectangle[row][col]; }; /** * Your SubrectangleQueries object will be instantiated and called as such: * var obj = new SubrectangleQueries(rectangle) * obj.updateSubrectangle(row1,col1,row2,col2,newValue) * var param_2 = obj.getValue(row,col) */
Subrectangle Queries
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. &nbsp; Example 1: Input: nums = [5,19,8,1] Output: 3 Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33. The following is one of the ways to reduce the sum by at least half: Pick the number 19 and reduce it to 9.5. Pick the number 9.5 and reduce it to 4.75. Pick the number 8 and reduce it to 4. The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 &gt;= 33/2 = 16.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations. Example 2: Input: nums = [3,8,20] Output: 3 Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31. The following is one of the ways to reduce the sum by at least half: Pick the number 20 and reduce it to 10. Pick the number 10 and reduce it to 5. Pick the number 3 and reduce it to 1.5. The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 &gt;= 31/2 = 16.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 107
class Solution: def halveArray(self, nums: List[int]) -> int: # Creating empty heap maxHeap = [] heapify(maxHeap) # Creates minHeap totalSum = 0 for i in nums: # Adding items to the heap using heappush # for maxHeap, function by multiplying them with -1 heappush(maxHeap, -1*i) totalSum += i requiredSum = totalSum / 2 minOps = 0 while totalSum > requiredSum: x = -1*heappop(maxHeap) # Got negative value make it positive x /= 2 totalSum -= x heappush(maxHeap, -1*x) minOps += 1 return minOps
class Solution { public int halveArray(int[] nums) { PriorityQueue<Double> q = new PriorityQueue<>(Collections.reverseOrder()); double sum=0; for(int i:nums){ sum+=(double)i; q.add((double)i); } int res=0; double req = sum; while(sum > req/2){ double curr = q.poll(); q.add(curr/2); res++; sum -= curr/2; } return res; } }
class Solution { public: int halveArray(vector<int>& nums) { priority_queue<double> pq; double totalSum = 0; double requiredSum = 0; for(auto x: nums){ totalSum += x; pq.push(x); } requiredSum = totalSum/2; int minOps = 0; while(totalSum > requiredSum){ double currtop = pq.top(); pq.pop(); currtop = currtop/2; totalSum -= currtop; pq.push(currtop); minOps++; } return minOps; } }
var halveArray = function(nums) { const n = nums.length; const maxHeap = new MaxPriorityQueue({ priority: x => x }); let startSum = 0; for (const num of nums) { maxHeap.enqueue(num); startSum += num; } let currSum = startSum; let numberOfOperations = 0; while (currSum > startSum / 2) { const biggestNum = maxHeap.dequeue().element; const halfNum = biggestNum / 2; numberOfOperations += 1; currSum -= halfNum; maxHeap.enqueue(halfNum); } return numberOfOperations; };
Minimum Operations to Halve Array Sum
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. &nbsp; Example 1: Input: root = [5,3,6,2,4,null,7], k = 9 Output: true Example 2: Input: root = [5,3,6,2,4,null,7], k = 28 Output: false &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. -104&nbsp;&lt;= Node.val &lt;= 104 root is guaranteed to be a valid binary search tree. -105&nbsp;&lt;= k &lt;= 105
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: def inorder(root,l): if root: inorder(root.left,l) l.append(root.val) inorder(root.right,l) l = [] inorder(root,l) left,right=0,len(l)-1 while left!=right: sum = l[left] + l[right] if sum > k : right -=1 elif sum <k: left +=1 else: return 1 return 0
class Solution { Set<Integer> set = new HashSet<>(); public boolean findTarget(TreeNode root, int k) { if(root == null){ return false; } if(set.contains(k-root.val)){ return true; } set.add(root.val); return findTarget(root.left,k) || findTarget(root.right,k); } }
class Solution { public: int countNodes(TreeNode *root) { if (root == NULL) { return 0; } return countNodes(root->left) + countNodes(root->right) + 1; } bool findTarget(TreeNode* root, int k) { int totalCount = countNodes(root); int count = 0; stack<TreeNode*> inorder; stack<TreeNode*> revInorder; TreeNode* currNode = root; while(currNode != NULL){ inorder.push(currNode); //Store all elements in left of tree currNode = currNode->left; } currNode = root; while(currNode != NULL){ revInorder.push(currNode); //Store all elements in right of tree currNode = currNode->right; } while(count < totalCount-1){ TreeNode* inordertop = inorder.top(); TreeNode* revinordertop = revInorder.top(); if(inordertop->val + revinordertop->val == k){ // If inordertop + revinordertop is equal to k, we have found a pair, so return true return true; } else if(inordertop->val + revinordertop->val > k){ //If they are greater than k, we have to found a value //which is just smaller than revinordertop, which means we have to find predecessor of revinordertop, as //we have to reduce the sum to make it equal to k TreeNode* currtop = revinordertop; count++; revInorder.pop(); if(currtop->left){ currtop = currtop->left; while(currtop){ revInorder.push(currtop); currtop = currtop->right; } } } else{ //If they are smaller than k, we have to found a value which is just larger than inordertop, which means //we have to find successor of revinordertop, as we have to increase the sum to make it equal to k TreeNode* currtop = inordertop; count++; inorder.pop(); if(currtop->right){ currtop = currtop->right; while(currtop){ inorder.push(currtop); currtop = currtop->left; } } } } return false; } };
var findTarget = function(root, k) { const set = new Set(); const search = (root, k) => { if (!root) return false; if (set.has(k - root.val)) return true; set.add(root.val); return search(root.left, k) || search(root.right, k); } return search(root,k); };
Two Sum IV - Input is a BST
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... &nbsp; Example 1: Input: columnNumber = 1 Output: "A" Example 2: Input: columnNumber = 28 Output: "AB" Example 3: Input: columnNumber = 701 Output: "ZY" &nbsp; Constraints: 1 &lt;= columnNumber &lt;= 231 - 1
class Solution: def convertToTitle(self, num: int) -> str: # We make this lookup list, having A-Z in ascending order alpha = [chr(x) for x in range(ord("A"), ord("Z")+1)] # range(65, 90+1) -> 91-65 = 26 res = "" while num > 0: res += alpha[(num-1)%26] # since 0 indexed list, num-1 % 26 gives the index of ch in alpha num = (num-1) // 26 return res[::-1]
class Solution { public String convertToTitle(int columnNumber) { String ans = ""; while(columnNumber > 0){ columnNumber--; ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans; columnNumber /= 26; } return ans; } }
class Solution { public: string convertToTitle(int columnNumber) { string s = ""; while(columnNumber){ char c = (columnNumber-1)%26+65; s = c+s; columnNumber = (columnNumber-1)/26; } return s; } };
/** * @param {number} columnNumber * @return {string} */ var convertToTitle = function(columnNumber) { let ans = ""; while(columnNumber >0){ let n = (--columnNumber) % 26; columnNumber = Math.floor(columnNumber/ 26); // console.log(String.fromCharCode(65+n),) ans+=String.fromCharCode(65 + n); } ans = ans.split("").reverse().join("") return ans };
Excel Sheet Column Title
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces. &nbsp; Example 1: Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] Output: 2 Example 2: Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] Output: 3 &nbsp; Constraints: 1 &lt;= n &lt;= 200 n == isConnected.length n == isConnected[i].length isConnected[i][j] is 1 or 0. isConnected[i][i] == 1 isConnected[i][j] == isConnected[j][i]
class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: graph = defaultdict(list) for i,x in enumerate(isConnected): for j,n in enumerate(x): if j!=i and n == 1: graph[i].append(j) visit = set() def dfs(node): if node not in graph: return for neighbor in graph[node]: if neighbor not in visit: visit.add(neighbor) dfs(neighbor) count = 0 for i in range(len(isConnected)): if i in visit: continue count+=1 dfs(i) return count
class Solution { public int findCircleNum(int[][] isConnected) { int size = isConnected.length; boolean[] isCheck = new boolean[size+1]; int ans = 0; for(int i=1; i<=size; i++){ if(!isCheck[i]){ // Doing BFS if it's false in isCheck[] Queue<Integer> q = new LinkedList<>(); q.add(i); ans++; // No. of queue = No. of Graphs while(!q.isEmpty()){ int temp = q.remove(); isCheck[temp] = true; for(int j=0; j<size; j++){ if(isConnected[temp-1][j]==1 && !isCheck[j+1]) q.add(j+1); } } } } return ans; } }
class Solution { private: void dfs(int node,vector<vector<int>> &graph,int n,vector<bool> &vis){ vis[node] = true; for(int j = 0; j < graph[node].size(); j++){ if(graph[node][j] == 1 and !vis[j]){ dfs(j,graph,n,vis); } } } public: int findCircleNum(vector<vector<int>>& isConnected) { int n = isConnected.size(); vector<bool> vis(n,false); int ans = 0; for(int i = 0; i < n; i++){ if(!vis[i]){ ans++; dfs(i,isConnected,n,vis); } } return ans; } };
function DisjointSet (size) { this.root = [] this.rank = [] this.size = size for (let i = 0; i < size; i++) { this.root.push(i) this.rank.push(1) } this.find = function(x) { if (x === this.root[x]) { return x } this.root[x] = this.find(this.root[x]) return this.root[x] } this.union = function(x, y) { const rootX = this.find(x) const rootY = this.find(y) if (rootX === rootY) return this.size-- if (this.rank[rootX] > this.rank[rootY]) { this.root[rootY] = this.root[rootX] } else if (this.rank[rootX] < this.rank[rootY]) { this.root[rootX] = this.root[rootY] } else { this.root[rootY] = this.root[rootX] this.rank[rootX]++ } } } /** * @param {number[][]} isConnected * @return {number} */ var findCircleNum = function(isConnected) { const n = isConnected.length const disjointSet = new DisjointSet(isConnected.length) for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (isConnected[i][j]) { disjointSet.union(i, j) } } } return disjointSet.size };
Number of Provinces
You are given an integer array bloomDay, an integer m and an integer k. You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1. &nbsp; Example 1: Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 Output: 3 Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: [x, _, _, _, _] // we can only make one bouquet. After day 2: [x, _, _, _, x] // we can only make two bouquets. After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3. Example 2: Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 Output: -1 Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. Example 3: Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 Output: 12 Explanation: We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: [x, x, x, x, _, x, x] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: [x, x, x, x, x, x, x] It is obvious that we can make two bouquets in different ways. &nbsp; Constraints: bloomDay.length == n 1 &lt;= n &lt;= 105 1 &lt;= bloomDay[i] &lt;= 109 1 &lt;= m &lt;= 106 1 &lt;= k &lt;= n
class Solution: def minDays(self, listOfFlowerBloomDays: List[int], targetNumberOfBouquets: int, flowersPerBouquet: int) -> int: def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking): currentListOfAdjacentBloomedFlowers = [] numberOfBouquetsWeCanMakeOnThisDay = 0 for dayThatFlowerBlooms in listOfFlowerBloomDays: # check if the flower has bloomed on this day if dayThatFlowerBlooms <= dayThatWeAreChecking: # add to the list an adjacent bloomed flowers, I use 'x' because the description uses an 'x' currentListOfAdjacentBloomedFlowers.append('x') else: # we've hit a day where we don't have a bloomed flower, so the list of adjacent bloomed flowers has to be reset # BUT FIRST figure out how many bouquets we can make with this list of adjacent bloomed flowers numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet # RESET list of adjacent bloomed flowers cause we're on a day where the a flower has not bloomed yet currentListOfAdjacentBloomedFlowers = [] # we've gone through the entire listOfFlowerBloomDays list and need to check if the "residual" current list # of adjacent bloomed flowers can make a bouquet ... so handle it here numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet return numberOfBouquetsWeCanMakeOnThisDay # if the TOTAL amount of flowers we need doesn't match the number of possible flowers we can grow, # then the given inputs are impossible for making enough bouquets (we don't have enough flowers) totalNumberOfFlowersNeeded = targetNumberOfBouquets*flowersPerBouquet numberOfFlowersWeCanGrow = len(listOfFlowerBloomDays) if numberOfFlowersWeCanGrow < totalNumberOfFlowersNeeded: return -1 # no need to go past the day of the flower with the longest bloom date leftDay = 0 rightDay = max(listOfFlowerBloomDays) while leftDay < rightDay: # currentDay is functioning as the "mid" of a binary search currentDay = leftDay + (rightDay-leftDay)//2 # as in most binary searches, we check if the mid (which I'm calling 'currentDay') satisfies the constraint # that is, if we can make the target amount of bouquets on this day if numberOfBouquetsWeCanMakeOnThisDay(currentDay) < targetNumberOfBouquets: # womp womp, we can't make enough bouquets on this day, so set up for next iteration # the "correct day" is on the right side, so we get rid of all the "incorrect days" on the left side # by updating the left to the currentDay+1 leftDay = currentDay+1 else: # yay, we can make enough bouquets on this day, but we don't know if this is the "minimum day" # we discard the right side to keep searching rightDay = currentDay # leftDay >= rightDay, so we've found the "minimum day" return leftDay
class Solution { public int minDays(int[] bloomDay, int m, int k) { if(m*k > bloomDay.length) return -1; int low = Integer.MAX_VALUE, high = 0; for(int i:bloomDay){ low = Math.min(low,i); high = Math.max(high,i); } while(low<=high){ int mid = low + (high-low)/2; if(isPossible(bloomDay,mid,m,k)) high = mid - 1; else low = mid + 1; } return low; } private boolean isPossible(int[] bloomDay,int maxDays,int m,int k){ for(int i=0;i<bloomDay.length;i++){ int count = k; while(i<bloomDay.length && bloomDay[i]<=maxDays){ count--; if(count==0){ m--; break; } i++; } if(m==0) return true; } return false; } }
class Solution { public: bool check(int mid,vector<int> &v, int m, int k) { int n=v.size(); int cnt=0;// taking cnt for the no of k adjacent bouquets possible for(int i=0;i<v.size();i++) { if(v[i]<=mid) { int c=0; while(i<n and v[i]<=mid) { i++; c++;// c->checking for adjacent count } cnt+=c/k; } } if(cnt>=m) return true; return false; } int minDays(vector<int>& bloomDay, int m, int k) { int s=*min_element(bloomDay.begin(),bloomDay.end()); int e=*max_element(bloomDay.begin(),bloomDay.end()); int ans=e; if((m*k)>bloomDay.size()) return -1; while(s<=e) { int mid=s+(e-s)/2; if(check(mid,bloomDay,m,k)) { ans=mid; e=mid-1; } else s=mid+1; } return ans; } };
var minDays = function(bloomDay, m, k) { if (m * k > bloomDay.length) { return -1; } let left = 0; let right = 0; for (const day of bloomDay) { left = Math.min(day, left); right = Math.max(day, right); } let ans = right; while (left < right) { const day = Math.floor((left + right) / 2); let count = 0; let current = 0; for (let j = 0; j < bloomDay.length; j++) { if (bloomDay[j] <= day) { current++; } else { current = 0; } if (current === k) { count++; current = 0; } } if (count === m) { ans = Math.min(ans, day); } if (count < m) { left = day + 1; } else { right = day; } } return ans; };
Minimum Number of Days to Make m Bouquets
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 &lt;= i &lt; n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game. &nbsp; Example 1: Input: n = 5, k = 2 Output: 3 Explanation: Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. Example 2: Input: n = 6, k = 5 Output: 1 Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. &nbsp; Constraints: 1 &lt;= k &lt;= n &lt;= 500 &nbsp; Follow up: Could you solve this problem in linear time with constant space?
class Solution: def findTheWinner(self, n: int, k: int) -> int: ls=list(range(1,n+1)) while len(ls)>1: i=(k-1)%len(ls) ls.pop(i) ls=ls[i:]+ls[:i] return ls[0]
class Solution { public int findTheWinner(int n, int k) { // Initialisation of the LinkedList LinkedList<Integer> participants = new LinkedList<>(); for (int i = 1; i <= n; i++) { participants.add(i); } int lastKilled = 0; // Run the game for (int i = 0; i < n; i++) { for (int j = 0; j < k-1; j++) { participants.add(participants.poll()); } lastKilled = participants.poll(); } // Return the last one killed return lastKilled; } }
class Solution { public: int findTheWinner(int n, int k) { vector<int>temp; for(int i=1;i<=n;i++) temp.push_back(i); int i=0; while(temp.size()>1){ int t=temp.size(); i=(i+k-1)%t; temp.erase(temp.begin()+i); } return *temp.begin(); } };
/** * @param {number} n * @param {number} k * @return {number} */ var findTheWinner = function(n, k) { let friends = Array.from({length: n}, (_, index) => index + 1) let start = 0; while(friends.length != 1){ start += (k - 1) start = start % friends.length friends.splice(start,1) } return friends[0] };
Find the Winner of the Circular Game
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.&nbsp; Return that maximum distance to the closest person. &nbsp; Example 1: Input: seats = [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. Example 2: Input: seats = [1,0,0,0] Output: 3 Explanation: If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. Example 3: Input: seats = [0,1] Output: 1 &nbsp; Constraints: 2 &lt;= seats.length &lt;= 2 * 104 seats[i]&nbsp;is 0 or&nbsp;1. At least one seat is empty. At least one seat is occupied.
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: # strategy is greedy solution: # calculate local maximum for each interval: (b-a)//2 # then take max of local maximums # the solution is O(n) # I find this solution clear, but uses 5 passes # get all the occupied seat nums seat_nums = [ix for ix, val in enumerate(seats) if val == 1] # check the ends left_max, right_max = min(seat_nums), len(seats)-max(seat_nums)-1 # calculate max distance for each gap dists = [(y-x)//2 for x, y in zip(seat_nums, seat_nums[1:])] # take max of sitting on either end + each gap return max([left_max, right_max, *dists])
class Solution { public int maxDistToClosest(int[] seats) { int size = seats.length; int max = 0; int start = -1; int end = -1; for(int i = 0; i<size; i++){ if(seats[i] != 0){ start = end; // update start to end when we have a filled seat. end = i; // update end with i pointer when we have a filled seat. if(start == -1) max = i; // for special case when there is only '1' in the array else max = Math.max((end-start)/2,max); // updating max. } } // Handeling speical cases before returning max. // 1) last element is 0 as we wont be updating max for that in above loop. // 2) when there only single '1' in the array, we need to make sure whether right half is bigger than the left half. if(seats[size - 1] == 0 || start == -1) return Math.max(max, (size - 1 - end)); return max; } }
class Solution { public: int maxDistToClosest(vector<int>& seats) { vector<int> d; int cnt = -1, ans = 0; for(int i=0; i<seats.size(); i++) { cnt++; if(seats[i]) d.push_back(cnt), cnt = 0; } d.push_back(cnt); for(int i=0; i<d.size(); i++) { if(i > 0 && i < d.size() - 1) d[i] /= 2; ans = max(ans, d[i]); } return ans; } };
/** * @param {number[]} seats * @return {number} */ var maxDistToClosest = function(seats) { let arr = seats.join('').split('1'); for(let i = 0; i < arr.length;i++){ if(arr[i] == '') arr[i] = 0; else{ let middle = true; if(i == 0 || i == arr.length-1){ arr[i] = arr[i].length; }else { arr[i] = Math.ceil(arr[i].length/2); } } } return arr.sort((a,b) => (a >= b)?-1:1)[0] };
Maximize Distance to Closest Person
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. &nbsp; Example 1: Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Example 2: Input: s = "God Ding" Output: "doG gniD" &nbsp; Constraints: 1 &lt;= s.length &lt;= 5 * 104 s contains printable ASCII characters. s does not contain any leading or trailing spaces. There is at least one word in s. All the words in s are separated by a single space.
class Solution: def reverseWords(self, s: str) -> str: s = s + ' ' l = len(s) t = '' w = '' for i in range(l): if s[i]!=' ': t = s[i] + t # t stores the word in reverse order else: # w stores the reversed word in the same order w = w + t + ' ' # could have used .join() function and not write .strip() t = "" # value of t is null so that it won't affect upcoming words return w.strip() # removes extra whitespace
class Solution { public String reverseWords(String s) { if(s == null || s.trim().equals("")){ return null; } String [] words = s.split(" "); StringBuilder resultBuilder = new StringBuilder(); for(String word: words){ for(int i = word.length() - 1; i>=0; i --){ resultBuilder.append(word.charAt(i)); } resultBuilder.append(" "); } return resultBuilder.toString().trim(); } }
Time: O(n+n) Space: O(1) class Solution { public: string reverseWords(string s) { int i,j; for( i=0,j=0;i<size(s);i++){ if(s[i]==' '){ reverse(begin(s)+j,begin(s)+i); j=i+1; } } reverse(begin(s)+j,end(s)); return s; } };
var reverseWords = function(s) { // make array of the words from s let words = s.split(" "); for (let i in words) { // replace words[i] with words[i] but reversed words.splice(i, 1, words[i].split("").reverse().join("")) } return words.join(" "); };
Reverse Words in a String III
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. &nbsp; Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -&gt; Down -&gt; Down 2. Down -&gt; Down -&gt; Right 3. Down -&gt; Right -&gt; Down &nbsp; Constraints: 1 &lt;= m, n &lt;= 100
class Solution: def uniquePaths(self, m: int, n: int) -> int: @cache def dfs(i ,j): if i == 0 and j == 0: return 1 elif i < 0 or j < 0: return 0 return dfs(i-1, j) + dfs(i, j-1) return dfs(m-1, n-1)
class Solution { public int uniquePaths(int m, int n) { int[][] dp = new int[m][n]; for(int i = 0; i < m; i ++) { for(int j = 0; j < n; j ++) { dp[i][j] = -1; } } return helper(m, 0, n, 0, dp); } private int helper(int m, int i, int n, int j, int[][] dp) { if(i == m || j == n) { return 0; } if(i == m-1 && j == n-1) { dp[i][j] = 1; } if(dp[i][j] == -1) { dp[i][j] = helper(m, i+1, n, j, dp) + helper(m, i, n, j+1, dp); } return dp[i][j]; } }
#define vi vector<int> #define vvi vector<vi> class Solution { public: int countPath(vvi& dp,int r,int c, int m , int n){ if(m==r-1 || n==c-1) return 1; if(dp[m][n]!=-1) return dp[m][n]; return dp[m][n] = countPath(dp,r,c,m+1,n) + countPath(dp,r,c,m,n+1); } int uniquePaths(int m, int n) { vvi dp(m,vi(n,-1)); return countPath(dp,m,n,0,0); } };
var uniquePaths = function(m, n) { let count = Array(m) for(let i=0; i<m; i++) count[i] = Array(n) for(let i=0; i<m; i++){ for(let j=0; j<n; j++){ if(i == 0 || j == 0) count[i][j] = 1 else count[i][j] = count[i][j-1] + count[i-1][j] } } return count[m-1][n-1] };
Unique Paths
Given an integer array nums and an integer k, return the number of pairs (i, j) where i &lt; j such that |nums[i] - nums[j]| == k. The value of |x| is defined as: x if x &gt;= 0. -x if x &lt; 0. &nbsp; Example 1: Input: nums = [1,2,2,1], k = 1 Output: 4 Explanation: The pairs with an absolute difference of 1 are: - [1,2,2,1] - [1,2,2,1] - [1,2,2,1] - [1,2,2,1] Example 2: Input: nums = [1,3], k = 3 Output: 0 Explanation: There are no pairs with an absolute difference of 3. Example 3: Input: nums = [3,2,1,5,4], k = 2 Output: 3 Explanation: The pairs with an absolute difference of 2 are: - [3,2,1,5,4] - [3,2,1,5,4] - [3,2,1,5,4] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 200 1 &lt;= nums[i] &lt;= 100 1 &lt;= k &lt;= 99
class Solution: def countKDifference(self, nums: List[int], k: int) -> int: seen = defaultdict(int) counter = 0 for num in nums: tmp, tmp2 = num - k, num + k if tmp in seen: counter += seen[tmp] if tmp2 in seen: counter += seen[tmp2] seen[num] += 1 return counter
class Solution { public int countKDifference(int[] nums, int k) { Map<Integer,Integer> map = new HashMap<>(); int res = 0; for(int i = 0;i< nums.length;i++){ if(map.containsKey(nums[i]-k)){ res+= map.get(nums[i]-k); } if(map.containsKey(nums[i]+k)){ res+= map.get(nums[i]+k); } map.put(nums[i],map.getOrDefault(nums[i],0)+1); } return res; } }
class Solution { public: int countKDifference(vector<int>& nums, int k) { unordered_map<int, int> freq; int res = 0; for (auto num : nums) { res += freq[num+k] + freq[num-k]; freq[num]++; } return res; } };
var countKDifference = function(nums, k) { nums = nums.sort((b,a) => b- a) let count = 0; for(let i = 0; i< nums.length; i++) { for(let j = i + 1; j< nums.length; j++) { if(Math.abs(nums[i] - nums[j]) == k) { count++ } } } return count ; };
Count Number of Pairs With Absolute Difference K
You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. Return the number of pairs of different nodes that are unreachable from each other. &nbsp; Example 1: Input: n = 3, edges = [[0,1],[0,2],[1,2]] Output: 0 Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0. Example 2: Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] Output: 14 Explanation: There are 14 pairs of nodes that are unreachable from each other: [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]]. Therefore, we return 14. &nbsp; Constraints: 1 &lt;= n &lt;= 105 0 &lt;= edges.length &lt;= 2 * 105 edges[i].length == 2 0 &lt;= ai, bi &lt; n ai != bi There are no repeated edges.
''' * Make groups of nodes which are connected eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] 0 ---- 2 1 --- 6 3 | | | | 5 ---- 4 groups will be {0: 4, 1: 2, 3: 1}, i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3 * Now, we have [4, 2, 1] as no of nodes in each group, we have to multiply each of no. with remaining ans = (4 * 2 + 4 * 1) + (2 * 1) but calculating ans this way will give TLE. * if we notice, (4 * 2 + 4 * 1) + (2 * 1), we can combine, equation like this, 4 * 2 + (4 + 2) * 1, using this, we can reduce complexity. so, if we have count of groups array as [a, b, c, d], ans will be, ans = a * b + (a + b) * c + (a + b + c) * d * will use, union for generating groups. * ps, you can modify UnionFind class as per your need. Have implemented full union-find for beginners. ''' class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.rank = [1] * size def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: self.root[rootY] = rootX elif self.rank[rootX] < self.rank[rootY]: self.root[rootX] = rootY else: self.root[rootY] = rootX self.rank[rootX] += 1 class Solution: def countPairs(self, n: int, edges: List[List[int]]) -> int: dsu = UnionFind(n) for u, v in edges: dsu.union(u, v) C = Counter([dsu.find(i) for i in range(n)]) groupCounts = list(C.values()) ans = 0 firstGroupCount = groupCounts[0] for i in range(1, len(groupCounts)): ans += firstGroupCount * groupCounts[i] firstGroupCount += groupCounts[i] return ans
class Solution { public long countPairs(int n, int[][] edges) { //Building Graph ArrayList < ArrayList < Integer >> graph = new ArrayList < > (); for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ()); for (int arr[]: edges) { graph.get(arr[0]).add(arr[1]); graph.get(arr[1]).add(arr[0]); } boolean visited[] = new boolean[n]; long res = 0; int prev = 0; int count[] = { 0 }; for (int i = 0; i < graph.size(); i++) { // Running for loop on all connected components of graph if (visited[i] == true) continue; // if the node is alredy reached by any of other vertex then we don't need to terverse it again dfs(graph, i, visited, count); long a = n - count[0]; // (total - current count) long b = count[0] - prev; // (current count - prev ) prev = count[0]; // Now Store count to prev res += (a * b); } return res; } void dfs(ArrayList < ArrayList < Integer >> graph, int v, boolean vis[], int count[]) { vis[v] = true; count[0]++; //for counting connected nodes for (int child: graph.get(v)) { if (!vis[child]) { dfs(graph, child, vis, count); } } } }
class Solution { public: typedef long long ll; void dfs(int node, unordered_map<int,vector<int>>& m, ll& cnt, vector<int>& vis){ vis[node] = 1; cnt++; for(auto& i: m[node]){ if(vis[i]==0) dfs(i,m,cnt,vis); } } long long countPairs(int n, vector<vector<int>>& edges) { unordered_map<int,vector<int>> m; // making adjacency list for(int i=0;i<edges.size();i++){ m[edges[i][0]].push_back(edges[i][1]); m[edges[i][1]].push_back(edges[i][0]); } ll ans = ((ll)n*(n-1))/2; vector<int> vis(n,0); for(int i=0;i<n;i++){ if(vis[i]==0){ // as node is not visited, we find the no. of nodes in current component. ll cnt = 0; dfs(i,m,cnt,vis); ans -= (cnt*(cnt-1))/2; } } return ans; } };
var countPairs = function(n, edges) { const adj = []; for (let i = 0; i < n; i++) { adj.push([]); } for (let [from, to] of edges) { adj[from].push(to); adj[to].push(from); } const visited = new Set(); function dfs(from) { visited.add(from); let count = 1; for (const to of adj[from]) { if (!visited.has(to)) { count += dfs(to); } } return count; } const groups = []; for (let i = 0; i < n; i++) { if (!visited.has(i)) { const count = dfs(i); groups.push(count); } } let ans = 0; for (let i = 0; i < groups.length - 1; i++) { for (let j = i + 1; j < groups.length; j++) { ans += groups[i] * groups[j]; } } return ans; };
Count Unreachable Pairs of Nodes in an Undirected Graph
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make (&nbsp;a OR b == c&nbsp;). (bitwise OR operation). Flip operation&nbsp;consists of change&nbsp;any&nbsp;single bit 1 to 0 or change the bit 0 to 1&nbsp;in their binary representation. &nbsp; Example 1: Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) Example 2: Input: a = 4, b = 2, c = 7 Output: 1 Example 3: Input: a = 1, b = 2, c = 3 Output: 0 &nbsp; Constraints: 1 &lt;= a &lt;= 10^9 1 &lt;= b&nbsp;&lt;= 10^9 1 &lt;= c&nbsp;&lt;= 10^9
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: res = 0 for i in range(32): if (a & 1) | (b & 1) != (c & 1): if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1 res += 1 else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1 res += (a & 1) + (b & 1) a, b, c = a>>1, b>>1, c>>1 # right-shift by 1 return res # Time: O(1) # Space: O(1)
class Solution { public int minFlips(int a, int b, int c) { int j=-1; int x=a|b; int count=0; while(c!=0 || x!=0){ j++; int aa=x%2; int bb=c%2; if(aa==0 && bb==1)count++; else if(aa==1 && bb==0) count+=funcount(j,a,b); x=x>>1; c=c>>1; } return count; } public static int funcount(int shift,int a,int b){ int cc=0; int mask=1<<shift; int b1=a&mask; int b2=b&mask; if(b1!=0)cc++; if(b2!=0)cc++; return cc; } }```
class Solution { public: int minFlips(int a, int b, int c) { int changeBits = 0; for(int i=0; i<32; i++){ int lastBitA = 0; int lastBitB = 0; int lastBitC = 0; if(((a >> i) & 1) == 1){ lastBitA = 1; } if (((b >> i) & 1) == 1){ lastBitB = 1; } if (((c >> i) & 1) == 1){ lastBitC = 1; } if(lastBitC == 1){ if(lastBitA == 0 & lastBitB == 0){ changeBits++; } } else{ if(lastBitA == 1 || lastBitB == 1){ if(lastBitA == 1){ changeBits++; } if(lastBitB == 1){ changeBits++; } } } } return changeBits; } };
var minFlips = function(a, b, c) { let ans = 0; for(let bit = 0; bit < 32; bit++) { let bit_a = (a >> bit)&1, bit_b = (b >> bit)&1, bit_c = (c >> bit)&1; if(bit_c !== (bit_a | bit_b)) { if(bit_c === 1) { //a b will be 0 0 ans += 1; } else { //a b -> 0 1 -> 1 0 -> 1 1 ans += (bit_a + bit_b === 2 ? 2 : 1); } } } return ans; };
Minimum Flips to Make a OR b Equal to c
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where both A and B are balanced strings, or It can be written as [C], where C is a balanced string. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced. &nbsp; Example 1: Input: s = "][][" Output: 1 Explanation: You can make the string balanced by swapping index 0 with index 3. The resulting string is "[[]]". Example 2: Input: s = "]]][[[" Output: 2 Explanation: You can do the following to make the string balanced: - Swap index 0 with index 4. s = "[]][][". - Swap index 1 with index 5. s = "[[][]]". The resulting string is "[[][]]". Example 3: Input: s = "[]" Output: 0 Explanation: The string is already balanced. &nbsp; Constraints: n == s.length 2 &lt;= n &lt;= 106 n is even. s[i] is either '[' or ']'. The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
class Solution: def minSwaps(self, s: str) -> int: res, bal = 0, 0 for ch in s: bal += 1 if ch == '[' else -1 if bal == -1: res += 1 bal = 1 return res
class Solution { public int minSwaps(String s) { // remove the balanced part from the given string Stack<Character> stack = new Stack<>(); for(char ch : s.toCharArray()) { if(ch == '[') stack.push(ch); else { if(!stack.isEmpty() && stack.peek() == '[') stack.pop(); else stack.push(ch); } } int unb = stack.size()/2; // # of open or close bracket return (unb+1)/2; } }
class Solution { public: int minSwaps(string s) { int ans=0; stack<char> stack; for(int i=0;i<s.length();i++){ if(s[i]=='['){ stack.push(s[i]); } if(s[i]==']' && stack.size()!=0 && stack.top()=='['){ stack.pop(); } } ans=stack.size(); if(ans%2==0) return ans/2; else return (ans+1)/2; } };
/** * @param {string} s * @return {number} */ var minSwaps = function(s) { let stk = [] for(let c of s){ if(stk && c == ']') stk.pop() else if(c == '[') stk.push(c) } return (stk.length) / 2 };
Minimum Number of Swaps to Make the String Balanced
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted. &nbsp; Example 1: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. &nbsp; Constraints: 1 &lt;= n &lt;= 100 edges.length == n - 1 edges[i].length == 2 1 &lt;= ai, bi &lt;= n 1 &lt;= t &lt;= 50 1 &lt;= target &lt;= n
class Solution: def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float: adj = [[] for i in range(n)] for u,v in edges: adj[u-1].append(v-1) adj[v-1].append(u-1) def f(u,p,tt): if(u==target-1): return tt==0 or len(adj[u])==(p>=0) if(tt==0): return 0 res = 0 for v in adj[u]: if(p==v): continue res = max(res,(1/(len(adj[u])-(p!=-1)))*f(v,u,tt-1)) return res return f(0,-1,t)
class Solution { public double frogPosition(int n, int[][] edges, int t, int target) { List<List<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++) graph.add(new ArrayList<>()); for(int i=0;i<edges.length;i++) { graph.get(edges[i][0]).add(edges[i][1]); graph.get(edges[i][1]).add(edges[i][0]); } boolean[] vis=new boolean[n+1]; return Sol(graph,1, t, target,vis); } public double Sol(List<List<Integer>> graph,int ver,int t,int tar,boolean[] vis){ int count=0; for(Integer child:graph.get(ver)){ if(!vis[child]) count++; } vis[ver]=true; if(t<0) return 0; if(ver==tar){ if(count==0 || t==0) return 1.0; } if(graph.get(ver).size()==0) return 0; double ans=0.0; for(Integer child:graph.get(ver)){ // System.out.println(child); if(!vis[child]) ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis); } // System.out.println(ans); vis[ver]=false; return ans; } }
class Solution { public: double frogPosition(int n, vector<vector<int>>& edges, int t, int target) { unordered_map<int, vector<int>> adjList; for(const auto& edge : edges) { adjList[edge[0]].push_back(edge[1]); adjList[edge[1]].push_back(edge[0]); } // BFS way queue<pair<int, double>> Q; Q.push({1, 1.0}); int time = 0; vector<int> visited(n+1, false); while(not Q.empty()) { int size = Q.size(); if (time > t) break; while(size--) { auto pp = Q.front(); Q.pop(); int node = pp.first; double prob = pp.second; visited[node] = true; // Count the unvisited nbr int nbrCount = 0; for(auto& nbr : adjList[node]) { if (not visited[nbr]) nbrCount++; } if (node == target) { if (time == t) return prob; if (time < t) { // Check if any unvisited ? if yes, then frog would jump there and not be able to jump back here if (nbrCount > 0) return 0.0; // else return the same prob return prob; } } for(auto& nbr : adjList[node]) { if (not visited[nbr]) { // update the prob as it will be divided by number of nbr Q.push({nbr, (prob * (1.0/nbrCount))}); } } } time++; } return 0.0; } };
/** * @param {number} n * @param {number[][]} edges * @param {number} t * @param {number} target * @return {number} */ function dfs(n, map, t, target, visited, prop) { // edge case1: if run out of steps, cannot find target if(t === 0 && n !== target) return 0; // edge case2: if run out of steps, but found target if(t === 0 && n === target) return prop; visited.add(n); // get unvisited children/neighbors const validChildren = []; (map[n] ?? []).forEach((child) => { if(!visited.has(child)) validChildren.push(child); }) // edge case3, if still more steps to use, but no more children to move, // if already at the targeted node, should just return if(n === target && t > 0 && !validChildren.length) return prop; // edge case4, if still more steps to use and no more children to move, // but current node is not target node, cannot find target, return 0 if(n !== target && t > 0 && !validChildren.length) return 0; // go to next valid child/neighbor for(let i = 0; i < validChildren.length; i ++) { if(visited.has(validChildren[i])) continue; let result = dfs(validChildren[i], map, t - 1, target, visited, prop * (1 / validChildren.length)) if(result !== 0) return result; } return 0; } var frogPosition = function(n, edges, t, target) { const map = new Array(n + 1); // make bidirectional edge map edges.forEach(item => { if(!map[item[0]]) map[item[0]] = []; if(!map[item[1]]) map[item[1]] = []; map[item[0]].push(item[1]); map[item[1]].push(item[0]); }); return dfs(1, map, t, target, new Set(), 1); };
Frog Position After T Seconds
There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point. For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n. &nbsp; Example 1: Input: obstacles = [0,1,2,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). Example 2: Input: obstacles = [0,1,1,3,3,0] Output: 0 Explanation: There are no obstacles on lane 2. No side jumps are required. Example 3: Input: obstacles = [0,2,1,0,3,0] Output: 2 Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps. &nbsp; Constraints: obstacles.length == n + 1 1 &lt;= n &lt;= 5 * 105 0 &lt;= obstacles[i] &lt;= 3 obstacles[0] == obstacles[n] == 0
class Solution: def minSideJumps(self, obstacles: List[int]) -> int: """ # TLE Recursion DP @cache def dp(curr_lane = 2, point = 0): if point == len(obstacles)-1: return 0 if obstacles[point+1] == curr_lane: return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1 return dp(curr_lane, point+1) return dp() """ n = len(obstacles) dp = [[0, 0, 0, 0] for _ in range(n)] for point in range(n-2, -1, -1): for curr_lane in range(4): if obstacles[point+1] == curr_lane: dp[point][curr_lane] = min(dp[point+1][lane] for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1 else: dp[point][curr_lane] = dp[point+1][curr_lane] return dp[0][2]
class Solution { public int minSideJumps(int[] obstacles) { int[] dp = new int[]{1, 0, 1}; for(int i=1; i<obstacles.length; i++){ switch(obstacles[i]){ case 0: dp[0] = min(dp[0], dp[1]+1, dp[2]+1); dp[1] = min(dp[0]+1, dp[1], dp[2]+1); dp[2] = min(dp[0]+1, dp[1]+1, dp[2]); break; case 1: dp[0] = Integer.MAX_VALUE; dp[1] = min(dp[1], dp[2]+1); dp[2] = min(dp[1]+1, dp[2]); break; case 2: dp[0] = min(dp[0], dp[2]+1); dp[1] = Integer.MAX_VALUE; dp[2] = min(dp[0]+1, dp[2]); break; case 3: dp[0] = min(dp[0], dp[1]+1); dp[1] = min(dp[0]+1, dp[1]); dp[2] = Integer.MAX_VALUE; break; } } return min(dp[0], dp[1], dp[2]); } int min(int... vals){ int min = Integer.MAX_VALUE; for(int val: vals){ if(val>=0) min = Math.min(min, val); } return min; } }
class Solution { public: int func(int i,int l,vector<int>&obstacles,vector<vector<int>>&dp){ if(i==obstacles.size()-2){ if(obstacles[i+1]==l)return 1; return 0; } if(dp[i][l]!=-1)return dp[i][l]; if(obstacles[i+1]!=l){ return dp[i][l] = func(i+1,l,obstacles,dp); } int b=INT_MAX; for(int j=1;j<=3;j++){ if(l==j)continue; if(obstacles[i]==j)continue; b=min(b,1+func(i,j,obstacles,dp)); } return dp[i][l] = b; } int minSideJumps(vector<int>& obstacles) { int n=obstacles.size(); vector<vector<int>>dp(n,vector<int>(4,-1)); return func(0,2,obstacles,dp); } };
var minSideJumps = function(obstacles) { // create a dp cache for tabulation const dp = [...obstacles].map(() => new Array(4).fill(Infinity)); // initialize the first positions dp[0][2] = 0; for (const lane of [1,3]) { if (obstacles[0] === lane) continue; dp[0][lane] = 1; } // for every index we will do the following for (let i = 1; i < obstacles.length; i++) { // first we find the best way to get to this position from the previous index for (let nextLane = 1; nextLane <= 3; nextLane++) { if (obstacles[i] === nextLane) continue; dp[i][nextLane] = dp[i - 1][nextLane] } // then we find the best way to get to this position from the current index; for (let nextLane = 1; nextLane <= 3; nextLane++) { for (let prevLane = 1; prevLane <= 3; prevLane++) { if (prevLane === nextLane) continue; if (obstacles[i] === nextLane) continue; dp[i][nextLane] = Math.min(dp[i][nextLane], dp[i][prevLane] + 1) } } } // return the best result after reaching the end return Math.min(...dp[dp.length - 1]) };
Minimum Sideway Jumps
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes. &nbsp; Example 1: Input: boxes = "110" Output: [1,1,3] Explanation: The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. Example 2: Input: boxes = "001011" Output: [11,8,5,4,3,4] &nbsp; Constraints: n == boxes.length 1 &lt;= n &lt;= 2000 boxes[i] is either '0' or '1'.
class Solution: def minOperations(self, boxes: str) -> List[int]: ans = [0]*len(boxes) leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes) for i in range(1, n): if boxes[i-1] == '1': leftCount += 1 leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left ans[i] = leftCost for i in range(n-2, -1, -1): if boxes[i+1] == '1': rightCount += 1 rightCost += rightCount ans[i] += rightCost return ans
class Solution{ public int[] minOperations(String boxes){ int n = boxes.length(); int[] ans = new int[n]; for(int i=0; i<n; i++){ int t = 0; for(int j=0; j<n; j++){ char c = boxes.charAt(j); if(c=='1') t += Math.abs(i-j); } ans[i] = t; } return ans; } }
class Solution { public: vector<int> minOperations(string boxes) { int n = boxes.size(); vector<int> ans; for(int i = 0; i < n; i++) { int res = 0; for(int j = 0; j < n; j++) { if(boxes[j] == '1') { res += abs(i-j); } } ans.push_back(res); } return ans; } };
var minOperations = function(boxes) { const ans = new Array(boxes.length).fill(0); let ballsLeft = 0, ballsRight = 0; let movesLeft = 0, movesRight = 0; const len = boxes.length - 1; for(let i = 0; i <= len; i++) { movesLeft += ballsLeft; movesRight += ballsRight; ans[i] += movesLeft; ans[len - i] += movesRight; ballsLeft += +boxes[i]; ballsRight += +boxes[len - i]; } return ans; };
Minimum Number of Operations to Move All Balls to Each Box
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess. Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. &nbsp; Example 1: Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] Output: 7 Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. Example 2: Input: dungeon = [[0]] Output: 1 &nbsp; Constraints: m == dungeon.length n == dungeon[i].length 1 &lt;= m, n &lt;= 200 -1000 &lt;= dungeon[i][j] &lt;= 1000
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: dp = defaultdict(lambda: inf) dp[(len(dungeon), len(dungeon[0]) - 1)] = 1 for i in range(len(dungeon) - 1, -1, -1): for j in range(len(dungeon[0]) - 1, -1, -1): dp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i][j] if dp[(i, j)] <= 0: dp[(i, j)] = 1 return dp[(0, 0)]
class Solution { Integer[][] min; public int calculateMinimumHP(int[][] dungeon) { min = new Integer[dungeon.length][dungeon[0].length]; int answer = min(0, 0, dungeon); return Math.max(answer, 1); } public int min(int i, int j, int[][] dungeon){ if(i > dungeon.length - 1 || j > dungeon[0].length - 1) return 400000; if(i == dungeon.length - 1 && j == dungeon[0].length - 1) return - dungeon[i][j] + 1; if(min[i][j] == null){ int down = min(i + 1, j, dungeon); int right = min(i, j + 1, dungeon); min[i][j] = Math.min(Math.max(right, 1), Math.max(down, 1)) - dungeon[i][j]; } return min[i][j]; } }
class Solution { public: int solve(int i, int j, int m , int n, vector<vector<int>> &grid) { // if we come out of the grid simply return a large value if(i >= m || j >= n) return INT_MAX; // calucate health by the 2 possible ways int down = solve(i + 1, j, m, n, grid); int right = solve(i, j + 1, m, n, grid); // take the min both both int health = min(down, right); // we reach the destination when both the sides return INT_MAX if(health == INT_MAX) { health = 1; // both are +ve large integers so min health required = 1 } int ans = 0; if(health - grid[i][j] > 0) { ans = health - grid[i][j]; } else { ans = 1; } return ans; } int calculateMinimumHP(vector<vector<int>>& dungeon) { int m = dungeon.size(); int n = dungeon[0].size(); return solve(0, 0, m, n, dungeon); } };
/** * The dynamic programming solution. * * Time Complexity: O(m*n) * Space Complexity: O(1) * * @param {number[][]} dungeon * @return {number} */ var calculateMinimumHP = function(dungeon) { const m = dungeon.length const n = dungeon[0].length const ii = m - 1 const jj = n - 1 for (let i = ii; i >= 0; i--) { for (let j = jj; j >= 0; j--) { if (i < ii || j < jj) { const hc = dungeon[i][j] const hp1 = (i < ii) ? Math.min(hc, hc + dungeon[i + 1][j]) : -Infinity const hp2 = (j < jj) ? Math.min(hc, hc + dungeon[i][j + 1]) : -Infinity dungeon[i][j] = Math.max(hp1, hp2) } } } return Math.max(1 - dungeon[0][0], 1) }
Dungeon Game
You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i is weaker than a row j if one of the following is true: The number of soldiers in row i is less than the number of soldiers in row j. Both rows have the same number of soldiers and i &lt; j. Return the indices of the k weakest rows in the matrix ordered from weakest to strongest. &nbsp; Example 1: Input: mat = [[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0], [1,1,1,1,1]], k = 3 Output: [2,0,3] Explanation: The number of soldiers in each row is: - Row 0: 2 - Row 1: 4 - Row 2: 1 - Row 3: 2 - Row 4: 5 The rows ordered from weakest to strongest are [2,0,3,1,4]. Example 2: Input: mat = [[1,0,0,0], [1,1,1,1], [1,0,0,0], [1,0,0,0]], k = 2 Output: [0,2] Explanation: The number of soldiers in each row is: - Row 0: 1 - Row 1: 4 - Row 2: 1 - Row 3: 1 The rows ordered from weakest to strongest are [0,2,3,1]. &nbsp; Constraints: m == mat.length n == mat[i].length 2 &lt;= n, m &lt;= 100 1 &lt;= k &lt;= m matrix[i][j] is either 0 or 1.
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: row = [] for i in range(len(mat)): row.append((sum(mat[i]), i)) row.sort() ans = [idx for (val, idx) in row[:k]] return ans
class Solution { public int[] kWeakestRows(int[][] mat, int k) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> list = new ArrayList<>(); int[] arr = new int[k]; for (int i = 0; i < mat.length; i++){ int n = getBits(mat[i]); map.put(i, n); list.add(n); } Collections.sort(list); int z = 0; for (int i = 0; i < k; i++){ for (Map.Entry<Integer, Integer> m : map.entrySet()){ if (list.get(i).equals(m.getValue())){ arr[z++] = m.getKey(); map.remove(m.getKey(), m.getValue()); break; } } } return arr; } private static Integer getBits(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == 1) count++; } return count; } }
class Solution { public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { // <idx, count> vector<pair<int,int>> freqMapper; int civilian = 0; for(int i=0; i<mat.size(); ++i) { int degree = count(mat[i].begin(), mat[i].end(), civilian); freqMapper.push_back({i, degree}); } sort(freqMapper.begin(), freqMapper.end(), [](pair<int,int> pair1, pair<int,int> pair2) { if (pair1.second > pair2.second) { return true; } else if (pair1.second == pair2.second) { return pair1.first < pair2.first; } return pair1.second > pair2.second; }); vector<int> kWeakest; for(int i=0; i<k; i++) kWeakest.push_back(freqMapper[i].first); return kWeakest; } };
/** * @param {number[][]} mat * @param {number} k * @return {number[]} * S: O(N) * T: O(N*logN) */ var kWeakestRows = function(mat, k) { return mat.reduce((acc, row, index) => { let left = 0; let right = row.length - 1; while(left <= right) { let mid = Math.floor( (left + right) / 2); if(row[mid]) { left = mid + 1; } else { right = mid - 1; } } acc.push({ index, value: left }); return acc; }, []).sort((a, b) => a.value - b.value).splice(0, k).map(item => item.index); };
The K Weakest Rows in a Matrix
Given an m x n matrix, return all elements of the matrix in spiral order. &nbsp; Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 10 -100 &lt;= matrix[i][j] &lt;= 100
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: col, row = len(matrix[0]), len(matrix) l, t, r, b = 0, 0, col - 1, row - 1 res = [] while l <= r and t <= b: for i in range(l, r): res.append(matrix[t][i]) for i in range(t, b): res.append(matrix[i][r]) # Append the orphan left by the open interval if t == b: res.append(matrix[t][r]) else: # From right to left at the bottom for i in range(r, l, -1): res.append(matrix[b][i]) # Avoid duplicated appending if it is a square if l == r and t != b: res.append(matrix[b][r]) else: # From bottom to top at the left for i in range(b, t, -1): res.append(matrix[i][l]) l += 1 t += 1 r -= 1 b -= 1 return res
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1; while (top <= bottom && left <= right) { for (int i = left; i <= right; i++) ans.add(matrix[top][i]); top++; for (int i = top; i <= bottom; i++) ans.add(matrix[i][right]); right--; if (top <= bottom) { for (int i = right; i >= left; i--) ans.add(matrix[bottom][i]); bottom--; } if (left <= right) { for (int i = bottom; i >= top; i--) ans.add(matrix[i][left]); left++; } } return ans; } }
class Solution { public: vector<int> _res; vector<vector<bool>> _visited; void spin(vector<vector<int>>& matrix, int direction, int i, int j) { _visited[i][j] = true; _res.push_back(matrix[i][j]); switch (direction){ // left to right case 0: if ( j+1 >= matrix[0].size() || _visited[i][j+1]) { direction = 1; i++; } else { j++; } break; // up to bottom case 1: if ( i+1 >= matrix.size() || _visited[i+1][j]) { direction = 2; j--; } else { i++; } break; // right to left case 2: if ( j == 0 || _visited[i][j-1]) { direction = 3; i--; } else { j--; } break; // bottom to up case 3: if ( i == 0 || _visited[i-1][j]) { direction = 0; j++; } else { i--; } break; } if ( i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() ) { return; } if ( _visited[i][j] ) { return; } spin(matrix, direction, i, j); } vector<int> spiralOrder(vector<vector<int>>& matrix) { _res.clear(); _visited = vector<vector<bool>>(matrix.size(), std::vector<bool>(matrix[0].size(), false)); spin(matrix, 0, 0, 0); return _res; } };
/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function(matrix) { let [top, bot, left, right, ans] = [0, matrix.length - 1, 0, matrix[0].length - 1,[]] while ((top <= bot) && (left <= right)) { for (let j = left; j <= right; j++) { ans.push(matrix[top][j]) } top ++; for (let i = top; i <= bot; i++) { ans.push(matrix[i][right]) } right --; if ((bot < top) || (right < left)) { break } for (let j = right; left <= j; j--){ ans.push(matrix[bot][j]) } bot --; for (let i = bot; top <= i; i--){ ans.push(matrix[i][left]) } left ++; } return ans }
Spiral Matrix
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning. &nbsp; Example 1: Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] Explanation Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 -231 &lt;= nums[i] &lt;= 231 - 1 target is an integer from nums. At most 104 calls will be made to pick.
class Solution: def __init__(self, nums: List[int]): #self.nums = nums #create a hash of values with their list of indices self.map = defaultdict(list) for i,v in enumerate(nums): self.map[v].append(i) def pick(self, target: int) -> int: return random.sample(self.map[target],1)[0] ''' reservoir = 0 count = 0 for i in range(len(self.nums)): if self.nums[i] == target: count+=1 if random.random() < 1/count: reservoir = i return reservoir samp = [] for i in range(len(self.nums)): if self.nums[i] == target: samp.append(i) return (random.sample(samp,1))[0] ''' # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target)
class Solution { ArrayList<Integer> ll=new ArrayList<>(); public Solution(int[] nums) { for(int i=0;i<nums.length;i++){ ll.add(nums[i]); } } public int pick(int target) { double a=Math.random(); int n=(int)(a*this.ll.size()); while(this.ll.get(n)!=target){ a=Math.random(); n=(int)(a*this.ll.size()); } return n; } }
class Solution { unordered_map<int,vector<int>> itemIndicies; public: Solution(vector<int>& nums) { srand(time(NULL)); for (int i = 0; i < nums.size(); i++) { if (itemIndicies.find(nums[i]) == itemIndicies.end()) itemIndicies[nums[i]] = {i}; else itemIndicies[nums[i]].push_back(i); } } int pick(int target) { int size = itemIndicies[target].size(); int randomValue = rand() % size; return itemIndicies[target][randomValue]; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * int param_1 = obj->pick(target); */
var Solution = function(nums) { this.map = nums.reduce((result, num, index) => { const value = result.get(num) ?? []; value.push(index); result.set(num, value); return result; }, new Map()); }; Solution.prototype.pick = function(target) { const pick = this.map.get(target); const random = Math.random() * pick.length | 0; return pick[random]; };
Random Pick Index
Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). &nbsp; Example 1: Input: s = "abacbc" Output: true Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s. Example 2: Input: s = "aaabb" Output: false Explanation: The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times. &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consists of lowercase English letters.
class Solution: def areOccurrencesEqual(self, s: str) -> bool: return len(set(Counter(s).values())) == 1
class Solution { public boolean areOccurrencesEqual(String s) { int[] freq = new int[26]; for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++; int val = freq[s.charAt(0) - 'a']; for (int i = 0; i < 26; i++) if (freq[i] != 0 && freq[i] != val) return false; return true; } }
class Solution { public: bool areOccurrencesEqual(string s) { unordered_map<char, int> freq; for (auto c : s) freq[c]++; int val = freq[s[0]]; for (auto [a, b] : freq) if (b != val) return false; return true; } };
var areOccurrencesEqual = function(s) { var freq = {} for (let c of s) freq[c] = (freq[c] || 0) + 1 var val = freq[s[0]] for (let c in freq) if (freq[c] && freq[c] != val) return false; return true; };
Check if All Characters Have Equal Number of Occurrences
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed. &nbsp; Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes. &nbsp; Constraints: 3 &lt;= s.length &lt;= 2000 s​​​​​​ consists only of lowercase English letters.
class Solution: def checkPartitioning(self, s: str) -> bool: n = len(s) @lru_cache(None) def pal(i,j): if i == j: return True if s[i] != s[j]: return False if i+1 == j: return True else: return pal(i+1,j-1) for i in range(n-2): if pal(0,i): for j in range(i+1,n-1): if pal(i+1,j) and pal(j+1,n-1): return True return False
class Solution { public boolean checkPartitioning(String s) { int n = s.length(); boolean[][] dp = new boolean[n][n]; for(int g=0 ; g<n ; g++){ for(int i=0, j=g ; j<n ; j++, i++){ if(g == 0) dp[i][j] = true; else if(g == 1) dp[i][j] = (s.charAt(i) == s.charAt(j)) ? true : false; else{ dp[i][j] = (dp[i+1][j-1]&((s.charAt(i) == s.charAt(j)) ? true : false)); } } } for(int i=0 ; i<n-2 ; i++){ if(dp[0][i]){ for(int j=i+1 ; j<n-1 ; j++){ if(dp[i+1][j] && dp[j+1][n-1]){ return true; } } } } return false; } }
class Solution { public: vector<vector<int>> dp1; bool isPalindrome(string& s, int i, int j) { if (i >= j) return true; if (dp1[i][j] != -1) return dp1[i][j]; if (s[i] == s[j]) return dp1[i][j] = isPalindrome(s, i + 1, j - 1); return dp1[i][j] = false; } bool checkPartitioning(string s) { int n = s.size(); dp1.resize(n,vector<int> (n,-1)); for(int i=0;i<n;i++){ for(int j=i+1;j<n-1;j++){ if(isPalindrome(s,0,i) && isPalindrome(s,i+1,j) && isPalindrome(s,j+1,n-1)) return true; } } return false; } };
/** * @param {string} s * @return {boolean} */ var checkPartitioning = function(s) { // create a dp that will represent the starting and ending index of a substring // if dp[i][j] is true that means that the string starting from i and ending at j is a palindrome const dp = new Array(s.length).fill(null).map(() => new Array(s.length).fill(false)); // all substrings of length 1 are palindromes so we mark all matching indices as true for (let i = 0; i < s.length; i++) { dp[i][i] = true; } // slowly grow the substring from each index // we will know the substring is a palindrom if the substring prior was a palindrome for (let lengthOfSubString = 2; lengthOfSubString <= s.length; lengthOfSubString++) { for (let startingIndex = 0; startingIndex + lengthOfSubString <= s.length; startingIndex++) { // if it's not the same character, then it can not be a palindrome if (s[startingIndex] !== s[startingIndex + lengthOfSubString - 1]) continue; if (lengthOfSubString <= 3 || // this checks if the prior substring was a palindrome dp[startingIndex + 1][startingIndex + lengthOfSubString - 2]) { dp[startingIndex][startingIndex + lengthOfSubString - 1] = true; } } } // find out if any 3 of the partitions are palindromes for (let i = 0; i < s.length; i++) { for (let j = i + 1; j < s.length; j++) { if (dp[0][i] && dp[i + 1][j] && dp[j + 1][s.length - 1]) return true; } } // if we haven't found a partition, return false return false; };
Palindrome Partitioning IV
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. &nbsp; Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] &nbsp; Constraints: 1 &lt;= n &lt;= 8
class Solution: def generateParenthesis(self, n: int) -> list[str]: # Initialize the result res = [] # Recursively go through all possible combinations def add(open, close, partialRes): nonlocal res # If we have added opening and closing parentheses n times, we reaches a solution if open == close == n: res.append("".join(partialRes)) return # Add a closing parenthesis to the partial result if we have at least 1 opening parenthesis if close < open: add(open, close + 1, partialRes + [")"]) # Add an opening parenthesis to the partial result if we haven't added n parenthesis yet if open < n: add(open + 1, close, partialRes + ["("]) add(0, 0, []) return res
class Solution { List<String> s = new ArrayList<>(); public void get(int n, int x, String p) { if(n==0 && x==0) { s.add(p); return; } if(n==0) { get(n,x-1,p+")"); } else if(x==0) { get(n-1,x+1,p+"("); } else { get(n,x-1,p+")"); get(n-1,x+1,p+"("); } } public List<String> generateParenthesis(int n) { s.clear(); get(n,0,""); return s; } }
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> ans; generate(ans,"",n,n); return ans; } void generate(vector<string> &ans,string s,int open,int close) { if(open == 0 && close == 0) { ans.push_back(s); return ; } if(open > 0) { generate(ans,s+'(',open-1,close); } if(open < close) { generate(ans,s+')',open,close-1); } } };
var generateParenthesis = function(n) { let ans = [] generate_parenthisis(n, 0, 0, "") return ans function generate_parenthisis(n, open, close, res){ if(open==n && close == n){ ans.push(res) return } if(open<n){ generate_parenthisis(n, open+1, close, res + "(") } if(close<open){ generate_parenthisis(n, open, close+1, res+")") } } };
Generate Parentheses
The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 &amp; 5 &amp; 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0. &nbsp; Example 1: Input: candidates = [16,17,71,62,12,24,14] Output: 4 Explanation: The combination [16,17,62,24] has a bitwise AND of 16 &amp; 17 &amp; 62 &amp; 24 = 16 &gt; 0. The size of the combination is 4. It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. Note that more than one combination may have the largest size. For example, the combination [62,12,24,14] has a bitwise AND of 62 &amp; 12 &amp; 24 &amp; 14 = 8 &gt; 0. Example 2: Input: candidates = [8,8] Output: 2 Explanation: The largest combination [8,8] has a bitwise AND of 8 &amp; 8 = 8 &gt; 0. The size of the combination is 2, so we return 2. &nbsp; Constraints: 1 &lt;= candidates.length &lt;= 105 1 &lt;= candidates[i] &lt;= 107
class Solution: def largestCombination(self, candidates: List[int]) -> int: return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))
class Solution { public static int largestCombination(int[] candidates) { int arr[] = new int[32]; for (int i = 0; i < candidates.length; i++) { String temp = Integer.toBinaryString(candidates[i]); int n = temp.length(); int index = 0; while (n-- > 0) { arr[index++] += temp.charAt(n) - '0'; } } int res = Integer.MIN_VALUE; for (int i = 0; i < 32; i++) { res = Math.max(res, arr[i]); } return res; } }
class Solution { public: int largestCombination(vector<int>& candidates) { vector<int> bits(32); for(int i = 0; i < candidates.size(); i++){ int temp = 31; while(candidates[i] > 0){ bits[temp] += candidates[i] % 2; candidates[i] = candidates[i] / 2; temp--; } } int ans = 0; for(int i = 0; i < 32; i++){ //cout<<bits[i]<<" "; ans = max(ans, bits[i]); } return ans; } };
var largestCombination = function(candidates) { const indexArr=Array(24).fill(0) for(let candidate of candidates){ let index =0 while(candidate>0){ if((candidate&1)===1)indexArr[index]+=1 candidate>>>=1 index++ } } return Math.max(...indexArr) };
Largest Combination With Bitwise AND Greater Than Zero
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). &nbsp; Example 1: Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) &lt; sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. Example 2: Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted. &nbsp; Constraints: 1 &lt;= k &lt;= points.length &lt;= 104 -104 &lt; xi, yi &lt; 104
def cal(ele): return ele[0]**2 +ele[1]**2 def partition(arr,start,end): # We must take a pivot element randomly to make Quick select work faster rdIdx = randint(start,end) arr[rdIdx],arr[end] = arr[end],arr[rdIdx] pivot = arr[end] i = start-1 pivot_dis = cal(pivot) for j in range(start,end): if cal(arr[j]) <= pivot_dis: i+=1 arr[j],arr[i] = arr[i],arr[j] arr[i+1],arr[end] = arr[end],arr[i+1] return i+1 def qSelect(arr,kth,start,end): if start < end: pv= partition(arr,start,end) # _______________________ # | Left |ele| Right| # ------------------------ # pv # after partition function call, pv is the index that sacrify: # all elements in Left will smaller than ele # all elements in Right side will greater than ele if pv == kth:# return if kth < pv: return qSelect(arr,kth,start,pv-1) else: return qSelect(arr,kth,pv+1,end) # Space O (logn) because of using recursion # Time: Average case: O(N) # Worst case: O(N**2) class Solution: def kClosest(self, points, k): # print(points) qSelect(points,k-1,0,len(points)-1)# kth smallest number will be at (k-1) index in sorted array return points[:k]
class Solution { static class Distance { int i; int j; double dist; public Distance(int i, int j, double dist) { this.i = i; this.j = j; this.dist = dist; } } public int[][] kClosest(int[][] points, int k) { PriorityQueue<Distance> pq = new PriorityQueue<>((x,y) -> Double.compare(x.dist, y.dist)); for(int[] point : points) { double dist = calcDistance(point[0], point[1]); pq.offer(new Distance(point[0], point[1], dist)); } int cnt = 0; ArrayList<int[]> l = new ArrayList<>(); while(cnt < k) { Distance d = pq.poll(); l.add(new int[]{d.i, d.j}); cnt++; } int[][] res = l.toArray(new int[l.size()][]); return res; } private double calcDistance(int i, int j) { double dist = Math.sqrt(Math.pow(i,2) + Math.pow(j,2)); return dist; } }
class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int k) { //max heap priority_queue<pair<int,pair<int,int>>> pq;//first integer is distance(no need for sq root as comparison is same and next part of pair is coordinate int n= points.size(); for(int i=0;i<n;i++) { int dist=(points[i][0]*points[i][0]+points[i][1]*points[i][1]); pq.push({dist, {points[i][0],points[i][1]}}); if(pq.size()>k) pq.pop(); } vector<vector<int>> ans; while(!pq.empty()) { vector<int> temp={(pq.top().second.first),pq.top().second.second}; ans.push_back(temp); pq.pop(); } return ans; } };
/** * @param {number[][]} points * @param {number} k * @return {number[][]} */ var kClosest = function(points, k) { let res = []; let hashMap = new Map(); for(let i = 0; i < points.length; i++) { //store the distance and the index of the points in a map const dis = calcDis(points[i]); hashMap.set(i, dis); } //sort the map by its distance to the origin const hashMapNew = new Map([...hashMap].sort((a,b) => a[1] - b[1])); //use the index sorted by distance to get the result let i = 0; for(const x of hashMapNew.keys()) { //do it k times if(i === k) break; res.push(points[x]); i++; } return res; }; var calcDis = (b) => { return Math.sqrt( Math.pow(b[0], 2) + Math.pow(b[1], 2) ); }
K Closest Points to Origin
Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. &nbsp; Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. Example 2: Input: root = [1], target = 1, k = 3 Output: [] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 500]. 0 &lt;= Node.val &lt;= 500 All the values Node.val are unique. target is the value of one of the nodes in the tree. 0 &lt;= k &lt;= 1000
class Solution: def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: # DFS to make the adj List adjList = defaultdict(list) def dfs(node): if not node: return if node.left: adjList[node].append(node.left) adjList[node.left].append(node) if node.right: adjList[node].append(node.right) adjList[node.right].append(node) dfs(node.left) dfs(node.right) dfs(root) # bfs to find the nodes with k distance q = deque([(target, 0)]) visit = set() visit.add(target) res = [] while q: for i in range(len(q)): node, dist = q.popleft() if dist == k: res.append(node.val) if dist > k: break for nei in adjList[node]: if nei not in visit: visit.add(nei) q.append((nei, dist + 1)) return res
class Solution { public List<Integer> distanceK(TreeNode root, TreeNode target, int k) { HashMap<TreeNode,TreeNode> map=new HashMap<>(); get_parent(root,map); Queue<TreeNode> q=new LinkedList<>(); q.add(target); int distance=0; HashSet<TreeNode> visited=new HashSet<>(); visited.add(target); while(!q.isEmpty()) { if(distance==k) break; distance++; int size=q.size(); for(int i=0;i<size;i++) { TreeNode current=q.poll(); if(current.left!=null && !visited.contains(current.left)) { q.add(current.left); visited.add(current.left); } if(current.right!=null && !visited.contains(current.right)) { q.add(current.right); visited.add(current.right); } if(map.containsKey(current) && !visited.contains(map.get(current))) { q.add(map.get(current)); visited.add(map.get(current)); } } } List<Integer> ans=new ArrayList<>(); while(!q.isEmpty()) ans.add(q.poll().val); return ans; } public void get_parent(TreeNode root,HashMap<TreeNode,TreeNode> map) { Queue<TreeNode> q=new LinkedList<>(); q.add(root); while(!q.isEmpty()) { int size=q.size(); for(int i=0;i<size;i++) { TreeNode current=q.poll(); if(current.left!=null) { map.put(current.left,current); q.add(current.left); } if(current.right!=null) { map.put(current.right,current); q.add(current.right); } } } } }
void makeParent(TreeNode *root, unordered_map<TreeNode*, TreeNode*> &parent) { queue<TreeNode*> q; q.push(root); while(q.empty()==false) { TreeNode *curr = q.front(); q.pop(); if(curr->left!=NULL) { parent[curr->left] = curr; q.push(curr->left); } if(curr->right!=NULL) { parent[curr->right] = curr; q.push(curr->right); } } } class Solution { public: void solve(TreeNode* target, unordered_map<TreeNode*,TreeNode*> &parent,unordered_map<TreeNode*,bool> &visited, vector<int> &res, int k) { if(k==0){ res.push_back(target->val); return; } queue<TreeNode *>q; int distance = 0; q.push(target); visited[target] = 1; while(q.empty()==false) { int count = q.size(); distance++;// increment distance value for current level of our level order traversal for(int i=0;i<count;i++) { TreeNode *curr = q.front(); q.pop(); if(curr->left!=NULL && visited[curr->left]==false) { visited[curr->left] = true; q.push(curr->left); if(distance==k)// when we reach the node at distance = k, push it to res res.push_back(curr->left->val); } if(curr->right!=NULL && visited[curr->right]==false) { visited[curr->right] = true; q.push(curr->right); if(distance==k)// when we reach the node at distance = k, push it to res res.push_back(curr->right->val); } if(parent[curr] && visited[parent[curr]]==false) { visited[parent[curr]] = true; q.push(parent[curr]); if(distance==k)// when we reach the node at distance = k, push it to res res.push_back(parent[curr]->val); } } if(distance==k)// if in curr iteration all k distances nodes have been pushed, we break break; } } vector<int> distanceK(TreeNode* root, TreeNode* target, int k) { unordered_map<TreeNode*,TreeNode*> parent; makeParent(root,parent); unordered_map<TreeNode*,bool> visited; vector<int> ans; solve(target,parent,visited,ans,k);// begin from target Node return ans; }
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} target * @param {number} k * @return {number[]} */ var distanceK = function(root, target, k) { if(k === 0) return [target.val]; let res = []; const helper = (node, k, bool) => { if(node === null) return [false, 0]; if(k === 0 && node.val !== target.val) { res.push(node.val); return null; } if(bool) { helper(node.left, k - 1, bool); helper(node.right, k - 1, bool); return null; } if(node.val === target.val) { //Here nodes of k distance are at bottom helper(node.left, k - 1, true); helper(node.right, k - 1, true); return [true, 1]; } else { let [l, d] = helper(node.left, k, false); //Found target node on left side, now get nodes of k distance from right side as well if(l === true) { if(k - d === 0) //for current node res.push(node.val); helper(node.right, k - d - 1, true); return [true, d + 1]; } let [r, d1] = helper(node.right, k, false); if(r === true) { if(k - d1 === 0) res.push(node.val); helper(node.left, k - d1 - 1, true); return [true, d1 + 1]; } return [false, 0]; } } helper(root, k, false); return res; };
All Nodes Distance K in Binary Tree
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. &nbsp; Example 1: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: list1 = [], list2 = [] Output: [] Example 3: Input: list1 = [], list2 = [0] Output: [0] &nbsp; Constraints: The number of nodes in both lists is in the range [0, 50]. -100 &lt;= Node.val &lt;= 100 Both list1 and list2 are sorted in non-decreasing order.
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: cur = dummy = ListNode() while list1 and list2: if list1.val < list2.val: cur.next = list1 list1, cur = list1.next, list1 else: cur.next = list2 list2, cur = list2.next, list2 if list1 or list2: cur.next = list1 if list1 else list2 return dummy.next
class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { if(list1==null && list2==null) return null; if(list1 == null) return list2; if(list2 == null) return list1; ListNode newHead = new ListNode(); ListNode newNode = newHead; while(list1!=null && list2!=null) { //ListNode newNode = new ListNode(); if(list1.val <= list2.val) { newNode.next = list1; list1 = list1.next; } else if(list1.val >= list2.val) { newNode.next = list2; list2 = list2.next; } newNode = newNode.next; } if(list1!=null) newNode.next = list1; else if(list2!=null) newNode.next = list2; return newHead.next; } }
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy(INT_MIN); ListNode *tail = &dummy; while (l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } tail->next = l1 ? l1 : l2; return dummy.next; } };
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} list1 * @param {ListNode} list2 * @return {ListNode} */ var mergeTwoLists = function(list1, list2) { if(!list1) return list2 if(!list2) return list1 let mergedList = new ListNode(0); let ptr = mergedList; let curr1 = list1; let curr2 = list2; while(curr1 && curr2){ let newNode = new ListNode(); if(!curr2 || curr1.val < curr2.val){ newNode.val = curr1.val; newNode.next = null; ptr.next = newNode curr1 =curr1.next; } else{ newNode.val = curr2.val; newNode.next = null; ptr.next = newNode curr2 =curr2.next; } ptr = ptr.next } if(curr1 !== null){ ptr.next = curr1; curr1 = curr1.next; } if(curr2 !== null){ ptr.next = curr2; curr2 = curr2.next; } return mergedList.next };
Merge Two Sorted Lists
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. &nbsp; Example 1: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Explanation: The given graph is shown above. Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. Example 2: Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] Output: [4] Explanation: Only node 4 is a terminal node, and every path starting at node 4 leads to node 4. &nbsp; Constraints: n == graph.length 1 &lt;= n &lt;= 104 0 &lt;= graph[i].length &lt;= n 0 &lt;= graph[i][j] &lt;= n - 1 graph[i] is sorted in a strictly increasing order. The graph may contain self-loops. The number of edges in the graph will be in the range [1, 4 * 104].
import collections class Solution: def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]: n = len(graph) ans = [] for i in range(n): if not graph[i]: ans.append(i) def loop(key, loops): loops.append(key) for i in graph[key]: if i in loops: return False elif i in ans: continue else: r = loop(i, loops) if r == True: continue else: return False idx = loops.index(key) loops.pop(idx) return True for i in range(n): loops = [] if i in ans: continue r = loop(i, loops) if r == True: ans.append(i) return sorted(ans)
class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int n=graph.length; List<Integer> ans=new ArrayList<>(); boolean visited[]=new boolean[n]; boolean dfsVisited[]=new boolean[n]; boolean nodeCycles[]=new boolean[n]; for(int i=0;i<n;i++){ if(visited[i]==false){ isCycle(i,graph,dfsVisited,visited,nodeCycles); } } for(int i=0;i<nodeCycles.length;i++){ if(nodeCycles[i]==false) ans.add(i); } return ans; } public boolean isCycle(int node,int graph[][],boolean dfsVisited[],boolean visited[],boolean [] nodeCycles) { visited[node]=true; dfsVisited[node]=true; for(int adjNode:graph[node]){ if(visited[adjNode]==false){ if(isCycle(adjNode,graph,dfsVisited,visited,nodeCycles)) return nodeCycles[node]=true; }else if(visited[adjNode]==true && dfsVisited[adjNode]==true){ return nodeCycles[node]=true; } } dfsVisited[node]=false; return false; } }
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { int n=graph.size(); vector<bool> vis(n, false), curr_vis(n, false), safe(n, true); for(int i=0; i<n; i++) if(!vis[i]) dfs(i, vis, curr_vis, safe, graph); vector<int> ans; for(int i=0; i<n; i++) if(safe[i]) ans.push_back(i); return ans; } bool dfs(int i, vector<bool> &vis, vector<bool> &curr_vis, vector<bool> &safe, vector<vector<int>>& graph){ vis[i]=true, curr_vis[i]=true; for(auto j : graph[i]){ if(!vis[j]){ if(dfs(j, vis, curr_vis, safe, graph)==false) return safe[i] = false; } else if(curr_vis[j]) return safe[i] = false; } curr_vis[i]=false; return safe[i]; } };
/** * @param {number[][]} graph * @return {number[]} */ var eventualSafeNodes = function(graph) { const ans = []; const map = new Map(); for(let i=0; i<graph.length; i++) { if(dfs(graph, i, map)) { ans.push(i); } } return ans; }; var dfs = function(graph, node, map) { if(map.has(node)) return map.get(node); map.set(node, false); for(let nei of graph[node]) { if(!dfs(graph, nei, map)) { return false; } } map.set(node, true); return true; }
Find Eventual Safe States
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. &nbsp; Example 1: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] Output: 8 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 2: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] Output: 6 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 3: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] Output: 0 &nbsp; Constraints: 1 &lt;= n &lt;= 105 edges.length == n - 1 edges[i].length == 2 0 &lt;= ai &lt; bi &lt;= n - 1 fromi &lt; toi hasApple.length == n
class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: graph_map = {i: set() for i in range(n)} for edge in edges: graph_map[edge[0]].add(edge[1]) graph_map[edge[1]].add(edge[0]) self.result = set() visited = set() def dfs(node, path): visited.add(node) if hasApple[node]: temp = path + '|' + str(node) temp = temp.split('|')[1:] # print(temp) for i in range(1, len(temp)): self.result.add((temp[i], temp[i-1])) for nei in graph_map[node]: if nei not in visited: dfs(nei, path + '|' + str(node)) dfs(0, "") # print(self.result) return len(self.result) * 2
class Solution { public int minTime(int n, int[][] edges, List<Boolean> hasApple) { HashMap<Integer,List<Integer>> graph = new HashMap<>(n); for(int edge[] : edges){ int a = edge[0], b = edge[1]; graph.putIfAbsent(a, new LinkedList<>()); graph.putIfAbsent(b, new LinkedList<>()); graph.get(a).add(b); graph.get(b).add(a); } boolean[] visited = new boolean[n]; Arrays.fill(visited,false); int a = move(0,graph,hasApple,n,visited); return a==-1?0:a; } public int move(int i,HashMap<Integer,List<Integer>> graph,List<Boolean> hasApple,int n,boolean[] visited){ visited[i]=true; boolean cont = false; if(hasApple.get(i)){ cont=true; } List<Integer> list = graph.get(i); if(list==null){ return cont?0:-1; } int j = 0; for(int k : list){ if(!visited[k]){ int a = move(k,graph,hasApple,n,visited); if(a!=-1){ j+=2+a; } } } if(j==0 && cont) return 0; return j==0?-1:j; } }
class DSU{ private: vector<int> parent,rank ; public: DSU(int n){ rank.resize(n,1) ; parent.resize(n) ; iota(begin(parent),end(parent),0) ; } int find_parent(int node){ if(node == parent[node]) return node ; return parent[node] = find_parent(parent[node]) ; } void Union(int u , int v){ int U = find_parent(u) , V = find_parent(v) ; if(U == V) return ; if(rank[U] < rank[V]) swap(U,V) ; rank[U] += rank[V] ; parent[V] = U ; } int getRank(int node){ return rank[parent[node]] ; } }; class Solution { public: vector<bool> dp ; vector<bool> hasApple ; vector<int> adj[100001] ; vector<int> visited ; void dfs(int src){ visited[src] = 1 ; for(auto &nbr : adj[src]){ if(!visited[nbr]){ dfs(nbr) ; dp[src] = dp[src] or dp[nbr] ; } } } int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) { DSU dsu(n) ; dp = hasApple ; visited.resize(n,0) ; this->hasApple = hasApple ; for(auto &x : edges) adj[x[0]].push_back(x[1]) , adj[x[1]].push_back(x[0]) ; dfs(0) ; int start = -1 ; for(int i = 0 ; i < n ; ++i ){ if(!dp[i]) continue ; if(start == -1){ start = i ; continue ; } dsu.Union(start,i) ; } return (dsu.getRank(0) - 1) * 2 ; } };
var cnvrtAdjLst = (mat) => {//converts the list of edges to adjacency list let map = new Map(); for(let i=0; i<mat.length; i++){ let [p,c] = mat[i]; if(map[p]===undefined) map[p] = [c]; else map[p].push(c); if(map[c]===undefined) map[c] = [p]; else map[c].push(p); } return map; } var minTime = function(n, edges, hasApple) { let adjList = cnvrtAdjLst(edges);//convert to adjacency list for undirected graph let visited = new Set();// visited set for checking trivial loop let dfsForApples = (src, len) => { visited.add(src);// add root to visited set, as we start exploring the subtree let lengthFromNow = 0;//total length of path visited by each child, 0 if no child has apple for(let i in adjList[src]){ if(!visited.has(adjList[src][i])){ lengthFromNow += dfsForApples(adjList[src][i],len+1);// add child path length to total length } } if(lengthFromNow>0){ //if there is an apple present in the subtree return lengthFromNow + 2; } else if(hasApple[src]){ //if there is no apple in subtree but apple is present on the root node return 2; } else{ // if no apple is present in subtree return 0; } } visited.add(0); let res = dfsForApples(0,0); return res?res-2:0;//check if the root node itself has an apple or no apple is present };
Minimum Time to Collect All Apples in a Tree
There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] &lt; rating[j] &lt; rating[k]) or (rating[i] &gt; rating[j] &gt; rating[k]) where (0 &lt;= i &lt; j &lt; k &lt; n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). &nbsp; Example 1: Input: rating = [2,5,3,4,1] Output: 3 Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). Example 2: Input: rating = [2,1,3] Output: 0 Explanation: We can't form any team given the conditions. Example 3: Input: rating = [1,2,3,4] Output: 4 &nbsp; Constraints: n == rating.length 3 &lt;= n &lt;= 1000 1 &lt;= rating[i] &lt;= 105 All the integers in rating are unique.
class Solution: def numTeams(self, ratings: List[int]) -> int: upper_dps = [0 for _ in range(len(ratings))] lower_dps = [0 for _ in range(len(ratings))] count = 0 for i in range(len(ratings)): for j in range(i): if ratings[j] < ratings[i]: count += upper_dps[j] upper_dps[i] += 1 else: count += lower_dps[j] lower_dps[i] += 1 return count
// Smaller * Larger Solution // sum of #smaller * #larger // Time complexity: O(N^2) // Space complexity: O(1) class Solution { public int numTeams(int[] rating) { final int N = rating.length; int res = 0; for (int i = 1; i < N; i++) { res += smaller(rating, i, -1) * larger(rating, i, 1); res += larger(rating, i, -1) * smaller(rating, i, 1); } return res; } private int smaller(int[] rating, int i, int diff) { int t = rating[i], count = 0; i += diff; while (i >= 0 && i < rating.length) { if (rating[i] < t) count++; i += diff; } return count; } private int larger(int[] rating, int i, int diff) { int t = rating[i], count = 0; i += diff; while (i >= 0 && i < rating.length) { if (rating[i] > t) count++; i += diff; } return count; } }
class Solution { public: int numTeams(vector<int>& rating) { int i, j, n = rating.size(), ans = 0; vector<int> grt(n, 0), les(n, 0); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(rating[j] > rating[i]) grt[i] += 1; else les[i] += 1; } } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(rating[j] > rating[i]) ans += grt[j]; else ans += les[j]; } } return ans; } };
// counting bigger / smaller elements // if after rating[i] has X bigger elements, // and each element has Y bigger elements after them // hence total elements that has i < j < k and rating[i] < rating[j] < rating[k] // same for the number of smaller elements // so the key point here is to know how many elements // that smaller and bigger than the current number var numTeams = function(rating) { // save total number of elements after i // that smaller than rating[i] let big = new Array(rating.length).fill(0) let n = rating.length; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { if (rating[j] > rating[i]) big[i]++; } } let count = 0; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { if (rating[j] > rating[i]) count += big[j] // because all elements are unique, so // we don't need to calculate the number of smaller elements // because if there are X bigger elements after rating[i] // then there are (n - i - 1 - X) smaller elements after rating[i] // or small = n - i - 1 - big else count += n - j - 1 - big[j]; } } return count; }
Count Number of Teams
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] &lt; nums[i] for each index (1 &lt;= i &lt; nums.length). &nbsp; Example 1: Input: nums = [1,2,10,5,7] Output: true Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7]. [1,2,5,7] is strictly increasing, so return true. Example 2: Input: nums = [2,3,1,2] Output: false Explanation: [3,1,2] is the result of removing the element at index 0. [2,1,2] is the result of removing the element at index 1. [2,3,2] is the result of removing the element at index 2. [2,3,1] is the result of removing the element at index 3. No resulting array is strictly increasing, so return false. Example 3: Input: nums = [1,1,1] Output: false Explanation: The result of removing any element is [1,1]. [1,1] is not strictly increasing, so return false. &nbsp; Constraints: 2 &lt;= nums.length &lt;= 1000 1 &lt;= nums[i] &lt;= 1000
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: indx = -1 count = 0 n = len(nums) # count the number of non-increasing elements for i in range(n-1): if nums[i] >= nums[i+1]: indx = i count += 1 #the cases explained above if count==0: return True if count == 1: if indx == 0 or indx == n-2: return True if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]): return True return False
class Solution { public boolean canBeIncreasing(int[] nums) { int count=0; int p=0; for(int i=0;i<nums.length-1;i++){ if(nums[i]>nums[i+1] || nums[i]==nums[i+1]) { count++; p=i; } } if(count>1) return false; else if(count==1){ if(p==0 || p== nums.length-2) return true; if(nums[p+1]>nums[p-1] || nums[p+2]>nums[p]) return true; else return false; } return true; } }
class Solution { public: bool canBeIncreasing(vector<int>& nums) { int count = 0; for (int i = 1; i < nums.size(); ++i) { if (nums[i] <= nums[i - 1]) { if (count == 1) return false; count++; if (i > 1 && nums[i] <= nums[i - 2] ) nums[i] = nums[i - 1]; } } return true; } };
var canBeIncreasing = function(nums) { for (let i = 1, used = false, prev = nums[0]; i < nums.length; i++) { if (nums[i] > prev) { prev = nums[i]; continue } if (used) return false; used = true; (i === 1 || nums[i] > nums[i - 2]) && (prev = nums[i]); } return true; };
Remove One Element to Make the Array Strictly Increasing
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice. Note that the digits '0' and '1' do not map to any letters, so Alice does not use them. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. For example, when Alice sent the message "bob", Bob received the string "2266622". Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent. Since the answer may be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: pressedKeys = "22233" Output: 8 Explanation: The possible text messages Alice could have sent are: "aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce". Since there are 8 possible messages, we return 8. Example 2: Input: pressedKeys = "222222222222222222222222222222222222" Output: 82876089 Explanation: There are 2082876103 possible text messages Alice could have sent. Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089. &nbsp; Constraints: 1 &lt;= pressedKeys.length &lt;= 105 pressedKeys only consists of digits from '2' - '9'.
class Solution(object): def countTexts(self, pressedKeys): """ :type pressedKeys: str :rtype: int """ dp = [1] + [0]*len(pressedKeys) mod = 10**9 + 7 for i, n in enumerate(pressedKeys): dp[i+1] = dp[i] # check if is continous if i >= 1 and pressedKeys[i-1] == n: dp[i+1] += dp[i-1] dp[i+1] %= mod if i >= 2 and pressedKeys[i-2] == n: dp[i+1] += dp[i-2] dp[i+1] %= mod # Special case for '7' and '9' that can have 4 characters combination if i >= 3 and pressedKeys[i-3] == n and (n == "7" or n == "9"): dp[i+1] += dp[i-3] dp[i+1] %= mod return dp[-1]
class Solution { int mod = (1000000007); public int countTexts(String pressedKeys) { int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 }; int n = pressedKeys.length(); return solve(0,pressedKeys,key); } public int solve(int ind, String s, int[] key) { if (ind == s.length()) { return 1; } int count = 0; int num = s.charAt(ind) - '0'; int rep = key[num]; for (int i = 0; i < rep && ind + i < s.length() && s.charAt(ind) == s.charAt(ind + i); i++) { count += solve(ind + 1 + i, s, key); count %= mod; } return count; } }
class Solution { public: int mod = 1e9+7; int solve(string &str, int idx) { if(idx == str.length()) return 1; int maxKeyPress = (str[idx] == '7' || str[idx] == '9') ? 4 : 3; long long currIndex = idx, pressFrequency = 1, ans = 0; while(pressFrequency <= maxKeyPress && str[currIndex] == str[idx]) { ++currIndex; ++pressFrequency; ans += solve(str, currIndex) % mod; } return ans%mod; } int countTexts(string pressedKeys) { return solve(pressedKeys, 0) % mod; } };
var countTexts = function(pressedKeys) { const MOD = 1e9 + 7; const n = pressedKeys.length; const dp = new Array(n + 1).fill(0); dp[0] = 1; let lastChar = ""; let repeatCount = 0; for (let i = 1; i <= n; ++i) { const currChar = pressedKeys[i - 1]; if (currChar != lastChar) repeatCount = 0; lastChar = currChar; repeatCount += 1; dp[i] = (dp[i] + dp[i - 1]) % MOD; if (i >= 2 && repeatCount >= 2) dp[i] = (dp[i] + dp[i - 2]) % MOD; if (i >= 3 && repeatCount >= 3) dp[i] = (dp[i] + dp[i - 3]) % MOD; if ((currChar == "7" || currChar == "9") && i >= 4 && repeatCount >= 4) dp[i] = (dp[i] + dp[i - 4]) % MOD; } return dp[n]; };
Count Number of Texts
You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. &nbsp; Example 1: Input: s = "bab", t = "aba" Output: 1 Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. Example 2: Input: s = "leetcode", t = "practice" Output: 5 Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. Example 3: Input: s = "anagram", t = "mangaar" Output: 0 Explanation: "anagram" and "mangaar" are anagrams. &nbsp; Constraints: 1 &lt;= s.length &lt;= 5 * 104 s.length == t.length s and t consist of lowercase English letters only.
class Solution: def minSteps(self, s: str, t: str) -> int: for ch in s: # Find and replace only one occurence of this character in t t = t.replace(ch, '', 1) return len(t)
//find the frequency of every letter and check diffrence between the frequency of each letter then divide it by 2 to calculate the minimum number of letter to be changed. class Solution { public int minSteps(String s, String t) { int sf[]=new int[26]; int tf[]=new int[26]; int diff=0; for(char c:s.toCharArray()){ sf[c-'a']++; } for(char c:t.toCharArray()){ tf[c-'a']++; } for(int i=0;i<26;i++){ diff+=(int)Math.abs(sf[i]-tf[i]); } return diff/2; } }
class Solution { public: int minSteps(string s, string t) { int count = 0, length = s.length(); vector<int> vec1(26, 0), vec2(26, 0); for(int i = 0; i < length; ++i){ vec1[s[i] - 'a']++; vec2[t[i] - 'a']++; } for(int i = 0; i < 26; ++i){ if(vec1[i] > vec2[i]) count += vec1[i] - vec2[i]; } return count; } };
var minSteps = function(s, t) { let hash1 = hash(s); let hash2 = hash(t); let steps = 0; for(let key of Object.keys(hash1)) { if( hash2[key]) { hash1[key] = hash1[key] - hash2[key]; } if( hash1[key] > 0 ) { steps += hash1[key]; } } return steps; }; function hash(str) { let hash = {}; for(let i=0; i<str.length; i++) { let letter = str[i]; if( hash[letter] ) { hash[letter]++; } else { hash[letter] = 1; } } return hash; }
Minimum Number of Steps to Make Two Strings Anagram