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
There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain.   Example 1: Input: stoneValue = [6,2,3,4,5,5] Output: 18 Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11. In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5). The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row. Example 2: Input: stoneValue = [7,7,7,7,7,7,7] Output: 28 Example 3: Input: stoneValue = [4] Output: 0   Constraints: 1 <= stoneValue.length <= 500 1 <= stoneValue[i] <= 106
from collections import defaultdict from itertools import accumulate class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: n = len(stoneValue) dp = [[0]*n for _ in range(n)] left = [[0]*n for _ in range(n)] prefix = list(accumulate(stoneValue)) prefix = [0]+prefix+[prefix[-1]] def sum(i,j): return prefix[j+1]-prefix[i] row_idx = [i for i in range(n)] for i in range(n): left[i][i] = stoneValue[i] for d in range(1,n): for i in range(n-d): j = i+d while sum(i,row_idx[i]) < sum(row_idx[i]+1,j): row_idx[i] +=1 if sum(i, row_idx[i]) == sum(row_idx[i]+1,j): dp[i][j] = max(left[i][row_idx[i]], left[j][row_idx[i]+1]) else: if row_idx[i] == i: dp[i][j] = left[j][i+1] elif row_idx[i] == j: dp[i][j] = left[i][j-1] else: dp[i][j] = max(left[i][row_idx[i]-1], left[j][row_idx[i]+1]) left[j][i] = max(left[j][i+1],sum(i,j)+dp[i][j]) left[i][j] = max(left[i][j-1],sum(i,j)+dp[i][j]) return dp[0][n-1]
class Solution { int dp[][]; public int fnc(int a[], int i, int j, int sum){ //System.out.println(i+" "+j); int n=a.length; if(i>j) return 0; if(j>n) return 0; if(i==j){ dp[i][j]=-1; return 0; } if(dp[i][j]!=0) return dp[i][j]; int temp=0; int ans=Integer.MIN_VALUE; for(int index=i;index<=j;index++){ temp+=a[index]; if(temp>sum-temp){ ans=Math.max(ans,((sum-temp)+fnc(a,index+1,j,sum-temp))); } else if(temp<sum-temp){ ans=Math.max(ans,temp+fnc(a,i,index,temp)); } else ans=Math.max(ans,Math.max(sum-temp+fnc(a,index+1,j,sum-temp),temp+fnc(a,i,index,temp))); } dp[i][j]=ans; return dp[i][j]; } public int stoneGameV(int[] stoneValue) { int n=stoneValue.length; int sum=0; for(int ele:stoneValue) sum+=ele; dp= new int[n][n]; return fnc(stoneValue,0,n-1,sum); } }
class Solution { public: int dp[501][501]; int f(vector<int> &v,int i,int j){ if(i>=j) return 0; if(dp[i][j]!=-1) return dp[i][j]; int r=0; for(int k=i;k<=j;k++) r+=v[k]; int l=0,ans=0; for(int k=i;k<=j;k++){ l+=v[k]; r-=v[k]; if(l<r) ans=max(ans,l+f(v,i,k)); else if(r<l) ans=max(ans,r+f(v,k+1,j)); else ans=max(ans,max(l+f(v,i,k),r+f(v,k+1,j))); } return dp[i][j]=ans; } int stoneGameV(vector<int>& stoneValue) { memset(dp,-1,sizeof(dp)); return f(stoneValue,0,stoneValue.size()-1); } };
var stoneGameV = function(stoneValue) { // Find the stoneValue array's prefix sum let prefix = Array(stoneValue.length).fill(0); for (let i = 0; i < stoneValue.length; i++) { prefix[i] = stoneValue[i] + (prefix[i - 1] || 0); } let dp = Array(stoneValue.length).fill().map(() => Array(stoneValue.length).fill(0)); function game(start, end) { if (dp[start][end]) return dp[start][end]; if (start === end) return 0; let max = 0; for (let i = start + 1; i <= end; i++) { let sumL = prefix[i - 1] - (prefix[start - 1] || 0); let sumR = prefix[end] - (prefix[i - 1] || 0); if (sumL > sumR) { max = Math.max(max, sumR + game(i, end)); } else if (sumL < sumR) { max = Math.max(max, sumL + game(start, i - 1)); } else { // If tied, check both rows let left = sumR + game(i, end); let right = sumL + game(start, i - 1); max = Math.max(max, left, right); } } return dp[start][end] = max; } return game(0, stoneValue.length - 1); };
Stone Game V
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. &nbsp; Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false &nbsp; Constraints: -231 &lt;= n &lt;= 231 - 1 &nbsp; Follow up: Could you solve it without loops/recursion?
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n == 0: return False k = n while k != 1: if k % 2 != 0: return False k = k // 2 return True count = 0 for i in range(33): mask = 1 << i if mask & n: count += 1 if count > 1: return False if count == 1: return True return False
class Solution { public boolean isPowerOfTwo(int n) { return power2(0,n); } public boolean power2(int index,int n){ if(Math.pow(2,index)==n) return true; if(Math.pow(2,index)>n) return false; return power2(index+1,n); } }
class Solution { public: bool isPowerOfTwo(int n) { if(n==0) return false; while(n%2==0) n/=2; return n==1; } };
var isPowerOfTwo = function(n) { let i=1; while(i<n){ i*=2 }return i===n };
Power of Two
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. &nbsp; Example 1: Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: Input: n = 1 Output: [["Q"]] &nbsp; Constraints: 1 &lt;= n &lt;= 9
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: coord = self.findNextRows(0, n) ans = [] for c in coord: temp = [] for j in c: temp.append("."*j+"Q"+"."*(n-j-1)) ans.append(temp) return ans def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()): ''' h_occ: occupied horizontal coordinate d_occ: occupied diagonal ad_occ: occupied anti-diagonal ''' ans = [] if i==n: return [[]] for j in range(n): if (j not in h_occ) and (j-i not in d_occ) and ((j-n+1)+i not in ad_occ): h_occ.add(j) d_occ.add(j-i) ad_occ.add((j-n+1)+i) temp = self.findNextRows(i+1, n, h_occ, d_occ, ad_occ) h_occ.remove(j) d_occ.remove(j-i) ad_occ.remove((j-n+1)+i) ans += [[j]+l for l in temp] return ans
Simple backtracking logic, try out each row and col and check position is valid or not. since we are going row one by one, there is no way queen is placed in that row. so, we need to check col, diagonals for valid position. // col is straightforward flag for each column // dia1 // 0 1 2 3 // 1 2 3 4 // 2 3 4 5 // 3 4 5 6 // dia2 // 0 -1 -2 -3 // 1 0 -1 -2 // 2 1 0 -1 // 3 2 1 0 negative numbers are not allowed as index, so we add n - 1 to diagonal2. class Solution { List<List<String>> ans = new LinkedList<>(); int n; public List<List<String>> solveNQueens(int n) { this.n = n; int[][] board = new int[n][n]; boolean[] col = new boolean[n]; boolean[] dia1 = new boolean[2 * n]; boolean[] dia2 = new boolean[2 * n]; solve(0, col, dia1, dia2, board); return ans; } public void solve(int row, boolean[] col, boolean[] dia1, boolean[] dia2, int[][] board){ if(row == n){ copyBoardToAns(board); return; } // brute force all col in that row for(int i = 0; i < n; i++){ if(isValid(col, dia1, dia2, i, row)){ col[i] = true; dia1[row + i] = true; dia2[row - i + n - 1] = true; board[row][i] = 1; solve(row + 1, col, dia1, dia2, board); col[i] = false; dia1[row + i] = false; dia2[row - i + n - 1] = false; board[row][i] = 0; } } } public boolean isValid(boolean[] col, boolean[] dia1, boolean[] dia2, int curCol, int curRow){ return !col[curCol] && !dia1[curCol + curRow] && !dia2[curRow - curCol + n - 1]; } public void copyBoardToAns(int[][] board){ List<String> res = new LinkedList<>(); for(int i = 0; i < n; i++){ String row = ""; for(int j = 0; j < n; j++){ if(board[i][j] == 1){ row += "Q"; }else{ row += "."; } } res.add(row); } ans.add(res); } }
class Solution { bool isSafe(vector<string> board, int row, int col, int n){ int r=row; int c=col; // Checking for upper left diagonal while(row>=0 && col>=0){ if(board[row][col]=='Q') return false; row--; col--; } row=r; col=c; // Checking for left while(col>=0){ if(board[row][col]=='Q') return false; col--; } row=r; col=c; // Checking for lower left diagonal while(row<n && col>=0){ if(board[row][col]=='Q') return false; row++; col--; } return true; } void solve(vector<vector<string>> &ans, vector<string> &board, int n, int col){ if(col==n){ ans.push_back(board); return; } for(int row=0;row<n;row++){ if(isSafe(board,row,col,n)){ board[row][col]='Q'; solve(ans,board,n,col+1); board[row][col]='.'; } } } public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> ans; vector<string> board; string s(n,'.'); for(int i=0;i<n;i++) board.push_back(s); solve(ans,board,n,0); return ans; } };
// time O(n!) | space O(n^n) var solveNQueens = function(n) { let res = []; function backtrack(board, r) { if (r === n) { // - 1 to account for adding a Q that takes up a space res.push(board.map((c) => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1))); return; } for (let c = 0; c < n; c++) { // bc is the current element // br is the index of the element bc // // bc === c | checks row and col // bc === c - r + br | checks lower diagonal // bc === c + r - br | checks upper diagonal if (!board.some((bc, br) => bc === c || bc === c - r + br || bc === c + r - br)) { backtrack(board.concat(c), r + 1); } } } backtrack([], 0); return res; };
N-Queens
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation. &nbsp; Example 1: Input: nums = [3,4,5,1,2] Output: true Explanation: [1,2,3,4,5] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. Example 2: Input: nums = [2,1,3,4] Output: false Explanation: There is no sorted array once rotated that can make nums. Example 3: Input: nums = [1,2,3] Output: true Explanation: [1,2,3] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 1 &lt;= nums[i] &lt;= 100
class Solution: def check(self, num: List[int]) -> bool: ct=0 for i in range(1,len(num)): if num[i-1]>num[i]: ct+=1 if num[len(num)-1]>num[0]: ct+=1 return ct<=1
class Solution { public boolean check(int[] nums) { // here we compare all the neighbouring elemnts and check whether they are in somewhat sorted // there will be a small change due to rotation in the array at only one place. // so if there are irregularities more than once, return false // else return true; int irregularities = 0; int length = nums.length; for (int i=0; i<length; i++) { if (nums[i] > nums[(i + 1) % length]) irregularities += 1; } return irregularities > 1 ? false : true; } }
class Solution { public: bool check(vector<int>& nums) { int count=0; for(int i=0;i<nums.size();i++){ if(nums[i]>nums[(i+1)%nums.size()]) count++; } return (count<=1); } };
var check = function(nums) { let decreased = false for (let i = 1; i < nums.length; i += 1) { if (nums[i] < nums[i - 1]) { if (decreased) { return false } decreased = true } } return decreased ? nums[0] >= nums[nums.length - 1] : true };
Check if Array Is Sorted and Rotated
Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). &nbsp; Example 1: Input: mat = [[1,0,0],[0,0,1],[1,0,0]] Output: 1 Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2: Input: mat = [[1,0,0],[0,1,0],[0,0,1]] Output: 3 Explanation: (0, 0), (1, 1) and (2, 2) are special positions. &nbsp; Constraints: m == mat.length n == mat[i].length 1 &lt;= m, n &lt;= 100 mat[i][j] is either 0 or 1.
class Solution(object): def numSpecial(self, mat): """ :type mat: List[List[int]] :rtype: int """ r=len(mat) c=len(mat[0]) r_c={} l_c={} for i in range(r): flag=0 for j in range(c): if(mat[i][j]==1): flag+=1 r_c[i]=flag for i in range(c): flag=0 for j in range(r): if(mat[j][i]==1): flag+=1 l_c[i]=flag ret=0 for i in range(r): for j in range(c): if(mat[i][j]==1 and l_c[j]==1 and r_c[i]==1): ret+=1 return ret
class Solution { public int numSpecial(int[][] mat) { int count=0; for(int i=0;i<mat.length;i++){ for(int j=0;j<mat[0].length;j++){ if(mat[i][j]==1){ int flag=0; for(int k=0;k<mat.length;k++){ if(mat[k][j]!=0 && k!=i){ flag=1;break; } } if(flag==1) continue; for(int k=0;k<mat[0].length;k++){ if(mat[i][k]!=0 && k!=j){ flag=1; break; } } if(flag==0) count++; } } } return count; } }
class Solution { public: int numSpecial(vector<vector<int>>& mat) { vector<vector<int>>v; map<int,vector<int>>m; for(int i=0;i<mat.size();i++){ vector<int>temp = mat[i]; for(int j=0;j<temp.size();j++){ m[j].push_back(temp[j]); } } for(auto i:m){ v.push_back(i.second); } int counter = 0; for(int i=0;i<mat.size();i++){ int onecount = 0; int column = 0; for(int j=0;j<mat[i].size();j++){ if(mat[i][j]==1){ column = j; onecount++; } } if(onecount==1){ int countone = 0; vector<int>temp = v[column]; for(auto i:temp){ if(i==1){ countone++; } } if(countone==1){ counter++; } } } return counter; } };
/** * @param {number[][]} mat * @return {number} */ var numSpecial = function(mat) { let specialPostions = []; for(let i in mat){ for(let j in mat[i]){ if(mat[i][j] == 1 ){ let horizontalOnes = 0; let verticalOnes = 0; for(let k in mat[i]){ if(k != j && mat[i][k] == 1){ horizontalOnes++; } } for(let k = 0 ; k < mat.length ; k++ ){ if(k != i && mat[k][j] == 1){ verticalOnes++; } } if(horizontalOnes == 0 && verticalOnes == 0){ specialPostions.push([i,j]); } } } } return specialPostions.length; };
Special Positions in a Binary Matrix
Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: MyCircularDeque(int k) Initializes the deque with a maximum size of k. boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise. boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise. boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise. boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise. int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. boolean isEmpty() Returns true if the deque is empty, or false otherwise. boolean isFull() Returns true if the deque is full, or false otherwise. &nbsp; Example 1: Input ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"] [[3], [1], [2], [3], [4], [], [], [], [4], []] Output [null, true, true, true, false, 2, true, true, true, 4] Explanation MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 &nbsp; Constraints: 1 &lt;= k &lt;= 1000 0 &lt;= value &lt;= 1000 At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.
class MyCircularDeque { public: deque<int> dq; int max_size; MyCircularDeque(int k) { max_size = k; } bool insertFront(int value) { if(dq.size() < max_size) { dq.push_front(value); return true; } return false; } bool insertLast(int value) { if(dq.size() < max_size) { dq.push_back(value); return true; } return false; } bool deleteFront() { if(dq.size() > 0) { dq.pop_front(); return true; } return false; } bool deleteLast() { if(dq.size() > 0) { dq.pop_back(); return true; } return false; } int getFront() { if(dq.size() > 0) return dq.front(); return -1; } int getRear() { if(dq.size() > 0) return dq.back(); return -1; } bool isEmpty() { return dq.empty(); } bool isFull() { return dq.size() == max_size; } };
class MyCircularDeque { public: deque<int> dq; int max_size; MyCircularDeque(int k) { max_size = k; } bool insertFront(int value) { if(dq.size() < max_size) { dq.push_front(value); return true; } return false; } bool insertLast(int value) { if(dq.size() < max_size) { dq.push_back(value); return true; } return false; } bool deleteFront() { if(dq.size() > 0) { dq.pop_front(); return true; } return false; } bool deleteLast() { if(dq.size() > 0) { dq.pop_back(); return true; } return false; } int getFront() { if(dq.size() > 0) return dq.front(); return -1; } int getRear() { if(dq.size() > 0) return dq.back(); return -1; } bool isEmpty() { return dq.empty(); } bool isFull() { return dq.size() == max_size; } };
class MyCircularDeque { public: deque<int> dq; int max_size; MyCircularDeque(int k) { max_size = k; } bool insertFront(int value) { if(dq.size() < max_size) { dq.push_front(value); return true; } return false; } bool insertLast(int value) { if(dq.size() < max_size) { dq.push_back(value); return true; } return false; } bool deleteFront() { if(dq.size() > 0) { dq.pop_front(); return true; } return false; } bool deleteLast() { if(dq.size() > 0) { dq.pop_back(); return true; } return false; } int getFront() { if(dq.size() > 0) return dq.front(); return -1; } int getRear() { if(dq.size() > 0) return dq.back(); return -1; } bool isEmpty() { return dq.empty(); } bool isFull() { return dq.size() == max_size; } };
class MyCircularDeque { public: deque<int> dq; int max_size; MyCircularDeque(int k) { max_size = k; } bool insertFront(int value) { if(dq.size() < max_size) { dq.push_front(value); return true; } return false; } bool insertLast(int value) { if(dq.size() < max_size) { dq.push_back(value); return true; } return false; } bool deleteFront() { if(dq.size() > 0) { dq.pop_front(); return true; } return false; } bool deleteLast() { if(dq.size() > 0) { dq.pop_back(); return true; } return false; } int getFront() { if(dq.size() > 0) return dq.front(); return -1; } int getRear() { if(dq.size() > 0) return dq.back(); return -1; } bool isEmpty() { return dq.empty(); } bool isFull() { return dq.size() == max_size; } };
Design Circular Deque
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1. Given an array nums, return the sum of all XOR totals for every subset of nums.&nbsp; Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. &nbsp; Example 1: Input: nums = [1,3] Output: 6 Explanation: The 4 subsets of [1,3] are: - The empty subset has an XOR total of 0. - [1] has an XOR total of 1. - [3] has an XOR total of 3. - [1,3] has an XOR total of 1 XOR 3 = 2. 0 + 1 + 3 + 2 = 6 Example 2: Input: nums = [5,1,6] Output: 28 Explanation: The 8 subsets of [5,1,6] are: - The empty subset has an XOR total of 0. - [5] has an XOR total of 5. - [1] has an XOR total of 1. - [6] has an XOR total of 6. - [5,1] has an XOR total of 5 XOR 1 = 4. - [5,6] has an XOR total of 5 XOR 6 = 3. - [1,6] has an XOR total of 1 XOR 6 = 7. - [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2. 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 Example 3: Input: nums = [3,4,5,6,7,8] Output: 480 Explanation: The sum of all XOR totals for every subset is 480. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 12 1 &lt;= nums[i] &lt;= 20
class Solution: def subsetXORSum(self, nums: List[int]) -> int: def sums(term, idx): if idx == len(nums): return term return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1) return sums(0, 0)
class Solution { int sum=0; public int subsetXORSum(int[] nums) { sum=0; return getAns(nums,0,0); } int getAns(int[] arr,int i,int cur){ if(i==arr.length){ return cur; } return getAns(arr,i+1,cur^arr[i]) + getAns(arr,i+1,cur); } }
class Solution { public: int subsetXORSum(vector<int>& nums) { int ans=0; for(int i=0; i<32; i++) { int mask=1<<i; int count=0; for(int j=0; j<nums.size(); j++) { if(nums[j]&mask) count++; } if(count) { ans+=mask*(1<<(count-1))*(1<<(nums.size()-count)); } } return ans; } };
var subsetXORSum = function(nums) { let output=[]; backtrack(); return output.reduce((a,b)=>a+b); function backtrack(start = 0, arr=[nums[0]]){ output.push([...arr].reduce((a,b)=>a^b,0)); for(let i=start; i<nums.length; i++){ arr.push(nums[i]); backtrack(i+1, arr); arr.pop(); } } };
Sum of All Subset XOR Totals
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance. The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 Output: 60 Explanation: We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60. Example 2: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 Output: 68 Explanation: This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68. Example 3: Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 Output: 72 &nbsp; Constraints: 1 &lt;= k &lt;= n &lt;= 105 speed.length == n efficiency.length == n 1 &lt;= speed[i] &lt;= 105 1 &lt;= efficiency[i] &lt;= 108
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: l = list(zip(efficiency,speed)) l.sort(reverse=True) h = [] res = 0 mod = 1000000007 mx_sum = 0 print(l) for i in range(n): res = max(res , (mx_sum+l[i][1])*l[i][0]) if len(h)<k-1: heappush(h,l[i][1]) mx_sum+=l[i][1] elif k!=1: x=0 if h: x = heappop(h) heappush(h,max(x,l[i][1])) mx_sum = mx_sum - x + max(x,l[i][1]) return res%mod
class Engineer { int speed, efficiency; Engineer(int speed, int efficiency) { this.speed = speed; this.efficiency = efficiency; } } class Solution { public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { List<Engineer> engineers = new ArrayList<>(); for(int i=0;i<n;i++) { engineers.add(new Engineer(speed[i], efficiency[i])); } engineers.sort((a, b) -> b.efficiency - a.efficiency); PriorityQueue<Engineer> maxHeap = new PriorityQueue<>((a,b) -> a.speed - b.speed); long maxPerformance = 0l, totalSpeed = 0l; for(Engineer engineer: engineers) { if(maxHeap.size() == k) { totalSpeed -= maxHeap.poll().speed; } totalSpeed += engineer.speed; maxHeap.offer(engineer); maxPerformance = Math.max(maxPerformance, totalSpeed * (long)engineer.efficiency); } return (int)(maxPerformance % 1_000_000_007); } }
class Solution { public: int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) { priority_queue<int, vector<int>, greater<int>> pq; long long sum = 0, ans = 0; const int m = 1e9 + 7; vector<vector<int>> pairs(n, vector<int> (2, 0)); for(int i = 0; i < n; i++) pairs[i] = {efficiency[i], speed[i]}; sort(pairs.rbegin(), pairs.rend()); for(int i = 0; i < n; i++){ sum += pairs[i][1]; pq.push(pairs[i][1]); ans = max(ans,sum * pairs[i][0]); if(pq.size() >= k){ sum -= pq.top(); pq.pop(); } } return ans%(m); } };
var maxPerformance = function(n, speed, efficiency, k) { let ord = Array.from({length: n}, (_,i) => i) ord.sort((a,b) => efficiency[b] - efficiency[a]) let sppq = new MinPriorityQueue(), totalSpeed = 0n, best = 0n for (let eng of ord) { sppq.enqueue(speed[eng]) if (sppq.size() <= k) totalSpeed += BigInt(speed[eng]) else totalSpeed += BigInt(speed[eng] - sppq.dequeue().element) let res = totalSpeed * BigInt(efficiency[eng]) if (res > best) best = res } return best % 1000000007n };
Maximum Performance of a Team
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. &nbsp; Example 1: Input: n = 5, ranges = [3,4,1,1,0,0] Output: 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5] Example 2: Input: n = 3, ranges = [0,0,0,0] Output: -1 Explanation: Even if you activate all the four taps you cannot water the whole garden. &nbsp; Constraints: 1 &lt;= n &lt;= 104 ranges.length == n + 1 0 &lt;= ranges[i] &lt;= 100
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: maxRanges = [0] for i in range(len(ranges)): minIdx = max(i - ranges[i], 0) maxIdx = min(i + ranges[i], n) idx = bisect_left(maxRanges, minIdx) if idx == len(maxRanges) or maxIdx <= maxRanges[idx]: continue if idx == len(maxRanges) - 1: maxRanges.append(maxIdx) else: maxRanges[idx + 1] = max(maxRanges[idx + 1], maxIdx) if maxRanges[-1] < n: return -1 else: return len(maxRanges) - 1
class Solution { public int minTaps(int n, int[] ranges) { Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new); Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o])); int ans = 1, cur = 0, end = 0; for (int i = 0;i<ranges.length&&end<n;i++){ int j = idx[i]; if (j-ranges[j]>cur){ cur=end; ans++; } if (j-ranges[j]<=cur){ end=Math.max(end, j+ranges[j]); } } return end<n?-1:ans; } }
class Solution { public: int minTaps(int n, vector<int>& ranges) { vector<pair<int,int>> v; for(int i=0;i<ranges.size();i++){ // making ranges v.push_back({i-ranges[i],i+ranges[i]}); } // sorting the intervals sort(v.begin(),v.end()); // to keep track from where we need to cover int uncovered = 0; int idx = 0; // number of ranges used int cnt = 0; // to check if its possible bool ok = true; // as long as we have not covered the garden while(uncovered<n){ // we will try to cover the uncovered such that new uncovered is maximum possible int new_uncovered = uncovered; while(idx<n+1 && v[idx].first<=uncovered){ new_uncovered = max(new_uncovered,v[idx].second); idx++; } // we have used one range cnt++; // it means we were not able to cover with ranges so not possible if(new_uncovered == uncovered){ ok = false; break; } // updating uncovered for next iteration uncovered = new_uncovered; } if(ok) return cnt; return -1; } };
var minTaps = function(n, ranges) { let intervals = []; for (let i = 0; i < ranges.length; i++) { let l = i - ranges[i]; let r = i + ranges[i]; intervals.push([l, r]); } intervals.sort((a, b) => { if (a[0] === b[0]) return b[1] - a[1]; return a[0] - b[0]; }) // Find the starting idx let startIdx; for (let i = 0; i < intervals.length; i++) { let [s, e] = intervals[i]; if (s <= 0) { if (startIdx === undefined) startIdx = i; else if (intervals[startIdx][1] < e) startIdx = i; } else break; } if (startIdx === undefined) return -1; let q = [startIdx], openedTaps = 1; while (q.length) { let max; while (q.length) { let idx = q.pop(); let [start, end] = intervals[idx]; if (end >= n) return openedTaps; for (let i = idx + 1; i < intervals.length; i++) { let [nextStart, nextEnd] = intervals[i]; // If next interval's start is less than the current interval's end if (nextStart <= end) { if (!max && nextEnd > end) max = {i, end: nextEnd}; // If the next interval's end is greater than the current interval's end else if (max && nextEnd > max.end) max = {i, end: nextEnd}; } else break; } } if (max) { q.push(max.i); openedTaps++; } } return -1; };
Minimum Number of Taps to Open to Water a Garden
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. &nbsp; Example 1: Input: n = 12 Output: 21 Example 2: Input: n = 21 Output: -1 &nbsp; Constraints: 1 &lt;= n &lt;= 231 - 1
class Solution: def nextGreaterElement(self, n): digits = list(str(n)) i = len(digits) - 1 while i-1 >= 0 and digits[i] <= digits[i-1]: i -= 1 if i == 0: return -1 j = i while j+1 < len(digits) and digits[j+1] > digits[i-1]: j += 1 digits[i-1], digits[j] = digits[j], digits[i-1] digits[i:] = digits[i:][::-1] ret = int(''.join(digits)) return ret if ret < 1<<31 else -1
class Solution { public int nextGreaterElement(int n) { char[] arr = (n + "").toCharArray(); int i = arr.length - 1; while(i > 0){ if(arr[i-1] >= arr[i]){ i--; }else{ break; } } if(i == 0){ return -1; } int idx1 = i-1; int j = arr.length - 1; while(j > idx1){ if(arr[j] > arr[idx1]){ break; } j--; } //Swapping swap(arr,idx1,j); //sorting int left = idx1+1; int right = arr.length-1; while(left < right){ swap(arr,left,right); left++; right--; } String result = new String(arr); long val = Long.parseLong(result); return (val > Integer.MAX_VALUE ? -1 : (int)val); } void swap(char[]arr,int i,int j){ char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
class Solution { public: int nextGreaterElement(int n) { vector<int>vec; int temp = n; while(n>0){ int r = n%10; vec.push_back(r); n /= 10; } sort(vec.begin(),vec.end()); do{ int num=0; long j=0; int s = vec.size()-1; long i = pow(10,s); while(i>0) { num += i*vec[j++]; i /= 10; } if(num>temp) return num; } while(next_permutation(vec.begin(),vec.end())); return -1; } };
var nextGreaterElement = function(n) { const MAX_VALUE = 2 ** 31 - 1; const nums = `${n}`.split(''); let findPos; for (let index = nums.length - 2; index >= 0; index--) { if (nums[index] < nums[index + 1]) { findPos = index; break; } } if (findPos === undefined) return -1; for (let index = nums.length - 1; index >= 0; index--) { if (nums[index] > nums[findPos]) { [nums[index], nums[findPos]] = [nums[findPos], nums[index]]; break; } } const mantissa = nums.slice(findPos + 1).sort((a, b) => a - b).join(''); const result = Number(nums.slice(0, findPos + 1).join('') + mantissa); return result > MAX_VALUE ? -1 : result; };
Next Greater Element III
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n. All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server. Otherwise, no more resending will occur from this server. The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle. &nbsp; Example 1: Input: edges = [[0,1],[1,2]], patience = [0,2,1] Output: 8 Explanation: At (the beginning of) second 0, - Data server 1 sends its message (denoted 1A) to the master server. - Data server 2 sends its message (denoted 2A) to the master server. At second 1, - Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back. - Server 1 has not received any reply. 1 second (1 &lt; patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message. - Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B). At second 2, - The reply 1A arrives at server 1. No more resending will occur from server 1. - Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back. - Server 2 resends the message (denoted 2C). ... At second 4, - The reply 2A arrives at server 2. No more resending will occur from server 2. ... At second 7, reply 2D arrives at server 2. Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers. This is the time when the network becomes idle. Example 2: Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10] Output: 3 Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2. From the beginning of the second 3, the network becomes idle. &nbsp; Constraints: n == patience.length 2 &lt;= n &lt;= 105 patience[0] == 0 1 &lt;= patience[i] &lt;= 105 for 1 &lt;= i &lt; n 1 &lt;= edges.length &lt;= min(105, n * (n - 1) / 2) edges[i].length == 2 0 &lt;= ui, vi &lt; n ui != vi There are no duplicate edges. Each server can directly or indirectly reach another server.
class Solution: def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: #Build Adjency List adjList = defaultdict(list) for source, target in edges: adjList[source].append(target) adjList[target].append(source) #BFS to get the shortest route from node to master. shortest = {} queue = deque([(0,0)]) seen = set() while queue: currPos, currDist = queue.popleft() if currPos in seen: continue seen.add(currPos) shortest[currPos] = currDist for nei in adjList[currPos]: queue.append((nei, currDist+1)) #Calculate answer using shortest paths. ans = 0 for index in range(1,len(patience)): resendInterval = patience[index] #The server will stop sending requests after it's been sent to the master node and back. shutOffTime = (shortest[index] * 2) # shutOffTime-1 == Last second the server can send a re-request. lastSecond = shutOffTime-1 #Calculate the last time a packet is actually resent. lastResentTime = (lastSecond//resendInterval)*resendInterval # At the last resent time, the packet still must go through 2 more cycles to the master node and back. lastPacketTime = lastResentTime + shutOffTime ans = max(lastPacketTime, ans) #Add +1, the current answer is the last time the packet is recieved by the target server (still active). #We must return the first second the network is idle, therefore + 1 return ans + 1
class Solution { public int networkBecomesIdle(int[][] edges, int[] patience) { int n = patience.length; // creating adjacency list ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for(int i = 0 ; i < n ; i++ ) { adj.add(new ArrayList<>()); } for(int[] edge : edges) { adj.get(edge[0]).add(edge[1]); adj.get(edge[1]).add(edge[0]); } // getting the distance array using dijkstra algorithm int[] dist = dijkstra(adj); // variable to store the result int ans = 0; // performing the calculations discussed above for each index for(int x = 1; x < n ; x++) { // round trip time int time = 2*dist[x]; int p = patience[x]; //total number of messages the station will send until it receives the reply of first message int numberOfMessagesSent = (time)/p; //handling an edge case if round trip time is a multiple of patience example time =24 patience = 4 //then the reply would be received at 24 therefore station will not send any message at t = 24 if(time%p == 0) { numberOfMessagesSent--; } // time of last message int lastMessage = numberOfMessagesSent*p; // updating the ans to store max of time at which the station becomes idle ans = Math.max(ans,lastMessage+ 2*dist[x]+1); } return ans; } // simple dijkstra algorithm implementation private int[] dijkstra(ArrayList<ArrayList<Integer>> adj) { int n = adj.size(); int[] dist = new int[n]; boolean[] visited = new boolean[n]; Arrays.fill(dist,Integer.MAX_VALUE); dist[0] = 0; PriorityQueue<int[]> pq = new PriorityQueue<>((o1,o2)->o1[1]-o2[1]); pq.add(new int[]{0,0}); while(!pq.isEmpty()) { int[] node = pq.remove(); if(!visited[node[0]]) { visited[node[0]] = true; for(int nbr : adj.get(node[0])) { if(dist[nbr] > dist[node[0]]+1) { dist[nbr] = dist[node[0]]+1; pq.add(new int[]{nbr,dist[nbr]}); } } } } return dist; } }
class Solution { public: int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) { int n = patience.size(); vector <vector <int>> graph(n); vector <int> time(n, -1); for(auto x: edges) { // create adjacency list graph[x[0]].push_back(x[1]); graph[x[1]].push_back(x[0]); } queue <int> q; q.push(0); time[0] = 0; while(q.size()) { int node = q.front(); q.pop(); for(auto child: graph[node]) { if(time[child] == -1) { // if not visited. time[child] = time[node] + 1; // calc time for child node q.push(child); } } } int res = 0; for(int i = 1; i<n; i++) { int extraPayload = (time[i]*2 - 1)/patience[i]; // extra number of payload before the first message arrive back to data server. // since a data server can only send a message before first message arrives back." // and first message arrives at time[i]*2. so "(time[i]*2-1)" int lastOut = extraPayload * patience[i]; // find the last time when a data server sends a message int lastIn = lastOut + time[i]*2; // this is the result for current data server res = max(res, lastIn); } // at "res" time the last message has arrived at one of the data servers. // so at res+1 no message will be passing between servers. return res+1; } };
/** * @param {number[][]} edges * @param {number[]} patience * @return {number} */ var networkBecomesIdle = function(edges, patience) { /* Approach: Lets call D is the distance from node to master And last message sent from node is at T Then last message will travel till D+T and network will be idal at D+T+1 */ let edgesMap={},minDistanceFromMasterArr=[],ans=0,visited={}; for(let i=0;i<edges.length;i++){ if(edgesMap[edges[i][0]]===undefined){ edgesMap[edges[i][0]] = []; } edgesMap[edges[i][0]].push(edges[i][1]); if(edgesMap[edges[i][1]]===undefined){ edgesMap[edges[i][1]] = []; } edgesMap[edges[i][1]].push(edges[i][0]); } let queue=[],node,neighbour; minDistanceFromMasterArr[0]=0;//Distance of source to source is 0 queue.push(0); while(queue[0]!==undefined){ node = queue.shift(); for(let i=0;i<edgesMap[node].length;i++){ neighbour = edgesMap[node][i]; if(minDistanceFromMasterArr[neighbour]===undefined){ minDistanceFromMasterArr[neighbour] = minDistanceFromMasterArr[node] + 1; queue.push(neighbour); } } } for(let i=1;i<patience.length;i++){ let responseWillBeReceivedAt = minDistanceFromMasterArr[i]*2; let lastMessageSentAt; if(patience[i]<responseWillBeReceivedAt){ lastMessageSentAt = Math.floor((responseWillBeReceivedAt-1)/patience[i])*patience[i]; }else{ lastMessageSentAt=0; } let lastMessageWillTravelTill = lastMessageSentAt + responseWillBeReceivedAt; let firstIdleSecond = lastMessageWillTravelTill+1; ans = Math.max(ans,firstIdleSecond); } return ans; };
The Time When the Network Becomes Idle
There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of&nbsp;directly connected roads to either city. If a road is directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads, return the maximal network rank of the entire infrastructure. &nbsp; Example 1: Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]] Output: 4 Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. Example 2: Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]] Output: 5 Explanation: There are 5 roads that are connected to cities 1 or 2. Example 3: Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]] Output: 5 Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. &nbsp; Constraints: 2 &lt;= n &lt;= 100 0 &lt;= roads.length &lt;= n * (n - 1) / 2 roads[i].length == 2 0 &lt;= ai, bi&nbsp;&lt;= n-1 ai&nbsp;!=&nbsp;bi Each&nbsp;pair of cities has at most one road connecting them.
class Solution: def maximalNetworkRank(self, n: int, roads) -> int: max_rank = 0 connections = {i: set() for i in range(n)} for i, j in roads: connections[i].add(j) connections[j].add(i) for i in range(n - 1): for j in range(i + 1, n): max_rank = max(max_rank, len(connections[i]) + len(connections[j]) - (j in connections[i])) return max_rank
class Solution { public int maximalNetworkRank(int n, int[][] roads) { //number of road connected to city int[] numRoadsConnectedCity = new int[100 + 1]; //road exist between two two cities boolean[][] raadExist = new boolean[n][n]; for(int[] cities : roads){ //increment the count of numbers of connected city numRoadsConnectedCity[cities[0]]++; numRoadsConnectedCity[cities[1]]++; //mark road exist, between two cities raadExist[cities[0]][cities[1]] = true; raadExist[cities[1]][cities[0]] = true; } int maxRank = 0; for(int city1 = 0; city1 < n - 1; city1++){ for(int city2 = city1 + 1; city2 < n; city2++){ //count total number of road connected to both city int rank = numRoadsConnectedCity[city1] + numRoadsConnectedCity[city2]; //just decrement the rank, if both city connected if(raadExist[city1][city2]) rank--; maxRank = Math.max(maxRank, rank); } } return maxRank; } }
class Solution { public: int maximalNetworkRank(int n, vector<vector<int>>& roads) { vector<vector<int>>graph(n,vector<int>(n,0)); vector<int>degree(n,0); for(int i=0;i<roads.size();i++){ int u=roads[i][0]; int v=roads[i][1]; degree[u]++; degree[v]++; graph[u][v]=1; graph[v][u]=1; } int ans=0; for(int i=0;i<graph.size();i++){ for(int j=0;j<graph.size();j++){ if(j!=i){ int rank=degree[i]+degree[j]-graph[i][j]; ans=max(ans,rank); } } } return ans; } };
var maximalNetworkRank = function(n, roads) { let res = 0 let map = new Map() roads.forEach(([u,v])=>{ map.set(u, map.get(u) || new Set()) let set = map.get(u) set.add(v) map.set(v, map.get(v) || new Set()) set = map.get(v) set.add(u) }) for(let i=0;i<n;i++){ if(!map.has(i)) continue let uAdj = map.get(i) let uCount = uAdj.size; for(let j=i+1;j<n;j++){ if(!map.has(j)) continue let vAdj = map.get(j) let vCount = vAdj.size if(vAdj.has(i)) vCount-- res = Math.max(uCount+vCount, res) } } return res };
Maximal Network Rank
Implement pow(x, n), which calculates x raised to the power n (i.e., xn). &nbsp; Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 &nbsp; Constraints: -100.0 &lt; x &lt; 100.0 -231 &lt;= n &lt;= 231-1 -104 &lt;= xn &lt;= 104
class Solution: def myPow(self, x: float, n: int) -> float: self.x = x if n == 0: return 1 isInverted = False if n < 0: isInverted = True n = -1 * n result = self.pow(n) return result if not isInverted else 1 / result def pow(self, n): if n == 1: return self.x if n % 2 == 0: p = self.pow(n / 2) return p * p else: return self.x * self.pow(n-1)
class Solution { public double myPow(double x, int n) { if (n == 0) return 1; if (n == 1) return x; else if (n == -1) return 1 / x; double res = myPow(x, n / 2); if (n % 2 == 0) return res * res; else if (n % 2 == -1) return res * res * (1/x); else return res * res * x; } }
class Solution { public: double myPow(double x, int n) { if(n==0) return 1; //anything to the power 0 is 1 if(x==1 || n==1) return x; //1 to the power anything = 1 or x to the power 1 = x double ans = 1; long long int a = abs(n); //since int range is from -2147483648 to 2147483647, so it can't store absolute value of -2147483648 if(n<0){ //as 2^(-2) = 1/2^2 if(a%2 == 0) ans = 1/myPow(x*x,a/2); else ans = 1/(x * myPow(x,a-1)); } else{ if(a%2 == 0) ans = myPow(x*x,a/2); else ans = x * myPow(x,a-1); } return ans; } };
var myPow = function(x, n) { return x**n; };
Pow(x, n)
According to&nbsp;Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state. &nbsp; Example 1: Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2: Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]] &nbsp; Constraints: m == board.length n == board[i].length 1 &lt;= m, n &lt;= 25 board[i][j] is 0 or 1. &nbsp; Follow up: Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
#pattern actual update ref 0 0 0 1 1 1 0 1 -1 1 0 -2 class Solution: def gameOfLife(self, board: List[List[int]]) -> None: r = len(board) c = len(board[0]) ans = [[0]*c for _ in range(r)] neighs = [[1,0],[-1,0],[0,1],[0,-1],[-1,-1],[-1,1],[1,1],[1,-1]] for i in range(r): for j in range(c): livecnt,deadcnt = 0,0 for di,dj in neighs: if 0<=(i+di) < r and 0<=(j+dj)<c: if board[i+di][j+dj] == 0 or board[i+di][j+dj] == -1 : deadcnt+=1 else: livecnt+=1 if board[i][j] == 0: if livecnt == 3: board[i][j] = -1 else: if livecnt == 2 or livecnt==3: board[i][j] = 1 else: board[i][j] = -2 for i in range(r): for j in range(c): if board[i][j] == -1: board[i][j] = 1 elif board[i][j] == -2: board[i][j] = 0
class Solution { public void gameOfLife(int[][] board) { int m = board.length, n = board[0].length; int[][] next = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { next[i][j] = nextState(board, i, j, m, n); } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = next[i][j]; } } } public int nextState(int[][] board, int i, int j, int m, int n) { int ones = 0; for (int x = -1; x <=1; x++) { for (int y = -1; y <= 1; y++) { if (x == 0 && y == 0) { continue; } int a = i + x, b = j + y; if (a >= 0 && a < m) { if (b >= 0 && b < n) { ones += board[a][b]; } } } } if (board[i][j] == 0) { return ones == 3 ? 1 : 0; } else { if (ones == 2 || ones == 3) { return 1; } else { return 0; } } } }
// Idea: Encode the value into 2-bit value, the first bit is the value of next state, and the second bit is the value of current state class Solution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(); int n = board[0].size(); for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { encode(board, i, j); } } for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { board[i][j] >>= 1; } } } void encode(vector<vector<int>>& board, int row, int col) { int ones = 0; int zeros = 0; int m = board.size(); int n = board[0].size(); int cur = board[row][col]; if (row >= 1 && col >= 1) { ones += (board[row - 1][col - 1] & 1); zeros += !(board[row - 1][col - 1] & 1); } if (row >= 1) { ones += (board[row - 1][col] & 1); zeros += !(board[row - 1][col] & 1); } if (row >= 1 && col < n - 1) { ones += (board[row - 1][col + 1] & 1); zeros += !(board[row - 1][col + 1] & 1); } if (col < n - 1) { ones += (board[row][col + 1] & 1); zeros += !(board[row][col + 1] & 1); } if (row < m - 1 && col < n - 1) { ones += (board[row + 1][col + 1] & 1); zeros += !(board[row + 1][col + 1] & 1); } if (row < m - 1) { ones += (board[row + 1][col] & 1); zeros += !(board[row + 1][col] & 1); } if (row < m - 1 && col >= 1) { ones += (board[row + 1][col - 1] & 1); zeros += !(board[row + 1][col - 1] & 1); } if (col >= 1) { ones += (board[row][col - 1] & 1); zeros += !(board[row][col - 1] & 1); } if (ones < 2 && cur == 1) { cur += 0 << 1; } else if (ones >= 2 && ones <= 3 && cur == 1) { cur += 1 << 1; } else if (ones > 3 && cur == 1) { cur += 0 << 1; } else if (ones == 3 && cur == 0) { cur += 1 << 1; } else { cur += cur << 1; } board[row][col] = cur; } };
/** * @param {number[][]} board * @return {void} Do not return anything, modify board in-place instead. */ var gameOfLife = function(board) { const m = board.length, n = board[0].length; let copy = JSON.parse(JSON.stringify(board)); const getNeighbor = (row, col) => { let radius = [-1, 0, 1], count = 0; for(let i = 0; i < 3; i++) { for(let j = 0; j < 3; j++) { if(!(radius[i] == 0 && radius[j] == 0) && copy[row + radius[i]] && copy[row + radius[i]][col + radius[j]]) { let neighbor = copy[row + radius[i]][col + radius[j]]; if(neighbor == 1) { count++; } } } } return count; } for(let i = 0; i < m; i++) { for(let j = 0; j < n; j++) { const count = getNeighbor(i, j); if(copy[i][j] == 1) { if(count < 2 || count > 3) { board[i][j] = 0; } } else { if(count == 3) { board[i][j] = 1; } } } } };
Game of Life
You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: nums[0] = 0 nums[1] = 1 nums[2 * i] = nums[i] when 2 &lt;= 2 * i &lt;= n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 &lt;= 2 * i + 1 &lt;= n Return the maximum integer in the array nums​​​. &nbsp; Example 1: Input: n = 7 Output: 3 Explanation: According to the given rules: nums[0] = 0 nums[1] = 1 nums[(1 * 2) = 2] = nums[1] = 1 nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 nums[(2 * 2) = 4] = nums[2] = 1 nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 nums[(3 * 2) = 6] = nums[3] = 2 nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. Example 2: Input: n = 2 Output: 1 Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1. Example 3: Input: n = 3 Output: 2 Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2. &nbsp; Constraints: 0 &lt;= n &lt;= 100
class Solution: def getMaximumGenerated(self, n): nums = [0]*(n+2) nums[1] = 1 for i in range(2, n+1): nums[i] = nums[i//2] + nums[(i//2)+1] * (i%2) return max(nums[:n+1])
class Solution { public int getMaximumGenerated(int n) { if(n==0 || n==1) return n; int nums[]=new int [n+1]; nums[0]=0; nums[1]=1; int max=Integer.MIN_VALUE; for(int i=2;i<=n;i++){ if(i%2==0){ nums[i]=nums[i/2]; } else{ nums[i]=nums[i/2]+nums[i/2 + 1]; } max=Math.max(max,nums[i]); } return max; } }
class Solution { public: int getMaximumGenerated(int n) { // base cases if (n < 2) return n; // support variables int arr[n + 1], m; arr[0] = 0, arr[1] = 1; // building arr for (int i = 2; i <= n; i++) { if (i % 2) arr[i] = arr[i / 2] + arr[i / 2 + 1]; else arr[i] = arr[i / 2]; // updating m m = max(arr[i], m); } return m; } };
var getMaximumGenerated = function(n) { if (n === 0) return 0; if (n === 1) return 1; let arr = [0, 1]; let max = 0; for (let i = 0; i < n; i++) { if (2 <= 2 * i && 2 * i <= n) { arr[2 * i] = arr[i] if (arr[i] > max) max = arr[i]; } if (2 <= 2 * i && 2 * i + 1 <= n) { arr[2 * i + 1] = arr[i] + arr[i + 1] if (arr[i] + arr[i + 1] > max) max = arr[i] + arr[i + 1]; }; } return max; };
Get Maximum in Generated Array
There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i], do both of the following: Increment all the cells on row ri. Increment all the cells on column ci. Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. &nbsp; Example 1: Input: m = 2, n = 3, indices = [[0,1],[1,1]] Output: 6 Explanation: Initial matrix = [[0,0,0],[0,0,0]]. After applying first increment it becomes [[1,2,1],[0,1,0]]. The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers. Example 2: Input: m = 2, n = 2, indices = [[1,1],[0,0]] Output: 0 Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix. &nbsp; Constraints: 1 &lt;= m, n &lt;= 50 1 &lt;= indices.length &lt;= 100 0 &lt;= ri &lt; m 0 &lt;= ci &lt; n &nbsp; Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
class Solution: def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int: rows, cols = [False] * row, [False] * col for index in indices: rows[index[0]] = not rows[index[0]] cols[index[1]] = not cols[index[1]] count = 0 for i in rows: for j in cols: count += i ^ j return count
// --------------------- Solution 1 --------------------- class Solution { public int oddCells(int m, int n, int[][] indices) { int[][] matrix = new int[m][n]; for(int i = 0; i < indices.length; i++) { int row = indices[i][0]; int col = indices[i][1]; for(int j = 0; j < n; j++) { matrix[row][j]++; } for(int j = 0; j < m; j++) { matrix[j][col]++; } } int counter = 0; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(matrix[i][j] % 2 != 0) { counter++; } } } return counter; } } // --------------------- Solution 2 --------------------- class Solution { public int oddCells(int m, int n, int[][] indices) { int[] row = new int[m]; int[] col = new int[n]; for(int i = 0; i < indices.length; i++) { row[indices[i][0]]++; col[indices[i][1]]++; } int counter = 0; for(int i : row) { for(int j : col) { counter += (i + j) % 2 == 0 ? 0 : 1; } } return counter; } }
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { // tc: O(n+m) & sc: O(n+m) public: int oddCells(int n, int m, vector<vector<int>>& indices) { vector<bool> rows(n,false),cols(m,false); for(auto index: indices){ rows[index[0]] = rows[index[0]] ^ true; cols[index[1]] = cols[index[1]] ^ true; } int r(0),c(0); for(int i(0);i<n;i++){ if(rows[i]) r++; } for(int i(0);i<m;i++){ if(cols[i]) c++; } return r*(m-c) + c*(n-r); // (or) return (r*m + c*n - 2*r*c); } };
var oddCells = function(m, n, indices) { const matrix = Array.from(Array(m), () => Array(n).fill(0)); let res = 0; for (const [r, c] of indices) { for (let i = 0; i < n; i++) { // toggle 0/1 for even/odd // another method: matrix[r][i] = 1 - matrix[r][i] // or: matrix[r][i] = +!matrix[r][i] matrix[r][i] ^= 1; if (matrix[r][i]) res++; else res--; } for (let i = 0; i < m; i++) { matrix[i][c] ^= 1; if (matrix[i][c]) res++; else res--; } } return res; };
Cells with Odd Values in a Matrix
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted. &nbsp; Example 1: Input: nums = [9,1,2,3,9], k = 3 Output: 20.00000 Explanation: The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into [9, 1], [2], [3, 9], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. Example 2: Input: nums = [1,2,3,4,5,6,7], k = 4 Output: 20.50000 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 1 &lt;= nums[i] &lt;= 104 1 &lt;= k &lt;= nums.length
class Solution: def largestSumOfAverages(self, A, k): n = len(A) dp = [0] * n sum = 0 for i in range(n-1,-1,-1): sum += A[i] dp[i] = sum / (n-i) for l in range(1,k): for i in range(n-l): sum = 0 for j in range(i,n-l): sum += A[j] dp[i] = max(dp[i],dp[j+1] + sum / (j-i+1)) return dp[0]
class Solution { Double dp[][][]; int n; int k1; public double check(int b, int c,long sum,int n1,int ar[]){ System.out.println(b+" "+c); if(dp[b][c][n1]!=null) return dp[b][c][n1]; if(b==n){ if(sum!=0) return (double)sum/(double)n1; else return 0.0;} if(c<k1&&sum>0) dp[b][c][n1]=Math.max((double)sum/(double)n1+check(b,c+1,0,0,ar),check(b+1,c,sum+(long)ar[b],n1+1,ar)); else dp[b][c][n1]=check(b+1,c,sum+(long)ar[b],n1+1,ar); return dp[b][c][n1]; } public double largestSumOfAverages(int[] nums, int k) { n=nums.length; k1=k-1; dp= new Double[n+1][k][n+1]; return check(0,0,0l,0,nums); } }
class Solution { public: double solve(vector<int>&nums, int index, int k, vector<vector<double>>&dp){ if(index<0) return 0; if(k<=0) return -1e8; if(dp[index][k]!=-1) return dp[index][k]; double s_sum = 0; double maxi = INT_MIN; int cnt = 1; for(int i=index;i>=0;i--){ s_sum += nums[i]; maxi = max(maxi, (s_sum/cnt) + solve(nums, i-1, k-1, dp)); cnt++; } return dp[index][k] = maxi; } double largestSumOfAverages(vector<int>& nums, int k) { int n = nums.size(); vector<vector<double>>dp(n, vector<double>(k+1, -1)); return solve(nums, n-1, k, dp); } };
/** * @param {number[]} nums * @param {number} k * @return {number} */ var largestSumOfAverages = function(nums, k) { // set length const len = nums.length; // set sum by len fill const sum = new Array(len).fill(0); // set nums first to first of sum sum[0] = nums[0]; // set every item of sum to the sum of the previous and the corresponding item of nums for (let i = 1; i < len; i++) { sum[i] = sum[i - 1] + nums[i]; } // set dynamic programming const dp = new Array(k + 1).fill("").map(() => new Array(len).fill(0)); // according to the meaning of the problem, set the value of dp for (let i = 0; i < len; i++) { dp[1][i] = sum[i] / (i + 1); } for (let i = 1; i <= k; i++) { dp[i][i - 1] = sum[i - 1]; } for (let i = 2; i <= k; i++) { for (let j = i; j < len; j++) { for (let m = j - 1; m >= i - 2; m--) { dp[i][j] = Math.max(dp[i][j], dp[i - 1][m] + (sum[j] - sum[m]) / (j - m)); } } } // result return dp[k][len - 1]; };
Largest Sum of Averages
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally. &nbsp; Example 1: Input: nums = [1,5,2] Output: false Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. Example 2: Input: nums = [1,5,233,7] Output: true Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 20 0 &lt;= nums[i] &lt;= 107
class Solution: def PredictTheWinner(self, nums: List[int]) -> bool: dp = [[-1] * len(nums) for _ in nums] def get_score(i: int, j: int) -> int: if i == j: dp[i][j] = 0 return dp[i][j] if i == j - 1: dp[i][j] = nums[j] if nums[i] > nums[j] else nums[i] return dp[i][j] if dp[i][j] != -1: return dp[i][j] y1 = get_score(i + 1, j - 1) y2 = get_score(i + 2, j) y3 = get_score(i, j - 2) res_y1 = y1 + nums[j] if y1 + nums[j] > y2 + nums[i+1] else y2 + nums[i+1] res_y2 = y1 + nums[i] if y1 + nums[i] > y3 + nums[j-1] else y3 + nums[j-1] dp[i][j] = min(res_y1, res_y2) return dp[i][j] y = get_score(0, len(nums) - 1) x = sum(nums) - y return 0 if y > x else 1
class Solution { public boolean PredictTheWinner(int[] nums) { return predictTheWinner(nums, 0, nums.length-1,true,0, 0); } private boolean predictTheWinner(int[] nums, int start,int end, boolean isP1Turn, long p1Score, long p2Score){ if(start > end){ return p1Score >= p2Score; } boolean firstTry; boolean secondTry; if(isP1Turn){ firstTry = predictTheWinner(nums, start +1 , end, false, p1Score + nums[start], p2Score); secondTry = predictTheWinner(nums, start, end-1, false, p1Score + nums[end], p2Score); }else{ firstTry = predictTheWinner(nums, start +1 , end, true, p1Score, p2Score + nums[start]); secondTry = predictTheWinner(nums, start, end-1, true, p1Score , p2Score + nums[end]); } return isP1Turn ? (firstTry || secondTry) : (firstTry && secondTry); } }
class Solution { public: bool PredictTheWinner(vector<int>& nums) { vector<vector<vector<int>>> dp(nums.size(),vector<vector<int>>(nums.size(),vector<int>(3,INT_MAX))); int t=fun(dp,nums,0,nums.size()-1,1); return t>=0; } int fun(vector<vector<vector<int>>>& dp,vector<int>& v,int i,int j,int t) { if(i>j) return 0; if(dp[i][j][t+1]!=INT_MAX) return dp[i][j][t+1]; if(t>0) return dp[i][j][t+1]=max(v[i]*t+fun(dp,v,i+1,j,-1),v[j]*t+fun(dp,v,i,j-1,-1)); else return dp[i][j][t+1]=min(v[i]*t+fun(dp,v,i+1,j,1),v[j]*t+fun(dp,v,i,j-1,1)); } };
var PredictTheWinner = function(nums) { const n = nums.length; const dp = []; for (let i = 0; i < n; i++) { dp[i] = new Array(n).fill(0); dp[i][i] = nums[i]; } for (let len = 2; len <= n; len++) { for (let start = 0; start < n - len + 1; start++) { const end = start + len - 1; dp[start][end] = Math.max(nums[start] - dp[start + 1][end], nums[end] - dp[start][end - 1]); } } return dp[0][n - 1] >= 0; };
Predict the Winner
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: The value of the first element in arr must be 1. The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) &lt;= 1 for each i where 1 &lt;= i &lt; arr.length (0-indexed). abs(x) is the absolute value of x. There are 2 types of operations that you can perform any number of times: Decrease the value of any element of arr to a smaller positive integer. Rearrange the elements of arr to be in any order. Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions. &nbsp; Example 1: Input: arr = [2,2,1,2,1] Output: 2 Explanation: We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. The largest element in arr is 2. Example 2: Input: arr = [100,1,1000] Output: 3 Explanation: One possible way to satisfy the conditions is by doing the following: 1. Rearrange arr so it becomes [1,100,1000]. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now arr = [1,2,3], which satisfies the conditions. The largest element in arr is 3. Example 3: Input: arr = [1,2,3,4,5] Output: 5 Explanation: The array already satisfies the conditions, and the largest element is 5. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 105 1 &lt;= arr[i] &lt;= 109
class Solution: def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: counter = collections.Counter(arr) available = sum(n > len(arr) for n in arr) i = ans = len(arr) while i > 0: # This number is not in arr if not counter[i]: # Use another number to fill in its place. If we cannot, we have to decrease our max if available: available -= 1 else: ans -= 1 # Other occurences can be used for future. else: available += counter[i] - 1 i -= 1 return ans
class Solution { public int maximumElementAfterDecrementingAndRearranging(int[] arr) { Arrays.sort(arr); arr[0] = 1; for(int i = 1;i<arr.length;i++){ if(Math.abs(arr[i] - arr[i-1]) > 1) arr[i] = arr[i-1] + 1; } return arr[arr.length-1]; } }
class Solution { public: int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) { sort(arr.begin(),arr.end()); int n=arr.size(); arr[0]=1; for(int i=1;i<n;i++) { if(arr[i]-arr[i-1]>1) { arr[i]=arr[i-1]+1; } } return arr[n-1]; } };
var maximumElementAfterDecrementingAndRearranging = function(arr) { if (!arr.length) return 0 arr.sort((a, b) => a - b) arr[0] = 1 for (let i = 1; i < arr.length; i++) { if (Math.abs(arr[i] - arr[i - 1]) > 1) arr[i] = arr[i - 1] + 1 } return arr.at(-1) };
Maximum Element After Decreasing and Rearranging
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. &nbsp; Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 6 -10 &lt;= nums[i] &lt;= 10 All the integers of nums are unique.
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: return list(permutations(nums))
class Solution { List<List<Integer>> res = new LinkedList<>(); public List<List<Integer>> permute(int[] nums) { ArrayList<Integer> list = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; backTrack(nums, list, visited); return res; } private void backTrack(int[] nums, ArrayList<Integer> list, boolean[] visited){ if(list.size() == nums.length){ res.add(new ArrayList(list)); return; } for(int i = 0; i < nums.length; i++){ if(!visited[i]){ visited[i] = true; list.add(nums[i]); backTrack(nums, list, visited); visited[i] = false; list.remove(list.size() - 1); } } } }
class Solution { public: void per(int ind, int n, vector<int>&nums, vector<vector<int>> &ans) { if(ind==n) { ans.push_back(nums); return; } for(int i=ind;i<n;i++) { swap(nums[ind],nums[i]); per(ind+1,n,nums,ans); swap(nums[ind],nums[i]); } } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> ans; int n=nums.size(); per(0,n,nums,ans); return ans; } };
var permute = function(nums) { const output = []; const backtracking = (current, remaining) => { if (!remaining.length) return output.push(current); for (let i = 0; i < remaining.length; i++) { const newCurrent = [...current]; const newRemaining = [...remaining]; newCurrent.push(newRemaining[i]); newRemaining.splice(i, 1); backtracking(newCurrent, newRemaining); } } backtracking([], nums); return output; };
Permutations
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations&nbsp;is sorted in an ascending order, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h, the maximum one is taken as the h-index. You must write an algorithm that runs in logarithmic time. &nbsp; Example 1: Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,2,100] Output: 2 &nbsp; Constraints: n == citations.length 1 &lt;= n &lt;= 105 0 &lt;= citations[i] &lt;= 1000 citations is sorted in ascending order.
import bisect class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) for h in range(n, -1, -1): if h <= n - bisect.bisect_left(citations, h): return h
class Solution { public int hIndex(int[] citations) { int n=citations.length; int res=0; for(int i=0;i<n;i++) { if(citations[i]>=n-i) { return n-i; } } return res; } }
class Solution { public: int hIndex(vector<int>& citations) { int start = 0 , end = citations.size()-1; int n = citations.size(); while(start <= end){ int mid = start + (end - start) / 2; int val = citations[mid]; if(val == (n - mid)) return citations[mid]; else if(val < n - mid){ start = mid + 1; } else{ end = mid - 1; } } return n - start; } };
/** * The binary search solution. * * Time Complexity: O(log(n)) * Space Complexity: O(1) * * @param {number[]} citations * @return {number} */ var hIndex = function(citations) { const n = citations.length let l = 0 let r = n - 1 while (l <= r) { const m = Math.floor((l + r) / 2) if (citations[m] > n - m) { r = m - 1 continue } if (citations[m] < n - m) { l = m + 1 continue } return citations[m] } return n - l }
H-Index II
Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List&lt;Node&gt; neighbors; } &nbsp; Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. &nbsp; Example 1: Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph, it does not have any nodes. &nbsp; Constraints: The number of nodes in the graph is in the range [0, 100]. 1 &lt;= Node.val &lt;= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node.
def cloneGraph(self, node: 'Node') -> 'Node': if node == None: return None new_node = Node(node.val, []) visited = set() q = [[node, new_node]] visited.add(node.val) adj_map = {} adj_map[node] = new_node while len(q) != 0: curr = q.pop(0) for n in curr[0].neighbors: # if n.val not in visited: if n not in adj_map and n is not None: new = Node(n.val, []) curr[1].neighbors.append(new) adj_map[n] = new else: curr[1].neighbors.append(adj_map[n]) if n.val not in visited: q.append([n, adj_map[n]]) visited.add(n.val) return new_node
/* // Definition for a Node. class Node { public int val; public List<Node> neighbors; public Node() { val = 0; neighbors = new ArrayList<Node>(); } public Node(int _val) { val = _val; neighbors = new ArrayList<Node>(); } public Node(int _val, ArrayList<Node> _neighbors) { val = _val; neighbors = _neighbors; } } */ class Solution { public void dfs(Node node , Node copy , Node[] visited){ visited[copy.val] = copy;// store the current node at it's val index which will tell us that this node is now visited // now traverse for the adjacent nodes of root node for(Node n : node.neighbors){ // check whether that node is visited or not // if it is not visited, there must be null if(visited[n.val] == null){ // so now if it not visited, create a new node Node newNode = new Node(n.val); // add this node as the neighbor of the prev copied node copy.neighbors.add(newNode); // make dfs call for this unvisited node to discover whether it's adjacent nodes are explored or not dfs(n , newNode , visited); }else{ // if that node is already visited, retrieve that node from visited array and add it as the adjacent node of prev copied node // THIS IS THE POINT WHY WE USED NODE[] INSTEAD OF BOOLEAN[] ARRAY copy.neighbors.add(visited[n.val]); } } } public Node cloneGraph(Node node) { if(node == null) return null; // if the actual node is empty there is nothing to copy, so return null Node copy = new Node(node.val); // create a new node , with same value as the root node(given node) Node[] visited = new Node[101]; // in this question we will create an array of Node(not boolean) why ? , because i have to add all the adjacent nodes of particular vertex, whether it's visited or not, so in the Node[] initially null is stored, if that node is visited, we will store the respective node at the index, and can retrieve that easily. Arrays.fill(visited , null); // initially store null at all places dfs(node , copy , visited); // make a dfs call for traversing all the vertices of the root node return copy; // in the end return the copy node } }
'IF YOU LIKE IT THEN PLS UpVote😎😎😎' class Solution { public: Node* dfs(Node* cur,unordered_map<Node*,Node*>& mp) { vector<Node*> neighbour; Node* clone=new Node(cur->val); mp[cur]=clone; for(auto it:cur->neighbors) { if(mp.find(it)!=mp.end()) //already clone and stored in map { neighbour.push_back(mp[it]); //directly push back the clone node from map to neigh } else neighbour.push_back(dfs(it,mp)); } clone->neighbors=neighbour; return clone; } Node* cloneGraph(Node* node) { unordered_map<Node*,Node*> mp; if(node==NULL) return NULL; if(node->neighbors.size()==0) //if only one node present no neighbors { Node* clone= new Node(node->val); return clone; } return dfs(node,mp); } };
var cloneGraph = function(node) { if(!node) return node; let queue = [node]; let map = new Map(); //1. Create new Copy of each node and save in Map while(queue.length) { let nextQueue = []; for(let i = 0; i < queue.length; i++) { let n = queue[i]; let newN = new Node(n.val); if(!map.has(n)) { map.set(n, newN); } let nei = n.neighbors; for(let j = 0; j < nei.length; j++) { if(map.has(nei[j])) continue; nextQueue.push(nei[j]); } } queue = nextQueue; } queue = [node]; let seen = new Set(); seen.add(node); //2. Run BFS again and populate neighbors in new node created in step 1. while(queue.length) { let nextQueue = []; for(let i = 0; i < queue.length; i++) { let n = queue[i]; let nei = n.neighbors; let newn = map.get(n); for(let j = 0; j < nei.length; j++) { newn.neighbors.push(map.get(nei[j])); if(!seen.has(nei[j])) { nextQueue.push(nei[j]); seen.add(nei[j]); } } } queue = nextQueue; } return map.get(node); };
Clone Graph
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| &lt; |b - x|, or |a - x| == |b - x| and a &lt; b &nbsp; Example 1: Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4] Example 2: Input: arr = [1,2,3,4,5], k = 4, x = -1 Output: [1,2,3,4] &nbsp; Constraints: 1 &lt;= k &lt;= arr.length 1 &lt;= arr.length &lt;= 104 arr is sorted in ascending order. -104 &lt;= arr[i], x &lt;= 104
class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: def sorted_distance(value, static_input = x): return abs(value - static_input) distances = [] result = [] heapq.heapify(distances) for l,v in enumerate(arr): distances.append((l, sorted_distance(value = v))) for i in heapq.nsmallest(k, distances, key = lambda x: x[1]): result.append(arr[i[0]]) result.sort() return result
class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { List<Integer> result = new ArrayList<>(); int low = 0, high = arr.length -1; while(high - low >= k){ if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x)) low++; else high--; } for(int i = low; i <= high; i++) result.add(arr[i]); return result; } }
class Solution { public: static bool cmp(pair<int,int>&p1,pair<int,int>&p2) { if(p1.first==p2.first) //both having equal abs diff { return p1.second<p2.second; } return p1.first<p2.first; } vector<int> findClosestElements(vector<int>& arr, int k, int x) { vector<pair<int,int>>v; //abs diff , ele for(int i=0;i<arr.size();i++) { v.push_back(make_pair(abs(arr[i]-x),arr[i])); } sort(v.begin(),v.end(),cmp); vector<int>ans; for(int i=0;i<k;i++) { ans.push_back(v[i].second); } sort(ans.begin(),ans.end()); return ans; } };
var findClosestElements = function(arr, k, x) { const result = [...arr]; while (result.length > k) { const start = result[0]; const end = result.at(-1); x - start <= end - x ? result.pop() : result.shift(); } return result; };
Find K Closest Elements
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range.&nbsp; Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters&nbsp;so that those heaters could cover all houses. Notice that&nbsp;all the heaters follow your radius standard, and the warm radius will the same. &nbsp; Example 1: Input: houses = [1,2,3], heaters = [2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: houses = [1,2,3,4], heaters = [1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. Example 3: Input: houses = [1,5], heaters = [2] Output: 3 &nbsp; Constraints: 1 &lt;= houses.length, heaters.length &lt;= 3 * 104 1 &lt;= houses[i], heaters[i] &lt;= 109
class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: """ """ houses.sort() heaters.sort() max_radius = -inf for house in houses: i = bisect_left(heaters, house) if i == len(heaters): max_radius = max(max_radius, house - heaters[-1]) elif i == 0: max_radius = max(max_radius, heaters[i] - house) else: curr = heaters[i] prev = heaters[i-1] max_radius = max(max_radius,min(abs(house - curr), abs(house-prev))) return max_radius # O(NLOGN)
class Solution { public boolean can(int r, int[] houses, int[] heaters) { int prevHouseIdx = -1; for(int i = 0; i < heaters.length; i++) { int from = heaters[i]-r; int to = heaters[i]+r; for(int j = prevHouseIdx+1; j < houses.length; j++){ if(houses[j]<=to && houses[j]>=from){ prevHouseIdx++; } else break; } if(prevHouseIdx >= houses.length-1)return true; } return prevHouseIdx>= houses.length-1; } public int findRadius(int[] houses, int[] heaters) { Arrays.sort(houses); Arrays.sort(heaters); int lo = 0, hi = 1000000004; int mid, ans = hi; while(lo <= hi) { mid = (lo+hi)/2; if(can(mid, houses, heaters)){ ans = mid; hi = mid - 1; } else lo = mid + 1; } return ans; } }
class Solution { public: //we will assign each house to its closest heater in position(by taking the minimum //of the distance between the two closest heaters to the house) and then store the maximum //of these differences(since we want to have the same standard radius) int findRadius(vector<int>& houses, vector<int>& heaters) { sort(heaters.begin(),heaters.end()); int radius=0; for(int house:houses){ //finding the smallest heater whose position is not greater than //the current house int index=lower_bound(heaters.begin(),heaters.end(),house)-heaters.begin(); if(index==heaters.size()){ index--; } //the two closest positions to house will be heaters[index] and //heaters[index-1] int leftDiff=(index-1>=0)?abs(house-heaters[index-1]):INT_MAX; int rightDiff=abs(house-heaters[index]); radius=max(radius,min(leftDiff,rightDiff)); } return radius; } };
var findRadius = function(houses, heaters) { houses.sort((a, b) => a - b); heaters.sort((a, b) => a - b); let heaterPos = 0; const getRadius = (house, pos) => Math.abs(heaters[pos] - house); return houses.reduce((radius, house) => { while ( heaterPos < heaters.length && getRadius(house, heaterPos) >= getRadius(house, heaterPos + 1) ) heaterPos += 1; const currentRadius = getRadius(house, heaterPos); return Math.max(radius, currentRadius); }, 0); };
Heaters
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal. Pick a non-empty suffix from the string s where all the characters in this suffix are equal. The prefix and the suffix should not intersect at any index. The characters from the prefix and suffix must be the same. Delete both the prefix and the suffix. Return the minimum length of s after performing the above operation any number of times (possibly zero times). &nbsp; Example 1: Input: s = "ca" Output: 2 Explanation: You can't remove any characters, so the string stays as is. Example 2: Input: s = "cabaabac" Output: 0 Explanation: An optimal sequence of operations is: - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". - Take prefix = "a" and suffix = "a" and remove them, s = "baab". - Take prefix = "b" and suffix = "b" and remove them, s = "aa". - Take prefix = "a" and suffix = "a" and remove them, s = "". Example 3: Input: s = "aabccabba" Output: 3 Explanation: An optimal sequence of operations is: - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". - Take prefix = "b" and suffix = "bb" and remove them, s = "cca". &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s only consists of characters 'a', 'b', and 'c'.
class Solution: def minimumLength(self, s: str) -> int: while(len(s)>1 and s[0]==s[-1]): s=s.strip(s[0]) else: return len(s)
class Solution { public int minimumLength(String s) { int length = s.length(); char[] chars = s.toCharArray(); for(int left = 0,right = chars.length-1;left < right;){ if(chars[left] == chars[right]){ char c = chars[left]; while(left < right && chars[left] == c ){ left++; length--; } while (right >= left && chars[right] == c){ right--; length--; } }else { break; } } return length; } }
class Solution { public: int minimumLength(string s) { int i=0,j=s.length()-1; while(i<j) { if(s[i]!=s[j]) { break; } else { char x=s[i]; while(s[i]==x) { i++; } if(i>j) { return 0; } while(s[j]==x) { j--; } if(j<i) { return 0; } } } return j-i+1; } };
var minimumLength = function(s) { const n = s.length; let left = 0; let right = n - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) break; left++; right--; while (left <= right && s.charAt(left - 1) == s.charAt(left)) left++; while (left <= right && s.charAt(right) == s.charAt(right + 1)) right--; } return right - left + 1; };
Minimum Length of String After Deleting Similar Ends
Given an integer n, return any array containing n unique integers such that they add up to 0. &nbsp; Example 1: Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. Example 2: Input: n = 3 Output: [-1,0,1] Example 3: Input: n = 1 Output: [0] &nbsp; Constraints: 1 &lt;= n &lt;= 1000
class Solution: def sumZero(self, n: int) -> List[int]: q,p=divmod(n,2) if p: return list(range(-q, q+1)) else: return list(range(-q,0))+list(range(1,q+1))
class Solution { public int[] sumZero(int n) { int[] ans = new int[n]; int j=0; for(int i=1;i<=n/2;i++) { ans[j] = i; j++; } for(int i=1;i<=n/2;i++) { ans[j] = -i; j++; } if(n%2!=0) ans[j] = 0; return ans; } }
class Solution { public: vector<int> sumZero(int n) { if(n == 1){ return {0}; }else{ vector<int> res; for(int i=n/2*-1;i<=n/2;i++){ if(i == 0){ if(n%2 == 0){ continue; }else{ res.push_back(i); continue; } } res.push_back(i); } return res; } } };
var sumZero = function(n) { var num = Math.floor(n/2); var res = []; for(var i=1;i<=num;i++){ res.push(i,-i) } if(n%2!==0){ res.push(0) } return res }
Find N Unique Integers Sum up to Zero
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 &lt;= i &lt;= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. &nbsp; Example 1: Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]] Output: 1 Explanation: source can be transformed the following way: - Swap indices 0 and 1: source = [2,1,3,4] - Swap indices 2 and 3: source = [2,1,4,3] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. Example 2: Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [] Output: 2 Explanation: There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. Example 3: Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]] Output: 0 &nbsp; Constraints: n == source.length == target.length 1 &lt;= n &lt;= 105 1 &lt;= source[i], target[i] &lt;= 105 0 &lt;= allowedSwaps.length &lt;= 105 allowedSwaps[i].length == 2 0 &lt;= ai, bi &lt;= n - 1 ai != bi
class UnionFind: def __init__(self, n): self.roots = [i for i in range(n)] def find(self, v): if self.roots[v] != v: self.roots[v] = self.find(self.roots[v]) return self.roots[v] def union(self, u, v): self.roots[self.find(u)] = self.find(v) class Solution: def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: uf = UnionFind(len(source)) for idx1, idx2 in allowedSwaps: uf.union(idx1, idx2) m = collections.defaultdict(set) for i in range(len(source)): m[uf.find(i)].add(i) res = 0 for indices in m.values(): freq = {} for i in indices: freq[source[i]] = freq.get(source[i], 0)+1 freq[target[i]] = freq.get(target[i], 0)-1 res += sum(val for val in freq.values() if val > 0) return res
class Solution { public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { int minHamming = 0; UnionFind uf = new UnionFind(source.length); for (int [] swap : allowedSwaps) { int firstIndex = swap[0]; int secondIndex = swap[1]; // int firstParent = uf.find(firstIndex); // int secondParent = uf.find(secondIndex); // if (firstParent != secondParent) // uf.parent[firstParent] = secondParent; uf.union(firstIndex, secondIndex); } Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); for (int i=0; i<source.length; i++) { int num = source[i]; int root = uf.find(i); map.putIfAbsent(root, new HashMap<>()); Map<Integer, Integer> store = map.get(root); store.put(num, store.getOrDefault(num, 0) + 1); } for (int i=0; i<source.length; i++) { int num = target[i]; int root = uf.find(i); Map<Integer, Integer> store = map.get(root); if (store.getOrDefault(num, 0) == 0) minHamming += 1; else store.put(num, store.get(num) - 1); } return minHamming; } } class UnionFind { int size; int components; int [] parent; int [] rank; UnionFind(int n) { if (n <= 0) throw new IllegalArgumentException("Size <= 0 is not allowed"); size = n; components = n; parent = new int [n]; rank = new int [n]; for (int i=0; i<n; i++) parent[i] = i; } public int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rank[rootQ] > rank[rootP]) { parent[rootP] = rootQ; } else { parent[rootQ] = rootP; if (rank[rootQ] == rank[rootP]) rank[rootP] += 1; } components -= 1; } public int size() { return size; } public boolean isConnected(int p, int q) { return find(p) == find(q); } public int numberComponents() { return components; } }
class Solution { public: vector<int> parents; vector<int> ranks; int find(int a) { if (a == parents[a]) return parents[a]; return parents[a] = find(parents[a]); } void uni(int a, int b) { a = find(a); b = find(b); if (ranks[a] >= ranks[b]) { parents[b] = a; ranks[a]++; } else { parents[a] = b; ranks[b]++; } } int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) { int n = source.size(); ranks = vector<int>(n, 0); for (int i = 0; i < n; i++) { parents.push_back(i); } for (auto &v : allowedSwaps) uni(v[0], v[1]); vector<unordered_multiset<int>> subs(n); for (int i = 0; i < n; i++) { subs[find(i)].insert(source[i]); } int cnt = 0; for (int i = 0; i < n; i++) { if (!subs[parents[i]].count(target[i])) cnt++; else subs[parents[i]].erase(subs[parents[i]].find(target[i])); } return cnt; } };
var minimumHammingDistance = function(source, target, allowedSwaps) { const n = source.length; const uf = {}; const sizes = {}; const members = {}; // initial setup for (let i = 0; i < n; i++) { const srcNum = source[i]; uf[i] = i; sizes[i] = 1; members[i] = new Map(); members[i].set(srcNum, 1); } function find(x) { if (uf[x] != x) uf[x] = find(uf[x]); return uf[x]; } function union(x, y) { const rootX = find(x); const rootY = find(y); if (rootX === rootY) return; if (sizes[rootX] > sizes[rootY]) { uf[rootY] = rootX; sizes[rootX] += sizes[rootY]; for (const [num, count] of members[rootY]) { if (!members[rootX].has(num)) members[rootX].set(num, 0); members[rootX].set(num, members[rootX].get(num) + count); } } else { uf[rootX] = rootY; sizes[rootY] += sizes[rootX]; const num = source[x]; for (const [num, count] of members[rootX]) { if (!members[rootY].has(num)) members[rootY].set(num, 0); members[rootY].set(num, members[rootY].get(num) + count); } } } for (const [idx1, idx2] of allowedSwaps) { union(idx1, idx2); } let mismatches = 0; for (let i = 0; i < n; i++) { const srcNum = source[i]; const tarNum = target[i]; const group = find(i); if (members[group].has(tarNum)) { members[group].set(tarNum, members[group].get(tarNum) - 1); if (members[group].get(tarNum) === 0) members[group].delete(tarNum); } else { mismatches++; } } return mismatches; };
Minimize Hamming Distance After Swap Operations
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. &nbsp; Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Example 2: Input: nums = [4,2,3,4] Output: 4 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt;= 1000
class Solution { public int triangleNumber(int[] nums) { int n = nums.length; Arrays.sort(nums); int count =0; for(int k = n-1; k>=2; k--) { int i = 0; int j = k-1; while(i < j) { int sum = nums[i] +nums[j]; if(sum > nums[k]) { count += j-i; j--; } else { i++; } } } return count; } }
class Solution { public int triangleNumber(int[] nums) { int n = nums.length; Arrays.sort(nums); int count =0; for(int k = n-1; k>=2; k--) { int i = 0; int j = k-1; while(i < j) { int sum = nums[i] +nums[j]; if(sum > nums[k]) { count += j-i; j--; } else { i++; } } } return count; } }
class Solution { public int triangleNumber(int[] nums) { int n = nums.length; Arrays.sort(nums); int count =0; for(int k = n-1; k>=2; k--) { int i = 0; int j = k-1; while(i < j) { int sum = nums[i] +nums[j]; if(sum > nums[k]) { count += j-i; j--; } else { i++; } } } return count; } }
class Solution { public int triangleNumber(int[] nums) { int n = nums.length; Arrays.sort(nums); int count =0; for(int k = n-1; k>=2; k--) { int i = 0; int j = k-1; while(i < j) { int sum = nums[i] +nums[j]; if(sum > nums[k]) { count += j-i; j--; } else { i++; } } } return count; } }
Valid Triangle Number
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime. Implement the AuthenticationManager class: AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive. generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds. renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens. countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime. Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions. &nbsp; Example 1: Input ["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"] [[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]] Output [null, null, null, 1, null, null, null, 0] Explanation AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds. authenticationManager.renew("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens. authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2. authenticationManager.countUnexpiredTokens(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1. authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7. authenticationManager.renew("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 &gt;= 7, so at time 8 the renew request is ignored, and nothing happens. authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15. authenticationManager.countUnexpiredTokens(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0. &nbsp; Constraints: 1 &lt;= timeToLive &lt;= 108 1 &lt;= currentTime &lt;= 108 1 &lt;= tokenId.length &lt;= 5 tokenId consists only of lowercase letters. All calls to generate will contain unique values of tokenId. The values of currentTime across all the function calls will be strictly increasing. At most 2000 calls will be made to all functions combined.
class AuthenticationManager(object): def __init__(self, timeToLive): self.token = dict() self.time = timeToLive # store timeToLive and create dictionary def generate(self, tokenId, currentTime): self.token[tokenId] = currentTime # store tokenId with currentTime def renew(self, tokenId, currentTime): limit = currentTime-self.time # calculate limit time to filter unexpired tokens if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time self.token[tokenId] = currentTime def countUnexpiredTokens(self, currentTime): limit = currentTime-self.time # calculate limit time to filter unexpired tokens c = 0 for i in self.token: if self.token[i]>limit: # count unexpired tokens c+=1 return c
class AuthenticationManager { private int ttl; private Map<String, Integer> map; public AuthenticationManager(int timeToLive) { this.ttl = timeToLive; this.map = new HashMap<>(); } public void generate(String tokenId, int currentTime) { map.put(tokenId, currentTime + this.ttl); } public void renew(String tokenId, int currentTime) { Integer expirationTime = this.map.getOrDefault(tokenId, null); if (expirationTime == null || expirationTime <= currentTime) return; generate(tokenId, currentTime); } public int countUnexpiredTokens(int currentTime) { int count = 0; for (Map.Entry<String, Integer> entry: this.map.entrySet()) if (entry.getValue() > currentTime) count++; return count; } }
class AuthenticationManager { int ttl; unordered_map<string, int> tokens; public: AuthenticationManager(int timeToLive) { ttl = timeToLive; } void generate(string tokenId, int currentTime) { tokens[tokenId] = currentTime + ttl; } void renew(string tokenId, int currentTime) { auto tokenIt = tokens.find(tokenId); if (tokenIt != end(tokens) && tokenIt->second > currentTime) { tokenIt->second = currentTime + ttl; } } int countUnexpiredTokens(int currentTime) { int res = 0; for (auto token: tokens) { if (token.second > currentTime) res++; } return res; } };
// O(n) var AuthenticationManager = function(timeToLive) { this.ttl = timeToLive; this.map = {}; }; AuthenticationManager.prototype.generate = function(tokenId, currentTime) { this.map[tokenId] = currentTime + this.ttl; }; AuthenticationManager.prototype.renew = function(tokenId, currentTime) { let curr = this.map[tokenId]; if (curr > currentTime) { this.generate(tokenId, currentTime); } }; AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) { return Object.keys(this.map).filter(key => this.map[key] > currentTime).length; };
Design Authentication Manager
You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: nums[i - 2] == nums[i], where 2 &lt;= i &lt;= n - 1. nums[i - 1] != nums[i], where 1 &lt;= i &lt;= n - 1. In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating. &nbsp; Example 1: Input: nums = [3,1,3,2,4,3] Output: 3 Explanation: One way to make the array alternating is by converting it to [3,1,3,1,3,1]. The number of operations required in this case is 3. It can be proven that it is not possible to make the array alternating in less than 3 operations. Example 2: Input: nums = [1,2,2,2,2] Output: 2 Explanation: One way to make the array alternating is by converting it to [1,2,1,2,1]. The number of operations required in this case is 2. Note that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 105
class Solution: def minimumOperations(self, nums: List[int]) -> int: n = len(nums) odd, even = defaultdict(int), defaultdict(int) for i in range(n): if i % 2 == 0: even[nums[i]] += 1 else: odd[nums[i]] += 1 topEven, secondEven = (None, 0), (None, 0) for num in even: if even[num] > topEven[1]: topEven, secondEven = (num, even[num]), topEven elif even[num] > secondEven[1]: secondEven = (num, even[num]) topOdd, secondOdd = (None, 0), (None, 0) for num in odd: if odd[num] > topOdd[1]: topOdd, secondOdd = (num, odd[num]), topOdd elif odd[num] > secondOdd[1]: secondOdd = (num, odd[num]) if topOdd[0] != topEven[0]: return n - topOdd[1] - topEven[1] else: return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])
class Solution { public int minimumOperations(int[] nums) { int freq[][] = new int[100005][2]; int i, j, k, ans=0; for(i = 0; i < nums.length; i++) { freq[nums[i]][i&1]++; } for(i = 1, j=k=0; i <= 100000; i++) { // Add the maximum frequency of odd indexes to maximum frequency even indexes //and vice versa, it will give us how many elements we don't need to change. ans = Math.max(ans, Math.max(freq[i][0] + k, freq[i][1] + j)); j = Math.max(j, freq[i][0]); k = Math.max(k, freq[i][1]); } return nums.length - ans; } }
class Solution { public: int minimumOperations(vector<int>& nums) { int totalEven = 0, totalOdd = 0; unordered_map<int,int> mapEven, mapOdd; for(int i=0;i<nums.size();i++) { if(i%2==0) { totalEven++; mapEven[nums[i]]++; } else { totalOdd++; mapOdd[nums[i]]++; } } int firstEvenCount = 0, firstEven = 0; int secondEvenCount = 0, secondEven = 0; for(auto it=mapEven.begin();it!=mapEven.end();it++) { int num = it->first; int count = it->second; if(count>=firstEvenCount) { secondEvenCount = firstEvenCount; secondEven = firstEven; firstEvenCount = count; firstEven = num; } else if(count >= secondEvenCount) { secondEvenCount = count; secondEven = num; } } int firstOddCount = 0, firstOdd = 0; int secondOddCount = 0, secondOdd = 0; for(auto it=mapOdd.begin();it!=mapOdd.end();it++) { int num = it->first; int count = it->second; if(count>=firstOddCount) { secondOddCount = firstOddCount; secondOdd = firstOdd; firstOddCount = count; firstOdd = num; } else if(count>=secondOddCount) { secondOddCount = count; secondOdd = num; } } int operationsEven = 0, operationsOdd = 0; operationsEven = totalEven - firstEvenCount; if(firstEven!=firstOdd) operationsEven += (totalOdd - firstOddCount); else operationsEven += (totalOdd - secondOddCount); operationsOdd = totalOdd - firstOddCount; if(firstOdd!=firstEven) operationsOdd += (totalEven - firstEvenCount); else operationsOdd += (totalEven - secondEvenCount); return min(operationsEven, operationsOdd); } };
/** * @param {number[]} nums * @return {number} */ var minimumOperations = function(nums) { let countOddId = {} let countEvenId = {} if(nums.length === 1) return 0 if(nums.length === 2 && nums[0] === nums[1]) { return 1 } nums.forEach((n, i) => { if(i%2) { if(!countOddId[n]) { countOddId[n] = 1; } else { countOddId[n]++ } } else { if(!countEvenId[n]) { countEvenId[n] = 1; } else { countEvenId[n]++ } } }) const sortedEven = Object.entries(countEvenId).sort((a, b) => { return b[1] - a[1] }) const sortedOdd = Object.entries(countOddId).sort((a, b) => { return b[1] - a[1] }) if(sortedEven[0][0] === sortedOdd[0][0]) { let maxFirst =0; let maxSec =0; if(sortedEven.length === 1) { maxFirst = sortedEven[0][1]; maxSec = sortedOdd[1]? sortedOdd[1][1] : 0; return nums.length - (maxFirst + maxSec) } if(sortedOdd.length === 1) { maxFirst = sortedOdd[0][1]; maxSec = sortedEven[1] ? sortedEven[1][1] : 0; return nums.length - (maxFirst + maxSec) } if(sortedEven[0][1] >= sortedOdd[0][1] && sortedEven[1][1] <= sortedOdd[1][1]) { maxFirst = sortedEven[0][1] maxSec = sortedOdd[1][1] return nums.length - (maxFirst + maxSec) } else { maxFirst = sortedOdd[0][1] maxSec = sortedEven[1][1] return nums.length - (maxFirst + maxSec) } } else { return nums.length - (sortedEven[0][1] + sortedOdd[0][1]) } };
Minimum Operations to Make the Array Alternating
Given an array of integers arr, return true if and only if it is a valid mountain array. Recall that arr is a mountain array if and only if: arr.length &gt;= 3 There exists some i with 0 &lt; i &lt; arr.length - 1 such that: arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1] &nbsp; Example 1: Input: arr = [2,1] Output: false Example 2: Input: arr = [3,5,5] Output: false Example 3: Input: arr = [0,3,2,1] Output: true &nbsp; Constraints: 1 &lt;= arr.length &lt;= 104 0 &lt;= arr[i] &lt;= 104
class Solution: def validMountainArray(self, arr: List[int]) -> bool: if len(arr) < 3: return False for i in range(1,len(arr)): if arr[i] <= arr[i-1]: if i==1: return False break for j in range(i,len(arr)): if arr[j] >= arr[j-1]: return False return True
class Solution { public boolean validMountainArray(int[] arr) { // edge case if(arr.length < 3) return false; // keep 2 pointers int i=0; int j=arr.length-1; // use i pointer to iterate through steep increase from LHS while(i<j && arr[i]<arr[i+1]) { i++; } // use j pointer to iterate steep increase from RHS while(j>i && arr[j]<arr[j-1]) { j--; } // both should meet at same place and it be neither start or end. return i==j && i<arr.length-1 && j>0; } }
class Solution { public: bool validMountainArray(vector<int>& arr) { int flag = 1; if((arr.size()<=2) || (arr[1] <= arr[0])) return false; for(int i=1; i<arr.size(); i++){ if(flag){ if(arr[i] > arr[i-1]) continue; i--; flag = 0; } else{ if(arr[i] < arr[i-1]) continue; return false; } } if(flag) return false; return true; } };****
var validMountainArray = function(arr) { let index = 0, length = arr.length; //find the peak while(index < length && arr[index] < arr[index + 1])index++ //edge cases if(index === 0 || index === length - 1) return false; //check if starting from peak to end of arr is descending order while(index < length && arr[index] > arr[index + 1])index++ return index === length - 1; };
Valid Mountain Array
You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree. &nbsp; Example 1: Input: root = [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown. Example 2: Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val == 0
import itertools # 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 minCameraHelper(self, root: Optional[TreeNode]) -> (int, int): # Return 3 things: # cam, uncam, uncov # cam(era) is best score for valid tree with camera at root # uncam(era) is best score for valid tree without camera at root # uncov(ered) is best score for invalid tree, where the only invalidity (i.e. the only uncovered node) is the root node # Note: maxint (float("inf")) is used to signify situations that don't make sense or can't happen. # Anywhere there is a float("inf"), you can safely replace that with a 1 as 1 is as bad or worse than worst practical, # but I stick with maxint to highlight the nonsensical cases for the reader! if not root.left and not root.right: # base case: leaf # Note: "Uncam" setting doesn't make much sense (a leaf with no parents can either have a camera or be uncovered, # but not covered with no camera) return 1, float("inf"), 0 if root.left: left_cam, left_uncam, left_uncov = self.minCameraHelper(root.left) else: # base case: empty child # Need to prevent null nodes from providing coverage to parent, so set that cost to inf left_cam, left_uncam, left_uncov = float("inf"), 0, 0 if root.right: right_cam, right_uncam, right_uncov = self.minCameraHelper(root.right) else: # base case: empty child # Need to prevent null nodes from providing coverage to parent, so set that cost to inf right_cam, right_uncam, right_uncov = float("inf"), 0, 0 # Get the possible combinations for each setting cam_poss = itertools.product([left_cam, left_uncam, left_uncov], [right_cam, right_uncam, right_uncov]) uncam_poss = [(left_cam, right_cam), (left_uncam, right_cam), (left_cam, right_uncam)] uncov_poss = [(left_uncam, right_uncam)] # Compute costs for each setting cam = min([x + y for x, y in cam_poss]) + 1 uncam = min([x + y for x, y in uncam_poss]) uncov = min([x + y for x, y in uncov_poss]) return cam, uncam, uncov def minCameraCover(self, root: Optional[TreeNode]) -> int: cam, uncam, _ = self.minCameraHelper(root) return min(cam, uncam)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int count = 0; public int minCameraCover(TreeNode root) { if(helper(root) == -1) count++; return count; } //post order //0 - have camera //1 - covered //-1 - not covered public int helper(TreeNode root) { if(root == null) return 1; int left = helper(root.left); int right = helper(root.right); if(left == -1 || right == -1) { count++; return 0; } if(left == 0 || right == 0) return 1; return -1; } }
class Solution { public: map<TreeNode*, int> mpr; int dp[1009][3]; int minCameraCover(TreeNode* root) { int num = 0; adres(root, num); memset(dp, -1, sizeof(dp)); int t1 = dp_fun(root, 0), t2 = dp_fun(root, 1), t3 = dp_fun(root, 2); return min({t1, t3}); } int dp_fun(TreeNode* cur, int st) { int nd = mpr[cur]; if(dp[nd][st] == -1) { if(cur == NULL) { if(st == 2) { return 1e8; } else { return 0; } } if(st == 2) { dp[nd][st] = 1 + min({dp_fun(cur->left, 1) + dp_fun(cur->right, 1), dp_fun(cur->left, 1) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 1), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)}); } else if(st == 1) { dp[nd][st] = min({dp_fun(cur->left, 0) + dp_fun(cur->right, 0), dp_fun(cur->left, 0) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 0), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)}); } else { dp[nd][st] = min({dp_fun(cur, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 0), dp_fun(cur->left, 0) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)}); } } return dp[nd][st]; } void adres(TreeNode* cur, int &cnt) { if(cur == NULL) { return; } mpr[cur] = cnt; cnt++; adres(cur->left, cnt); adres(cur->right, cnt); } };
var minCameraCover = function(root) { let cam = 0; // 0 --> No covered // 1 --> covered by camera // 2 --> has camera function dfs(root) { if(root === null) return 1; const left = dfs(root.left); const right = dfs(root.right); if(left === 0 || right === 0) { // child required a camera to covered cam++; return 2; } else if(left === 2 || right === 2) { // child has camera so i am covered return 1; } else { // child is covered but don't have camera,So i want camera return 0; } } const ans = dfs(root); if(ans === 0) ++cam; return cam; };
Binary Tree Cameras
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -&gt; 0, 'b' -&gt; 1, 'c' -&gt; 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. For example, if s = "acb", we concatenate each letter's letter value, resulting in "021". After converting it, we get 21. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise. &nbsp; Example 1: Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb" Output: true Explanation: The numerical value of firstWord is "acb" -&gt; "021" -&gt; 21. The numerical value of secondWord is "cba" -&gt; "210" -&gt; 210. The numerical value of targetWord is "cdb" -&gt; "231" -&gt; 231. We return true because 21 + 210 == 231. Example 2: Input: firstWord = "aaa", secondWord = "a", targetWord = "aab" Output: false Explanation: The numerical value of firstWord is "aaa" -&gt; "000" -&gt; 0. The numerical value of secondWord is "a" -&gt; "0" -&gt; 0. The numerical value of targetWord is "aab" -&gt; "001" -&gt; 1. We return false because 0 + 0 != 1. Example 3: Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa" Output: true Explanation: The numerical value of firstWord is "aaa" -&gt; "000" -&gt; 0. The numerical value of secondWord is "a" -&gt; "0" -&gt; 0. The numerical value of targetWord is "aaaa" -&gt; "0000" -&gt; 0. We return true because 0 + 0 == 0. &nbsp; Constraints: 1 &lt;= firstWord.length, secondWord.length, targetWord.length &lt;= 8 firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.
class Solution: def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: x=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] a="" for i in firstWord: a=a+str(x.index(i)) b="" for i in secondWord: b=b+str(x.index(i)) c="" for i in targetWord: c=c+str(x.index(i)) if int(a)+int(b)==int(c): return True return False
class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { int sumfirst=0, sumsecond=0, sumtarget=0; for(char c : firstWord.toCharArray()){ sumfirst += c-'a'; sumfirst *= 10; } for(char c : secondWord.toCharArray()){ sumsecond += c-'a'; sumsecond *= 10; } for(char c : targetWord.toCharArray()){ sumtarget += c-'a'; sumtarget *= 10; } return (sumfirst + sumsecond) == sumtarget; } }
class Solution { public: bool isSumEqual(string firstWord, string secondWord, string targetWord) { int first=0,second=0,target=0; for(int i=0;i<firstWord.size();i++) first=first*10 + (firstWord[i]-'a'); for(int i=0;i<secondWord.size();i++) second=second*10 +(secondWord[i]-'a'); for(int i=0;i<targetWord.size();i++) target=target*10 +(targetWord[i]-'a'); return first+second == target; } };
var isSumEqual = function(firstWord, secondWord, targetWord) { let obj = { 'a' : '0', "b" : '1', "c" : '2', "d" : '3', "e" : '4', 'f' : '5', 'g' : '6', 'h' : '7', 'i' : '8', "j" : '9' } let first = "", second = "", target = "" for(let char of firstWord){ first += obj[char] } for(let char of secondWord){ second += obj[char] } for(let char of targetWord){ target += obj[char] } return parseInt(first) + parseInt(second) === parseInt(target) };
Check if Word Equals Summation of Two Words
You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise. &nbsp; Example 1: Input: equations = ["a==b","b!=a"] Output: false Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations. Example 2: Input: equations = ["b==a","a==b"] Output: true Explanation: We could assign a = 1 and b = 1 to satisfy both equations. &nbsp; Constraints: 1 &lt;= equations.length &lt;= 500 equations[i].length == 4 equations[i][0] is a lowercase letter. equations[i][1] is either '=' or '!'. equations[i][2] is '='. equations[i][3] is a lowercase letter.
class Solution: def equationsPossible(self, equations: List[str]) -> bool: from collections import defaultdict g = defaultdict(list) for e in equations: if e[1] == '=': x = e[0] y = e[3] g[x].append(y) g[y].append(x) # marked the connected components as 0,1,2,...,25 ccs = defaultdict(lambda: -1) # -1 means unmarked or unseen def dfs(node, cc): if node not in ccs: ccs[node] = cc for neighbour in g[node]: dfs(neighbour, cc) for i in range(26): dfs(chr(i+97), i) for e in equations: if e[1] == '!': x = e[0] y = e[3] if ccs[x] == ccs[y]: return False return True
class Solution { static int par[]; public static int findPar(int u) { return par[u] == u ? u : (par[u] = findPar(par[u])); } public boolean equationsPossible(String[] equations) { par = new int[26]; for (int i = 0; i < 26; i++) { par[i] = i; } /*First perform all the merging operation*/ for (String s : equations) { int c1 = s.charAt(0) - 'a'; int c2 = s.charAt(3) - 'a'; char sign = s.charAt(1); int p1 = findPar(c1); int p2 = findPar(c2); if (sign == '=') { if (p1 != p2) { if (p1 < p2) { par[p2] = p1; } else { par[p1] = p2; } } } } /*Now traverse on the whole string and search for any != operation and check if there parents are same*/ for (String s : equations) { int c1 = s.charAt(0) - 'a'; int c2 = s.charAt(3) - 'a'; char sign = s.charAt(1); int p1 = findPar(c1); int p2 = findPar(c2); if (sign == '!') { if (p1 == p2) { return false; } } } return true; } }
class Solution { public: bool equationsPossible(vector<string>& equations) { unordered_map<char,set<char>> equalGraph; //O(26*26) unordered_map<char,set<char>> unEqualGraph; //O(26*26) //build graph: for(auto eq: equations){ char x = eq[0], y = eq[3]; if(eq[1] == '='){ equalGraph[x].insert(y); equalGraph[y].insert(x); } else{ unEqualGraph[x].insert(y); unEqualGraph[y].insert(x); } } //for each node in inequality, check if they are reachable from equality: for(auto it: unEqualGraph){ char node = it.first; set<char> nbrs = it.second; //all nbrs that should be unequal if(nbrs.size() == 0) continue; unordered_map<char,bool> seen; bool temp = dfs(node, seen, equalGraph, nbrs); if(temp) return false; //if any nbr found in equality, return false } return true; //TC, SC: O(N*N) + O(26*26) } bool dfs(char curNode, unordered_map<char,bool> &seen, unordered_map<char,set<char>> &equalGraph, set<char> &nbrs){ seen[curNode] = true; if(nbrs.find(curNode) != nbrs.end()) return true; for(auto nextNode: equalGraph[curNode]){ if(seen.find(nextNode) == seen.end()){ bool temp = dfs(nextNode, seen, equalGraph, nbrs); if(temp) return true; } } return false; } };
/** * @param {string[]} equations * @return {boolean} */ class UnionSet { constructor() { this.father = new Array(26).fill(0).map((item, index) => index); } find(x) { return this.father[x] = this.father[x] === x ? x : this.find(this.father[x]); } merge(a, b) { const fa = this.find(a); const fb = this.find(b); if (fa === fb) return; this.father[fb] = fa; } equal(a, b) { return this.find(a) === this.find(b); } } var equationsPossible = function(equations) { const us = new UnionSet(); const base = 'a'.charCodeAt(); // merge, when equal for(let i = 0; i < equations.length; i++) { const item = equations[i]; if (item[1] === '!') continue; const a = item[0].charCodeAt() - base; const b = item[3].charCodeAt() - base; us.merge(a, b); } // check, when different for(let i = 0; i < equations.length; i++) { const item = equations[i]; if (item[1] === '=') continue; const a = item[0].charCodeAt() - base; const b = item[3].charCodeAt() - base; if (us.equal(a, b)) return false; } return true; };
Satisfiability of Equality Equations
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. &nbsp; Example 1: Input: numerator = 1, denominator = 2 Output: "0.5" Example 2: Input: numerator = 2, denominator = 1 Output: "2" Example 3: Input: numerator = 4, denominator = 333 Output: "0.(012)" &nbsp; Constraints: -231 &lt;=&nbsp;numerator, denominator &lt;= 231 - 1 denominator != 0
from collections import defaultdict class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: sign = "" if numerator*denominator >= 0 else "-" numerator, denominator = abs(numerator), abs(denominator) a = numerator//denominator numerator %= denominator if not numerator: return sign+str(a) fractions = [] index = defaultdict(int) while 10*numerator not in index: numerator *= 10 index[numerator] = len(fractions) fractions.append(str(numerator//denominator)) numerator %= denominator i = index[10*numerator] return sign+str(a)+"."+"".join(fractions[:i])+"("+"".join(fractions[i:])+")" if numerator else sign+str(a)+"."+"".join(fractions[:i])
class Solution { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0){ return "0"; } StringBuilder sb = new StringBuilder(""); if(numerator<0 && denominator>0 || numerator>0 && denominator<0){ sb.append("-"); } long divisor = Math.abs((long)numerator); long dividend = Math.abs((long)denominator); long remainder = divisor % dividend; sb.append(divisor / dividend); if(remainder == 0){ return sb.toString(); } sb.append("."); HashMap<Long, Integer> map = new HashMap<Long, Integer>(); while(remainder!=0){ if(map.containsKey(remainder)){ sb.insert(map.get(remainder), "("); sb.append(")"); break; } map.put(remainder, sb.length()); remainder*= 10; sb.append(remainder/dividend); remainder%= dividend; } return sb.toString(); } }
class Solution { public: string fractionToDecimal(int numerator, int denominator) { unordered_map<int, int> umap; string result = ""; if ((double) numerator / (double) denominator < 0) result.push_back('-'); long long l_numerator = numerator > 0 ? numerator : -(long long) numerator; long long l_denominator = denominator > 0 ? denominator : -(long long) denominator; long long quotient = l_numerator / l_denominator; long long remainder = l_numerator % l_denominator; result.append(to_string(quotient)); if (remainder == 0) return result; result.push_back('.'); int position = result.size(); umap[remainder] = position++; while (remainder != 0) { l_numerator = remainder * 10; quotient = l_numerator / l_denominator; remainder = l_numerator % l_denominator; char digit = '0' + quotient; result.push_back(digit); if (umap.find(remainder) != umap.end()) { result.insert(umap[remainder], 1, '('); result.push_back(')'); return result; } umap[remainder] = position++; } return result; } };
var fractionToDecimal = function(numerator, denominator) { if(numerator == 0) return '0' let result = '' if(numerator*denominator <0){ result += '-' } let dividend = Math.abs(numerator) let divisor = Math.abs(denominator) result += Math.floor(dividend/divisor).toString() let remainder = dividend % divisor if(remainder == 0) return result result += '.' let map1 = new Map() while(remainder != 0){ if(map1.has(remainder)){ let i = map1.get(remainder) result = result.slice(0, i) + '(' + result.slice(i) + ')' break; } map1.set(remainder, result.length) remainder *= 10 result += Math.floor(remainder/divisor).toString() remainder %= divisor } return result };
Fraction to Recurring Decimal
Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. &nbsp; Example 1: Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: n = 5 Output: 1 Explanation: 5! = 120, one trailing zero. Example 3: Input: n = 0 Output: 0 &nbsp; Constraints: 0 &lt;= n &lt;= 104 &nbsp; Follow up: Could you write a solution that works in logarithmic time complexity?
class Solution: def trailingZeroes(self, n: int) -> int: res = 0 for i in range(2, n+1): while i > 0 and i%5 == 0: i //= 5 res += 1 return res
class Solution { public int trailingZeroes(int n) { int count=0; while(n>1) {count+=n/5; n=n/5;} return count; } }
class Solution { public: int trailingZeroes(int n) { int ni=0, mi=0; for (int i=1; i<=n; i++){ int x=i; while (x%2==0){ x= x>>1; ni++; } while (x%5==0){ x= x/5; mi++; } } return min(mi,ni); } };
var trailingZeroes = function(n) { let count=0 while(n>=5){ count += ~~(n/5) n= ~~(n/5) } return count };
Factorial Trailing Zeroes
You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. Return the maximum value of F(0), F(1), ..., F(n-1). The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: nums = [4,3,2,6] Output: 26 Explanation: F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. Example 2: Input: nums = [100] Output: 0 &nbsp; Constraints: n == nums.length 1 &lt;= n &lt;= 105 -100 &lt;= nums[i] &lt;= 100
class Solution: def maxRotateFunction(self, nums: List[int]) -> int: preSum, cur = 0, 0 for i in range(len(nums)): cur += i * nums[i] preSum += nums[i] ans = cur for i in range(1, len(nums)): cur -= len(nums) * nums[len(nums) - i] cur += preSum ans = max(ans, cur) return ans
class Solution { public int maxRotateFunction(int[] nums) { int sum1 =0,sum2 = 0; for(int i=0;i<nums.length;i++){ sum1 += nums[i]; sum2 += i*nums[i]; } int result = sum2; for(int i=0;i<nums.length;i++){ sum2 = sum2-sum1+(nums.length)*nums[i]; result = Math.max(result,sum2); } return result; } }
class Solution { public: int maxRotateFunction(vector<int>& A) { long sum = 0, fn = 0; int len = A.size(); for(int i=0;i<len;i++) { sum += A[i]; fn += (i * A[i]); } long l = 1, r; long newfn = fn; while(l < len) { r = l + len - 1; long removed = (l-1) * A[l-1]; long added = r * A[r%len]; newfn = newfn - removed + added - sum; fn = max(fn, newfn); l++; } return (int)fn; } };
var maxRotateFunction = function(nums) { let n = nums.length; let dp = 0; let sum = 0; for (let i=0; i<n;i++) { sum += nums[i]; dp += i*nums[i]; } let max = dp; for (let i=1; i<n;i++) { dp += sum - nums[n-i]*n; max = Math.max(max, dp); } return max; };
Rotate Function
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid. The following rules define a valid string: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "". &nbsp; Example 1: Input: s = "()" Output: true Example 2: Input: s = "(*)" Output: true Example 3: Input: s = "(*))" Output: true &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s[i] is '(', ')' or '*'.
class Solution: def checkValidString(self, s: str) -> bool: left,right,star = deque(), deque(), deque() #indexes of all unmatched left right parens and all '*' # O(n) where n=len(s) for i,c in enumerate(s): if c == '(': # we just append left paren's index left.append(i) elif c == ')': # we check if we can find a match of left paren if left and left[-1] < i: left.pop() else: right.append(i) else: #'*' case we just add the postion star.append(i) if not left and not right: return True elif not star: return False #no star to save the string, return False l,r = 0 ,len(star)-1 #O(n) since star will be length less than n # Note: left, right,and star are always kept in ascending order! And for any i in left, j in right, i > j, or they would have been matched in the previous for loop. while l<=r: if left: if left[-1]< star[r]: # we keep using right most star to match with right most '(' left.pop() r -= 1 else: return False # even the right most '*' can not match a '(', we can not fix the string. if right: if right[0] > star[l]: right.popleft() l += 1 else: return False if not left and not right: return True #if after some fix, all matched, we return True
class Solution{ public boolean checkValidString(String s){ Stack<Integer> stack = new Stack<>(); Stack<Integer> star = new Stack<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(' ) stack.push(i); else if(s.charAt(i)=='*') star.push(i); else { if(!stack.isEmpty()) stack.pop(); else if(!star.isEmpty()) star.pop(); else return false; } } while(!stack.isEmpty()){ if(star.isEmpty()) return false; else if( stack.peek()<star.peek()) { star.pop(); stack.pop(); } else return false; } return true; } }
class Solution { public: bool checkValidString(string s) { unordered_map<int, unordered_map<int, bool>> m; return dfs(s, 0, 0, m); } // b: balanced number bool dfs (string s, int index, int b, unordered_map<int, unordered_map<int, bool>>& m) { if (index == s.length()) { if (b == 0 ) return true; else return false; } if (m.count(index) && m[index].count(b)) return m[index][b]; if (s[index] == '(') { m[index][b] = dfs(s, index+1, b+1, m); } else if (s[index] == ')') { m[index][b] = (b!= 0 && dfs(s, index+1, b-1, m)); }else { m[index][b] = dfs(s,index+1, b, m) || dfs(s, index+1, b+1, m) || (b != 0 && dfs(s, index+1, b-1, m)); } return m[index][b]; } };
/** * @param {string} s * @return {boolean} */ var checkValidString = function(s) { let map = {} return check(s,0,0,map); }; function check(s,index,open,map){ if(index == s.length){ return open == 0; } if(open < 0){ return false; } let string = index.toString() + "##" + open.toString(); if(string in map){ return map[string] } if(s[index] == '('){ let l = check(s,index+1,open+1,map) map[string] = l return l }else if (s[index] == ')'){ let r = check(s,index+1,open-1,map) map[string] = r; return r }else { let lr = check(s,index+1,open+1,map) || check(s,index+1,open-1,map) || check(s,index+1,open,map) map[string] = lr; return lr } }
Valid Parenthesis String
There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. &nbsp; Example 1: Input: numBottles = 9, numExchange = 3 Output: 13 Explanation: You can exchange 3 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 9 + 3 + 1 = 13. Example 2: Input: numBottles = 15, numExchange = 4 Output: 19 Explanation: You can exchange 4 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 15 + 3 + 1 = 19. &nbsp; Constraints: 1 &lt;= numBottles &lt;= 100 2 &lt;= numExchange &lt;= 100
class Solution: def numWaterBottles(self, a: int, b: int) -> int: def sol(a,b,e,res): if a!=0: res += a if (a+e)<b: return res a += e new=a//b e = a-(new*b) a=new return sol(a,b,e,res) return sol(a,b,0,0)
class Solution { public int numWaterBottles(int numBottles, int numExchange) { int drinkedBottles = numBottles; int emptyBottles = numBottles; while(emptyBottles >= numExchange){ int gainedBottles = emptyBottles / numExchange; drinkedBottles += gainedBottles; int unusedEmptyBottles = emptyBottles % numExchange; emptyBottles = gainedBottles + unusedEmptyBottles; } return drinkedBottles; } }
class Solution { public: int numWaterBottles(int numBottles, int numExchange) { int ex=0,remain=0,res=numBottles; while(numBottles>=numExchange){ remain=numBottles%numExchange; numBottles=numBottles/numExchange; res+=numBottles; numBottles+=remain; cout<<numBottles<<" "; } return res; } };
var numWaterBottles = function(numBottles, numExchange) { let count = 0; let emptyBottles = 0; while (numBottles > 0) { count += numBottles; emptyBottles += numBottles; numBottles = Math.floor(emptyBottles / numExchange); emptyBottles -= numBottles * numExchange; } return count; };
Water Bottles
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. &nbsp; Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consists of lowercase English letters. &nbsp; Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
class Solution: def smallestSubsequence(self, s: str) -> str: # calculate the last occurence of each characters in s last_occurence = {c: i for i, c in enumerate(s)} stack = [] # check if element is in stack instack = set() for i, c in enumerate(s): if c not in instack: # check if stack already have char larger then current char # and if char in stack will occur later again, remove that from stack while stack and stack[-1] > c and last_occurence[stack[-1]] > i: instack.remove(stack[-1]) stack.pop() instack.add(c) stack.append(c) return "".join(stack)
class Solution { public String smallestSubsequence(String s) { boolean[] inStack = new boolean [26]; int[] lastIdx = new int [26]; Arrays.fill(lastIdx,-1); for(int i = 0; i < s.length(); i++){ lastIdx[s.charAt(i)-'a'] = i; } Deque<Character> dq = new ArrayDeque<>(); for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(inStack[ch-'a']){ continue; } while(!dq.isEmpty() && dq.peekLast() > ch && lastIdx[dq.peekLast()-'a'] > i){ inStack[dq.pollLast()-'a'] = false; } dq.addLast(ch); inStack[ch-'a'] = true; } StringBuilder sb = new StringBuilder(); while(!dq.isEmpty()){ sb.append(dq.pollFirst()); } return sb.toString(); } }
class Solution { public: string smallestSubsequence(string s) { string st=""; unordered_map< char ,int> m; vector< bool> vis( 26,false); for( int i=0;i<s.size();i++) m[s[i]]++; stack< char> t; t.push(s[0]) , m[s[0]]--; st+=s[0]; vis[s[0]-'a']=true; for( int i=1;i<s.size();i++){ m[ s[i]]--; if(!vis[ s[i]-'a']){ while( !t.empty() && m[t.top()] >0 && t.top() > s[i]){ st.pop_back(); vis[ t.top()-'a']=false; t.pop(); } t.push(s[i]); vis[s[i]-'a']=true; st=st+s[i]; } } return st; } };
var smallestSubsequence = function(s) { let stack = []; for(let i = 0; i < s.length; i++){ if(stack.includes(s[i])) continue; while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) stack.pop(); stack.push(s[i]); } return stack.join(""); };
Smallest Subsequence of Distinct Characters
A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 1, a = 2, b = 3 Output: 2 Example 2: Input: n = 4, a = 2, b = 3 Output: 6 &nbsp; Constraints: 1 &lt;= n &lt;= 109 2 &lt;= a, b &lt;= 4 * 104
class Solution: def nthMagicalNumber(self, N: int, A: int, B: int) -> int: import math lcm= A*B // math.gcd(A,B) l,r=2,10**14 while l<=r: mid=(l+r)//2 n = mid//A+mid//B-mid//lcm if n>=N: r=mid-1 else: l=mid+1 return l%(10**9+7)
class Solution { public int nthMagicalNumber(int n, int a, int b) { long N=(long)n; long A=(long)a; long B=(long)b; long mod=1000000007; long min=Math.min(A,B); long low=min; long high=min*N; long ans=0; while(low<=high) { long mid=(high-low)/2+low; long x=mid/A+mid/B-mid/lcm(A,B); if(x>=N) { ans=mid; high=mid-1; } else if(x<N) { low=mid+1; } else{ high=mid-1; } } ans=ans%mod; return (int)ans; } long lcm(long a,long b) { long tmpA=a; long tmpB=b; while(a>0) { long temp=a; a=b%a; b=temp; } return tmpA*tmpB/b; } }
class Solution { public: int lcm(int a, int b) // Finding the LCM of a and b { if(a==b) return a; if(a > b) { int count = 1; while(true) { if((a*count)%b==0) return a*count; count++; } } int count = 1; while(true) { if((b*count)%a==0) return b*count; count++; } return -1; // garbage value--ignore. } int nthMagicalNumber(int n, int a, int b) { long long int comm = lcm(a,b); //common element long long int first = (((comm*2) - comm) / a) - 1; //no. of elements appearing before the comm multiples (a). long long int second = (((comm*2) - comm) / b) - 1; //no. of elements appearing before the comm multiples(b). long long int landmark = (n / (first + second + 1)) * comm; // last common element before nth number. long long int offset = n % (first + second + 1); // how many numbers to consider after last common long long int p = landmark, q = landmark; // initialisations to find the offset from the landmarked element long long int ans = landmark; for(int i=1;i<=offset;i++) // forwarding offset number of times. { if(p+a < q+b) //this logic easily takes care of which elements to be considered for the current iteration. { ans = p+a; p = p+a; } else { ans = q+b; q = q+b; } } return (ans%1000000007); //returning the answer. } }; /* a and b 1st step would be to find the LCM of the two numbers --> Multiples of LCM would be the common numbers in the sequential pattern. The next step would be to find the numbers of a and numbers of b appearing between the common number. DRY : 4 and 6 4 -> 4 8 12 16 20 24 28 32 36 40 --> 6 -> 6 12 18 24 30 36 42 48 54 60 --> 4 6 8 12 16 18 20 24 --> n/(f + s) ---> 23/4 = 5 and 3 5th -----> (comm * 5 = 60) ------> */
/** * @param {number} n * @param {number} a * @param {number} b * @return {number} */ var nthMagicalNumber = function(n, a, b) { const gcd = (a1,b1)=>{ if(b1===0) return a1; return gcd(b1,a1%b1) } const modulo = 1000000007; let low = 0; let high = 10e17; let lcmAB = Math.floor((a*b)/gcd(a,b)); while(low<high){ let mid = Math.floor((low+high)/2); let ans = Math.floor(mid/a)+Math.floor(mid/b)-Math.floor(mid/lcmAB); if(ans<n){ low = mid + 1; }else{ high = mid; } } return high%modulo; };
Nth Magical Number
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 &lt;= k &lt; nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible. &nbsp; Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true Example 2: Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false &nbsp; Constraints: 1 &lt;= nums.length &lt;= 5000 -104 &lt;= nums[i] &lt;= 104 nums is guaranteed to be rotated at some pivot. -104 &lt;= target &lt;= 104 &nbsp; Follow up: This problem is similar to&nbsp;Search in Rotated Sorted Array, but&nbsp;nums may contain duplicates. Would this affect the runtime complexity? How and why?
class Solution: def search(self, nums: List[int], target: int) -> bool: nums.sort() low=0 high=len(nums)-1 while low<=high: mid=(low+high)//2 if nums[mid]==target: return True elif nums[mid]>target: high=mid-1 else: low=mid+1 return False
class Solution { public boolean search(int[] nums, int target) { if (nums == null || nums.length == 0) return false; int left = 0, right = nums.length-1; int start = 0; //1. find index of the smallest element while(left < right) { while (left < right && nums[left] == nums[left + 1]) ++left; while (left < right && nums[right] == nums[right - 1]) --right; int mid = left + (right-left)/2; if (nums[mid] > nums[right]) { left = mid +1; } else right = mid; } //2. figure out in which side our target lies start = left; left = 0; right = nums.length-1; if (target >= nums[start] && target <= nums[right]) left = start; else right = start; //3. Run normal binary search in sorted half. while(left <= right) { int mid = left + (right - left)/2; if (nums[mid] == target) return true; if (nums[mid] > target) right = mid-1; else left = mid + 1; } return false; } }
class Solution { public: bool search(vector<int>& nums, int target) { if( nums[0] == target or nums.back() == target ) return true; // this line is redundant it reduces only the worst case when all elements are same to O(1) const int n = nums.size(); int l = 0 , h = n-1; while( l+1 < n and nums[l] == nums[l+1]) l++; // if all elements are same if( l == n-1){ if( nums[0] == target ) return true; else return false; } // while last element is equal to 1st element while( h >= 0 and nums[h] == nums[0] ) h--; int start = l , end = h; // find the point of pivot ie from where the rotation starts int pivot = -1; while( l <= h ){ int mid = l + (h-l)/2; if( nums[mid] >= nums[0] ) l = mid+1; else { pivot = mid; h = mid-1; } } if( pivot == -1 ) l = start , h = end; // if no pivot exits then search space is from start -e end else { if( target > nums[end] ) l = start , h = pivot-1; // search space second half else l = pivot , h = end; // search space first half } // normal binary search while ( l <= h ){ int mid = l + (h-l)/2; if( nums[mid] > target ) h = mid-1; else if( nums[mid] < target ) l = mid+1; else return true; } return false; } };
var search = function(nums, target) { let found = nums.findIndex(c=> c==target); if(found === -1) return false else return true };
Search in Rotated Sorted Array II
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1. &nbsp; Example 1: Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. Example 2: Input: clips = [[0,1],[1,2]], time = 5 Output: -1 Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. Example 3: Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 Output: 3 Explanation: We can take clips [0,4], [4,7], and [6,9]. &nbsp; Constraints: 1 &lt;= clips.length &lt;= 100 0 &lt;= starti &lt;= endi &lt;= 100 1 &lt;= time &lt;= 100
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: dp = [float('inf')] * (T + 1) dp[0] = 0 for i in range(1, T + 1): for start, end in clips: if start <= i <= end: dp[i] = min(dp[start] + 1, dp[i]) if dp[T] == float('inf'): return -1 return dp[T]
class Solution { public int videoStitching(int[][] clips, int time) { Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]); int n = clips.length; int interval[] = new int[2]; int cuts = 0; while(true){ cuts++; int can_reach = 0; for(int i = interval[0]; i <= interval[1]; i++){ int j = 0; while(j < n){ if(clips[j][0] < i){ j++; } else if(clips[j][0] == i){ can_reach = Math.max(can_reach , clips[j][1]); j++; } else{ break; } } if(can_reach >= time) return cuts; } interval[0] = interval[1] + 1; interval[1] = can_reach; if(interval[0] > interval[1]) return -1; } } }
class Solution { public: static bool comp(vector<int> a, vector<int> b){ if(a[0]<b[0]) return true; else if(a[0]==b[0]) return a[1]>b[1]; return false; } int videoStitching(vector<vector<int>>& clips, int time) { sort(clips.begin(), clips.end(), comp); vector<vector<int>> res; //check if 0 is present or not if(clips[0][0] != 0) return -1; res.push_back(clips[0]); //if 1. First check if the required interval is already covered or not //if 2. If the first value of the already inserted element in res is equal, then the next value if obviously smaller interval because of custom sorting so, we should skip it //if 3. Cover every value by checking if the interval is required or not (already present?) if required then insert it //if 3.1. Check if the interval to be inserted covers the interval at the back for example [0,4], [2,6], now if we were to insert the interval [4, 7], then [2,6] is no more requried, then pop_back. for(int i=1; i<clips.size(); i++){ if(res.back()[1]>=time) break; if(clips[i][0]==res.back()[0]) continue; if(clips[i][1]>res.back()[1]){ if(res.size()>1 and res[res.size()-2][1]>=clips[i][0]) res.pop_back(); res.push_back(clips[i]); } } //Check if the compelete range from 0 to time is covered or not int prev = res[0][1]; for(int i=1; i<res.size(); i++){ if(res[i][0]>prev) return -1; prev = res[i][1]; } //check explicitly for the last value if(res.back()[1]<time) return -1; return res.size(); } };
/** https://leetcode.com/problems/video-stitching/ * @param {number[][]} clips * @param {number} time * @return {number} */ var videoStitching = function(clips, time) { // Memo this.memo = new Map(); // Sort the clips for easier iteration clips.sort((a, b) => a[0] - b[0]); // If the output is `Infinity` it means the task is impossible let out = dp(clips, time, 0, -1); return out === Infinity ? -1 : out; }; var dp = function(clips, time, index, endTime) { let key = `${index}_${endTime}`; // Base, we got all the clip we need if (endTime >= time) { return 0; } // Reach end of the clip array if (index === clips.length) { return Infinity; } // Return form memo if (this.memo.has(key) === true) { return this.memo.get(key); } // There are 2 choices, include clip in current `index` or exclude // Include clip in current `index` let include = Infinity; // We can only include clip in current `index` if either: // - the `endTime` is -1 and current clip's starting is 0, in which this clip is the first segment // - the `endTime` is greater than current clip's starting time, in which this clip has end time greater than our `endTime` if ((endTime < 0 && clips[index][0] === 0) || endTime >= clips[index][0]) { // Update the next `endTime` with the current clip's end time, `clips[index][1]` let nextEndTime = clips[index][1]; include = 1 + dp(clips, time, index + 1, nextEndTime); } // Exclude clip in current `index` let exclude = dp(clips, time, index + 1, endTime); // Find which one has less clips let count = Math.min(include, exclude); // Set memo this.memo.set(key, count); return count; };
Video Stitching
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. &nbsp; Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false &nbsp; Constraints: 1 &lt;= flowerbed.length &lt;= 2 * 104 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 &lt;= n &lt;= flowerbed.length
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: f = [0] + flowerbed + [0] i, could_plant = 1, 0 while could_plant < n and i < len(f) - 1: if f[i + 1]: # 0 0 1 -> skip 3 i += 3 elif f[i]: # 0 1 0 -> skip 2 i += 2 elif f[i - 1]: # 1 0 0 -> skip 1 i += 1 else: # 0 0 0 -> plant, becomes 0 1 0 -> skip 2 could_plant += 1 i += 2 return n <= could_plant
class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { if(flowerbed[0] != 1){ n--; flowerbed[0] = 1; } for(int i = 1; i < flowerbed.length; i++){ if(flowerbed[i - 1] == 1 && flowerbed[i] == 1){ flowerbed[i - 1] = 0; n++; } if(flowerbed[i - 1] != 1 && flowerbed[i] != 1){ flowerbed[i] = 1; n--; } } return (n <= 0) ? true: false; } }
class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int count = 1; int result = 0; for(int i=0; i<flowerbed.size(); i++) { if(flowerbed[i] == 0) { count++; }else { result += (count-1)/2; count = 0; } } if(count != 0) result += count/2; return result>=n; } };
/** * @param {number[]} flowerbed * @param {number} n * @return {boolean} */ var canPlaceFlowers = function(flowerbed, n) { for(let i=0 ; i<flowerbed.length ; i++) { if((i===0 || flowerbed[i-1]===0) && flowerbed[i]===0 && (i===flowerbed.length-1 || flowerbed[i+1]===0)) { flowerbed[i]=1; n--; } } return n < 1; };
Can Place Flowers
You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. &nbsp; Example 1: Input: rungs = [1,3,5,10], dist = 2 Output: 2 Explanation: You currently cannot reach the last rung. Add rungs at heights 7 and 8 to climb this ladder. The ladder will now have rungs at [1,3,5,7,8,10]. Example 2: Input: rungs = [3,6,8,10], dist = 3 Output: 0 Explanation: This ladder can be climbed without adding additional rungs. Example 3: Input: rungs = [3,4,6,7], dist = 2 Output: 1 Explanation: You currently cannot reach the first rung from the ground. Add a rung at height 1 to climb this ladder. The ladder will now have rungs at [1,3,4,6,7]. &nbsp; Constraints: 1 &lt;= rungs.length &lt;= 105 1 &lt;= rungs[i] &lt;= 109 1 &lt;= dist &lt;= 109 rungs is strictly increasing.
class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: rungs=[0]+rungs i,ans=1,0 while i<len(rungs): if rungs[i]-rungs[i-1] > dist: ans+=ceil((rungs[i]-rungs[i-1])/dist)-1 i+=1 return ans
class Solution { public int addRungs(int[] rungs, int dist) { int ans = 0; for (int i=0 ; i<rungs.length ; i++) { int d = (i==0) ? rungs[i] : rungs[i] - rungs[i-1]; if ( d > dist ) { ans += d/dist; ans += ( d%dist == 0 ) ? -1 : 0; } } return ans; } }
class Solution { public: int addRungs(vector<int>& rungs, int dist) { //to keep the track of the number of extra rung to be added long long int count = 0; //our curr pos at the beggining long long int currpos = 0; //to keep the track of the next pos to be climed long long int nextposidx = 0; while(true) { if(currpos == rungs[rungs.size()-1]) { break; } if((rungs[nextposidx] - currpos) <= dist) { currpos = rungs[nextposidx]; nextposidx++; } else { //cout<<"hello"<<endl; long long int temp = (rungs[nextposidx] - currpos); //cout<<"temp = "<<temp<<endl; if((temp%dist) == 0) { long long int val = temp/dist; count = count + (val - 1); } else { long long int val = floor(((temp*1.00)/(dist*1.00))); count = count + (val); } currpos = rungs[nextposidx]; } } return count; } };
var addRungs = function(rungs, dist) { let res = 0; let prev = 0; for ( let i = 0; i < rungs.length; i++ ){ res += Math.floor(( rungs[i] - prev - 1 ) / dist ); prev = rungs[i]; } return res; };
Add Minimum Number of Rungs
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. &nbsp; Example 1: Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false Example 2: Input: trips = [[2,1,5],[3,3,7]], capacity = 5 Output: true &nbsp; Constraints: 1 &lt;= trips.length &lt;= 1000 trips[i].length == 3 1 &lt;= numPassengersi &lt;= 100 0 &lt;= fromi &lt; toi &lt;= 1000 1 &lt;= capacity &lt;= 105
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: endheap = [] startheap = [] for i in range(len(trips)): endheap.append((trips[i][2],trips[i][0],trips[i][1])) startheap.append((trips[i][1],trips[i][0],trips[i][2])) heapify(endheap) heapify(startheap) cur = 0 while startheap: start,num,end = heappop(startheap) while start >= endheap[0][0]: newend,newnum,newstart = heappop(endheap) cur -= newnum cur += num print(cur) if cur >capacity: return False return True
class Solution { public boolean carPooling(int[][] trips, int capacity) { Map<Integer, Integer> destinationToPassengers = new TreeMap<>(); for(int[] trip : trips) { int currPassengersAtPickup = destinationToPassengers.getOrDefault(trip[1], 0); int currPassengersAtDrop = destinationToPassengers.getOrDefault(trip[2], 0); destinationToPassengers.put(trip[1], currPassengersAtPickup + trip[0]); destinationToPassengers.put(trip[2], currPassengersAtDrop - trip[0]); } int currPassengers = 0; for(int passengers : destinationToPassengers.values()) { currPassengers += passengers; if(currPassengers > capacity) { return false; } } return true; } }
class Solution { typedef pair<int, int> pd; public: bool carPooling(vector<vector<int>>& trips, int capacity) { int seat=0; priority_queue<pd, vector<pd>, greater<pd>>pq; for(auto it : trips) { pq.push({it[1], +it[0]}); pq.push({it[2], -it[0]}); } while(!pq.empty()) { // cout<<pq.top().first<<" "<<pq.top().second<<endl; // cout<<"seat-"<<seat<<endl; seat+=pq.top().second; if(seat>capacity) return false; pq.pop(); } return true; } };
/** * @param {number[][]} trips * @param {number} capacity * @return {boolean} */ var carPooling = function(trips, capacity) { // sort trips by destination distance trips.sort((a, b) => a[2] - b[2]); // build result array, using max distance const lastTrip = trips[trips.length - 1]; const maxDistance = lastTrip[lastTrip.length - 1]; const arr = new Array(maxDistance + 1).fill(0); // build partial sum array for (const [val, start, end] of trips) { arr[start] += val; arr[end] -= val; } // build combined sum array let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; if (sum > capacity) return false; } return true; };
Car Pooling
Given an array, rotate the array to the right by k steps, where k is non-negative. &nbsp; Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -231 &lt;= nums[i] &lt;= 231 - 1 0 &lt;= k &lt;= 105 &nbsp; Follow up: Try to come up with as many solutions as you can. There are at least three different ways to solve this problem. Could you do it in-place with O(1) extra space?
class Solution: def reverse(self,arr,left,right): while left < right: arr[left],arr[right] = arr[right], arr[left] left, right = left + 1, right - 1 return arr def rotate(self, nums: List[int], k: int) -> None: length = len(nums) k = k % length l, r = 0, length - 1 nums = self.reverse(nums,l,r) l, r = 0, k - 1 nums = self.reverse(nums,l,r) l, r = k, length - 1 nums = self.reverse(nums,l,r) return nums
class Solution { public void rotate(int[] nums, int k) { reverse(nums , 0 , nums.length-1); reverse(nums , 0 , k-1); reverse(nums , k , nums.length -1); } public static void reverse(int[] arr , int start , int end){ while(start<end){ int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } }
class Solution { public: void rotate(vector<int>& nums, int k) { vector<int> temp(nums.size()); for(int i = 0; i < nums.size() ;i++){ temp[(i+k)%nums.size()] = nums[i]; } nums = temp; } };
/** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ var rotate = function(nums, k) { const len = nums.length; k %= len; const t = nums.splice(len - k, k); nums.unshift(...t); };
Rotate Array
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key. &nbsp; Example 1: Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W" Explanation: The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: s = "2-5g-3-J", k = 2 Output: "2-5G-3J" Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s consists of English letters, digits, and dashes '-'. 1 &lt;= k &lt;= 104
class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: new_str = s.replace("-", "") res = "" j = len(new_str)-1 i = 0 while j >= 0: res += new_str[j].upper() i += 1 if i == k and j != 0: res += "-" i = 0 j -= 1 return res[::-1]
class Solution { public String licenseKeyFormatting(String s, int k) { StringBuilder answer = new StringBuilder(); int length = 0; // Iterate Backwards to fullfill first group condition for(int i=s.length()-1;i>=0;i--) { if(s.charAt(i) == '-') { continue; } if(length > 0 && length % k == 0) { answer.append('-'); } answer.append(Character.toUpperCase(s.charAt(i))); length++; } return answer.reverse().toString(); } }
class Solution { public: string licenseKeyFormatting(string s, int k) { stack<char>st; string ans=""; for(int i=0;i<s.length();i++){ if(isalpha(s[i]) || isdigit(s[i])){ st.push(s[i]); } } int i=0; while(st.size()>0){ char ch=st.top(); st.pop(); if(isalpha(ch)) { ch=toupper(ch); } ans+=ch; if((i+1)%k==0 && st.size()!=0) ans+='-'; i++; } reverse(ans.begin(),ans.end()); return ans; } };
// Please upvote if you like the solution. Thanks var licenseKeyFormatting = function(s, k) { let str=s.replace(/[^A-Za-z0-9]/g,"").toUpperCase() let ans="" let i=str.length; while(i>0){ ans="-"+str.substring(i-k,i)+ans // we are taking k characters from the end of string and adding it to answer i=i-k } return (ans.substring(1)) // removing the "-" which is present in the start of ans };
License Key Formatting
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6. [1, 2, 3, 4] is not possible since the differences are not correct. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0. &nbsp; Example 1: Input: differences = [1,-3,4], lower = 1, upper = 6 Output: 2 Explanation: The possible hidden sequences are: - [3, 4, 1, 5] - [4, 5, 2, 6] Thus, we return 2. Example 2: Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5 Output: 4 Explanation: The possible hidden sequences are: - [-3, 0, -4, 1, 2, 0] - [-2, 1, -3, 2, 3, 1] - [-1, 2, -2, 3, 4, 2] - [0, 3, -1, 4, 5, 3] Thus, we return 4. Example 3: Input: differences = [4,-7,2], lower = 3, upper = 6 Output: 0 Explanation: There are no possible hidden sequences. Thus, we return 0. &nbsp; Constraints: n == differences.length 1 &lt;= n &lt;= 105 -105 &lt;= differences[i] &lt;= 105 -105 &lt;= lower &lt;= upper &lt;= 105
class Solution: def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int: l = [0] for i in differences: l.append(l[-1]+i) return max(0,(upper-lower+1)-(max(l)-min(l)))
class Solution { public int numberOfArrays(int[] differences, int lower, int upper) { ArrayList<Integer> ans = new ArrayList<>(); ans.add(lower); int mn = lower; int mx = lower; for (int i = 0; i < differences.length; i++) { int d = differences[i]; ans.add(d + ans.get(ans.size() - 1)); mn = Math.min(mn, ans.get(ans.size() - 1)); mx = Math.max(mx, ans.get(ans.size() - 1)); } int add = lower - mn; for (int i = 0; i < ans.size(); i++) { ans.set(i, ans.get(i) + add); } for (int i = 0; i < ans.size(); i++) { if (ans.get(i) < lower || upper < ans.get(i)) { return 0; } } int add2 = upper - mx; return add2 - add + 1; } }
using ll = long long int; class Solution { public: int numberOfArrays(vector<int>& differences, int lower, int upper) { vector<ll> ans; ans.push_back(lower); ll mn = lower; ll mx = lower; for (const auto& d: differences) { ans.push_back(d + ans.back()); mn = min(mn, ans.back()); mx = max(mx, ans.back()); } ll add = lower - mn; for (auto& i: ans) i += add; for (auto& i: ans) if (i < lower or upper < i) return 0; ll add2 = upper - mx; return add2 - add + 1; } };
var numberOfArrays = function(differences, lower, upper) { let temp = 0; let res = 0; let n = lower; for (let i = 0; i < differences.length; i++) { temp += differences[i]; differences[i] = temp; } const min = Math.min(...differences); const max = Math.max(...differences); while (n <= upper) { if (n + min >= lower && n + max <= upper) res++; n++; } return res; };
Count the Hidden Sequences
You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 &lt;= i &lt;= n) into two arrays (possibly empty) numsleft and numsright: numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive). If i == 0, numsleft is empty, while numsright has all the elements of nums. If i == n, numsleft has all the elements of nums, while numsright is empty. The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright. Return all distinct indices that have the highest possible division score. You may return the answer in any order. &nbsp; Example 1: Input: nums = [0,0,1,0] Output: [2,4] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1. - 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2. - 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3. - 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2. - 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3. Indices 2 and 4 both have the highest possible division score 3. Note the answer [4,2] would also be accepted. Example 2: Input: nums = [0,0,0] Output: [3] Explanation: Division at index - 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0. - 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1. - 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2. - 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3. Only index 3 has the highest possible division score 3. Example 3: Input: nums = [1,1] Output: [0] Explanation: Division at index - 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2. - 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1. - 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0. Only index 0 has the highest possible division score 2. &nbsp; Constraints: n == nums.length 1 &lt;= n &lt;= 105 nums[i] is either 0 or 1.
class Solution: def maxScoreIndices(self, nums: List[int]) -> List[int]: zeroFromLeft = [0] * (len(nums) + 1) oneFromRight = [0] * (len(nums) + 1) for i in range(len(nums)): if nums[i] == 0: zeroFromLeft[i + 1] = zeroFromLeft[i] + 1 else: zeroFromLeft[i + 1] = zeroFromLeft[i] for i in range(len(nums))[::-1]: if nums[i] == 1: oneFromRight[i] = oneFromRight[i + 1] + 1 else: oneFromRight[i] = oneFromRight[i + 1] allSum = [0] * (len(nums) + 1) currentMax = 0 res = [] for i in range(len(nums) + 1): allSum[i] = oneFromRight[i] + zeroFromLeft[i] if allSum[i] > currentMax: res = [] currentMax = allSum[i] if allSum[i] == currentMax: res.append(i) return res
class Solution { public List<Integer> maxScoreIndices(int[] nums) { int N = nums.length; List<Integer> res = new ArrayList<>(); int[] pref = new int[N + 1]; pref[0] = 0; // at zeroth division we have no elements for(int i = 0; i < N; ++i) pref[i+1] = nums[i] + pref[i]; int maxScore = -1; int onesToRight, zeroesToLeft, currScore; for(int i = 0; i < N + 1; ++i) { onesToRight = pref[N] - pref[i]; zeroesToLeft = i - pref[i]; currScore = zeroesToLeft + onesToRight; if(currScore > maxScore) { res.clear(); maxScore = currScore; } if(currScore == maxScore) res.add(i); } return res; } }
class Solution { public: vector<int> maxScoreIndices(vector<int>& nums) { int n=nums.size(); if(n==1) { if(nums[0]==0) return {1}; else return {0}; } int one=0,zero=0; for(int i=0;i<n;i++) { if(nums[i]==1) one++; } if(nums[0]==0) zero++; vector<int> v; v.push_back(one); int ans=one; if(nums[0]==1) one--; for(int i=1;i<n;i++) { if(nums[i]==1) { v.push_back(zero+one); one--; } else { v.push_back(zero+one); zero++; } ans=max(ans,zero+one); } v.push_back(zero); vector<int> res; for(int i=0;i<=n;i++) { // cout<<v[i]<<" "; if(v[i]==ans) res.push_back(i); } return res; } };
/** * @param {number[]} nums * @return {number[]} */ var maxScoreIndices = function(nums) { let n=nums.length; // initialize 3 arrays for counting with n+1 size let zeros = new Array(n+1).fill(0); let ones = new Array(n+1).fill(0); let total = new Array(n+1).fill(0); // count no of zeros from left to right for(let i=0;i<n;i++){ if(nums[i]==0)zeros[i+1]=zeros[i]+1; else zeros[i+1]=zeros[i]; } // count no of ones from right to left for(let i=n-1;i>=0;i--){ if(nums[i]==1)ones[i]=ones[i+1]+1; else ones[i]=ones[i+1]; } // merge left and right to total and find max element let max=0; for(let i=0;i<n+1;i++){ total[i]=ones[i]+zeros[i]; if(total[i]>max)max=total[i]; } // Find occurrence of max elements and return those indexes let ans= []; for(let i=0;i<n+1;i++){ if(total[i]==max)ans.push(i); } return ans; };
All Divisions With the Highest Score of a Binary Array
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. &nbsp; Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 Example 2: Input: lists = [] Output: [] Example 3: Input: lists = [[]] Output: [] &nbsp; Constraints: k == lists.length 0 &lt;= k &lt;= 104 0 &lt;= lists[i].length &lt;= 500 -104 &lt;= lists[i][j] &lt;= 104 lists[i] is sorted in ascending order. The sum of lists[i].length will not exceed 104.
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next from heapq import heappush,heappop class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: heap = [] heapq.heapify(heap) start = end = ListNode(-1) for i in lists: if i: heappush(heap,(i.val,id(i),i)) while heap: val,iD,node = heappop(heap) end.next = node node = node.next end = end.next if node: heappush(heap,(node.val,id(node),node)) return start.next
class Solution { public ListNode mergeKLists(ListNode[] lists) { if(lists == null || lists.length < 1) return null; //add the first chunk of linkedlist to res, //so later we started from index 1 ListNode res = lists[0]; //traverse the lists and start merge by calling mergeTwo for(int i = 1; i < lists.length; i++){ res = mergeTwo(res, lists[i]); } return res; } //leetcode 21 technics private ListNode mergeTwo(ListNode l1, ListNode l2){ if(l1 == null) return l2; if(l2 == null) return l1; if(l1.val < l2.val){ l1.next = mergeTwo(l1.next, l2); return l1; } else{ l2.next = mergeTwo(l2.next, l1); return l2; } } }
class Solution { public: struct compare { bool operator()(ListNode* &a,ListNode* &b) { return a->val>b->val; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<ListNode*,vector<ListNode*>,compare>minh; for(int i=0;i<lists.size();i++) { if(lists[i]!=NULL) minh.push(lists[i]); } ListNode* head=new ListNode(0); ListNode* temp=head; while(minh.size()>0) { ListNode* p=minh.top(); minh.pop(); temp->next=new ListNode(p->val); temp=temp->next; if(p->next!=NULL) minh.push(p->next); } return head->next; } };
var mergeKLists = function(lists) { // Use min heap to keep track of the smallest node in constant time. // Enqueue and dequeue will be log(k) where k is the # of lists // b/c we only need to keep track of the next node for each list // at any given time. const minHeap = new MinPriorityQueue({ priority: item => item.val }); for (let head of lists) { if (head) minHeap.enqueue(head); } // Create tempHead that we initiate the new list with // Final list will start at tempHead.next const tempHead = new ListNode(); let curr = tempHead; while (!minHeap.isEmpty()) { const { val, next } = minHeap.dequeue().element; curr.next = new ListNode(val); curr = curr.next; if (next) minHeap.enqueue(next); } return tempHead.next; };
Merge k Sorted Lists
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it. For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7]. Return the minimum number of operations to make an array that is sorted in non-decreasing order. &nbsp; Example 1: Input: nums = [3,9,3] Output: 2 Explanation: Here are the steps to sort the array in non-decreasing order: - From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3] - From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3] There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2. Example 2: Input: nums = [1,2,3,4,5] Output: 0 Explanation: The array is already in non-decreasing order. Therefore, we return 0. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 109
class Solution: def minimumReplacement(self, nums) -> int: ans = 0 n = len(nums) curr = nums[-1] for i in range(n - 2, -1, -1): if nums[i] > curr: q = nums[i] // curr if nums[i] == curr * q: nums[i] = curr ans += q - 1 else: nums[i] = nums[i] // (q + 1) ans += q curr = nums[i] return ans
class Solution { public long minimumReplacement(int[] nums) { long ret = 0L; int n = nums.length; int last = nums[n - 1]; for(int i = n - 2;i >= 0; i--){ if(nums[i] <= last){ last = nums[i]; continue; } if(nums[i] % last == 0){ // split into nums[i] / last elements, operations cnt = nums[i] / last - 1; ret += nums[i] / last - 1; }else{ // split into k elements operations cnt = k - 1; int k = nums[i] / last + 1; // ceil ret += k - 1; last = nums[i] / k; // left most element max is nums[i] / k } } return ret; } }
class Solution { public: long long minimumReplacement(vector<int>& nums) { long long res=0; int n=nums.size(); int mxm=nums[n-1]; long long val; for(int i=n-2;i>=0;i--) { // minimum no. of elemetns nums[i] is divided such that every number is less than mxm and minimum is maximized val= ceil(nums[i]/(double)mxm); // no. of steps is val-1 res+=(val-1); // the new maximized minimum value val=nums[i]/val; mxm= val; } return res; } };
/** * @param {number[]} nums * @return {number} */ var minimumReplacement = function(nums) { const n = nums.length; let ans = 0; for(let i = n - 2 ; i >= 0 ; i--){ if(nums[i]>nums[i+1]){ const temp = Math.ceil(nums[i]/nums[i+1]); ans += temp - 1; nums[i] = Math.floor(nums[i]/temp); } } return ans; };
Minimum Replacements to Sort the Array
Given two integers num and k, consider a set of positive integers with the following properties: The units digit of each integer is k. The sum of the integers is num. Return the minimum possible size of such a set, or -1 if no such set exists. Note: The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0. The units digit of a number is the rightmost digit of the number. &nbsp; Example 1: Input: num = 58, k = 9 Output: 2 Explanation: One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9. Another valid set is [19,39]. It can be shown that 2 is the minimum possible size of a valid set. Example 2: Input: num = 37, k = 2 Output: -1 Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2. Example 3: Input: num = 0, k = 7 Output: 0 Explanation: The sum of an empty set is considered 0. &nbsp; Constraints: 0 &lt;= num &lt;= 3000 0 &lt;= k &lt;= 9
class Solution: def minimumNumbers(self, num: int, k: int) -> int: if num == 0: return 0 if k == 0: return 1 if num % 10 == 0 else -1 for n in range(1, min(num // k, 10) + 1): if (num - n * k) % 10 == 0: return n return -1
class Solution { public int minimumNumbers(int num, int k) { if(num == 0) return 0; if(k == 0) if(num % 10 == 0) //E.g. 20,1590,3000 return 1; else return -1; for(int i = 1; i <= num/k; i++) // Start with set size 1 and look for set having unit's digit equal to that of num if(num % 10 == ((i*k)%10)) // Look for equal unit's digit return i; return -1; } }
class Solution { public: //same code as that of coin change int coinChange(vector<int>& coins, int amount) { int Max = amount + 1; vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 0; i <= amount; i++) { for (int j = 0; j < coins.size(); j++) { if (coins[j] <= i && dp[i-coins[j]] !=INT_MAX) { dp[i] = min(dp[i], dp[i - coins[j]] + 1); } } } return dp[amount] == INT_MAX ? -1 : dp[amount]; } int minimumNumbers(int num, int k) { vector<int>res; for (int i = 0; i <= num; i++){ if (i % 10 == k) res.push_back(i); } return coinChange(res, num); } };
var minimumNumbers = function(num, k) { if (num === 0) return 0; for (let i = 1; i <= 10; i++) { if (k*i % 10 === num % 10 && k*i <= num) return i; if (k*i > num) return -1 } return -1; };
Sum of Numbers With Units Digit K
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e.,&nbsp;0 &lt;= i &lt; n). In one operation, you can select two indices x and y where 0 &lt;= x, y &lt; n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal. &nbsp; Example 1: Input: n = 3 Output: 2 Explanation: arr = [1, 3, 5] First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4] In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]. Example 2: Input: n = 6 Output: 9 &nbsp; Constraints: 1 &lt;= n &lt;= 104
class Solution: def minOperations(self, n: int) -> int: return sum([n-x for x in range(n) if x % 2 != 0])
class Solution { public int minOperations(int n) { int ans = (n/2)*(n/2); if(n%2==1){ ans += n/2; } return ans; } }
class Solution { public: int minOperations(int n) { int s=0; for(int i=0; i<= (n-1)/2; ++i){ s += fabs(n-(2*i+1)); } return s; } };
var minOperations = function(n) { let reqNum; if(n%2!=0){ reqNum = Math.floor(n/2)*2+1 }else{ reqNum = ((Math.floor(n/2))*2+1 + (Math.floor(n/2) -1)*2+1)/2 } let count = 0; for(let i=1; i<reqNum; i +=2){ count += (reqNum-i) } return count };
Minimum Operations to Make Array Equal
You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. You then do the following steps: If original is found in nums, multiply it by two (i.e., set original = 2 * original). Otherwise, stop the process. Repeat this process with the new number as long as you keep finding the number. Return the final value of original. &nbsp; Example 1: Input: nums = [5,3,6,1,12], original = 3 Output: 24 Explanation: - 3 is found in nums. 3 is multiplied by 2 to obtain 6. - 6 is found in nums. 6 is multiplied by 2 to obtain 12. - 12 is found in nums. 12 is multiplied by 2 to obtain 24. - 24 is not found in nums. Thus, 24 is returned. Example 2: Input: nums = [2,7,9], original = 4 Output: 4 Explanation: - 4 is not found in nums. Thus, 4 is returned. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 1 &lt;= nums[i], original &lt;= 1000
class Solution: def findFinalValue(self, nums: List[int], original: int) -> int: while original in nums: original *= 2 return original
class Solution { public int findFinalValue(int[] nums, int original) { HashSet<Integer> set = new HashSet<>(); for(int i : nums) if(i >= original) set.add(i); while(true) if(set.contains(original)) original *= 2; else break; return original; } }
class Solution { public: int findFinalValue(vector<int>& nums, int original) { int n = 1; for(int i = 0; i<n;++i) { if(find(nums.begin(),nums.end(),original) != nums.end()) //find func detailled explanation above { original *= 2; n += 1; //n is incremented by one beacuse questions want us to perform the operation again if element is found again after its double. } } return original; } };
var findFinalValue = function(nums, original) { while (nums.includes(original)) { original = original * 2 } return original };
Keep Multiplying Found Values by Two
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory. &nbsp; Example 1: Input: nums = [1,2,3] Output: [1,3,2] Example 2: Input: nums = [3,2,1] Output: [1,2,3] Example 3: Input: nums = [1,1,5] Output: [1,5,1] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 0 &lt;= nums[i] &lt;= 100
class Solution: def nextPermutation(self, nums) -> None: firstDecreasingElement = -1 toSwapWith = -1 lastIndex = len(nums) - 1 # Looking for an element that is less than its follower for i in range(lastIndex, 0, -1): if nums[i] > nums[i - 1]: firstDecreasingElement = i - 1 break # If there is not any then reverse the array to make initial permutation if firstDecreasingElement == -1: for i in range(0, lastIndex // 2 + 1): nums[i], nums[lastIndex - i] = nums[lastIndex - i], nums[i] return # Looking for an element to swap it with firstDecreasingElement for i in range(lastIndex, 0, -1): if nums[i] > nums[firstDecreasingElement]: toSwapWith = i break # Swap found elements nums[firstDecreasingElement], nums[toSwapWith] = nums[toSwapWith], nums[firstDecreasingElement] # Reverse elements from firstDecreasingElement to the end of the array left = firstDecreasingElement + 1 right = lastIndex while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1
class Solution { public void nextPermutation(int[] nums) { // FIND peek+1 int nextOfPeak = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { nextOfPeak = i - 1; break; } } // Return reverse Array if (nextOfPeak == -1) { int start = 0; int end = nums.length - 1; while (start <= end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } return; } // Find element greater than peek int reversalPoint = nums.length - 1; for (int i = nums.length - 1; i > nextOfPeak; i--) { if (nums[i] > nums[nextOfPeak]) { reversalPoint = i; break; } } // swap nextOfPeak && reversalPoint int temp = nums[nextOfPeak]; nums[nextOfPeak] = nums[reversalPoint]; nums[reversalPoint] = temp; // Reverse array from nextOfPeak+1 int start = nextOfPeak + 1; int end = nums.length - 1; while (start <= end) { int temp1 = nums[start]; nums[start] = nums[end]; nums[end] = temp1; start++; end--; } } }
class Solution { public: void nextPermutation(vector<int>& nums) { if(nums.size()==1) return; int i=nums.size()-2; while(i>=0 && nums[i]>=nums[i+1]) i--; if(i>=0){ int j=nums.size()-1; while(nums[i] >= nums[j]) j--; swap(nums[j], nums[i]); } sort(nums.begin()+i+1, nums.end()); } };
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var nextPermutation = function(nums) { const dsc = nums.slice(); dsc.sort((a, b) => b - a); if (dsc.every((n, i) => n === nums[i])) { nums.sort((a, b) => a - b); } else { const len = nums.length; let lo = len - 1, hi; while (nums[lo] === dsc[dsc.length - 1]) { lo--; dsc.pop(); } while (lo >= 0) { // console.log(lo, nums[lo], nums.slice(lo + 1)) hi = nums.slice(lo + 1).reverse().findIndex((n) => n > nums[lo]); if (hi !== -1) { hi = len - 1 - hi; break; } lo--; } const lval = nums[lo]; // console.log(lo, lval, hi, nums[hi]); nums[lo] = nums[hi]; nums[hi] = lval; const sorted = nums.slice(lo + 1); // console.log(nums, sorted) sorted.sort((a, b) => a - b); for (let i = 0; i < sorted.length; i++) nums[lo + 1 + i] = sorted[i]; } };
Next Permutation
There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 Output: 6 Example 2: Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 Output: 12 &nbsp; Constraints: 1 &lt;= m, n &lt;= 50 0 &lt;= maxMove &lt;= 50 0 &lt;= startRow &lt; m 0 &lt;= startColumn &lt; n
class Solution: def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int: if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n: return 1 if dp[maxMove][startRow][startColumn]!=-1: return dp[maxMove][startRow][startColumn] if mat[startRow][startColumn]==1: return 0 if maxMove <= 0: return 0 # mat[startRow][startColumn] = 1 a = self.helper(m, n, maxMove-1, startRow+1, startColumn,mat,dp) b = self.helper(m, n, maxMove-1, startRow-1, startColumn,mat,dp) c = self.helper(m, n, maxMove-1, startRow, startColumn+1,mat,dp) d = self.helper(m, n, maxMove-1, startRow, startColumn-1,mat,dp) dp[maxMove][startRow][startColumn] = a+b+c+d return dp[maxMove][startRow][startColumn] def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: mat = [[0 for i in range(n)] for j in range(m)] dp = [[[-1 for i in range(n+1)] for j in range(m+1)] for k in range(maxMove+1)] return self.helper(m, n, maxMove, startRow, startColumn, mat,dp)%(10**9 + 7)
class Solution { int[][][] dp; int mod = 1000000007; public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { dp = new int[m][n][maxMove + 1]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) for (int k = 0; k <= maxMove; k++) dp[i][j][k] = -1; return count(m, n, maxMove, startRow, startColumn) % mod; } public int count(int m, int n, int move, int r, int c) { if (r < 0 || c < 0 || r >= m || c >= n) return 1; if (move <= 0) return 0; if (dp[r][c][move] != -1) return dp[r][c][move] % mod; dp[r][c][move] = ((count(m, n, move - 1, r + 1, c) % mod + count (m, n, move - 1, r - 1, c) % mod) % mod + (count (m, n, move - 1, r, c + 1) % mod + count(m, n, move - 1, r, c - 1) % mod) % mod ) % mod; return dp[r][c][move] % mod; } }
vector<vector<vector<int>>> dp; int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; int mod = 1e9+7; int fun(int i,int j,int n,int m,int k){ if(i < 0 || j < 0 || i == n || j == m)return 1; else if(k == 0)return 0; if(dp[i][j][k] != -1)return dp[i][j][k]; int ans = 0; for(int c = 0; c < 4; c++){ int ni = i+dx[c] , nj = j+dy[c]; ans = (ans + fun(ni,nj,n,m,k-1)) % mod; } return dp[i][j][k] = ans; } int findPaths(int m, int n, int maxMove, int startRow, int startCol) { dp = vector<vector<vector<int>>>(m, vector<vector<int>>(n, vector<int>(maxMove+1, -1))); return fun(startRow, startCol,m,n,maxMove); }
vector<vector<vector<int>>> dp; int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; int mod = 1e9+7; int fun(int i,int j,int n,int m,int k){ if(i < 0 || j < 0 || i == n || j == m)return 1; else if(k == 0)return 0; if(dp[i][j][k] != -1)return dp[i][j][k]; int ans = 0; for(int c = 0; c < 4; c++){ int ni = i+dx[c] , nj = j+dy[c]; ans = (ans + fun(ni,nj,n,m,k-1)) % mod; } return dp[i][j][k] = ans; } int findPaths(int m, int n, int maxMove, int startRow, int startCol) { dp = vector<vector<vector<int>>>(m, vector<vector<int>>(n, vector<int>(maxMove+1, -1))); return fun(startRow, startCol,m,n,maxMove); }
Out of Boundary Paths
Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i &lt;= j. &nbsp; Example 1: Input: nums = [-2,5,-1], lower = -2, upper = 2 Output: 3 Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. Example 2: Input: nums = [0], lower = 0, upper = 0 Output: 1 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -231 &lt;= nums[i] &lt;= 231 - 1 -105 &lt;= lower &lt;= upper &lt;= 105 The answer is guaranteed to fit in a 32-bit integer.
class Solution: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: acc = list(accumulate(nums)) ans = a = 0 for n in nums: a += n ans += sum(1 for x in acc if lower <= x <= upper) acc.pop(0) lower += n upper += n return ans
class Solution { public int countRangeSum(int[] nums, int lower, int upper) { int n = nums.length, ans = 0; long[] pre = new long[n+1]; for (int i = 0; i < n; i++){ pre[i+1] = nums[i] + pre[i]; } Arrays.sort(pre); int[] bit = new int[pre.length+2]; long sum = 0; for (int i = 0; i < n; i++){ update(bit, bs(sum, pre), 1); sum += nums[i]; ans += sum(bit, bs(sum-lower, pre)) - sum(bit, bs(sum-upper-1, pre)); } return ans; } private int bs(long sum, long[] pre){ // return the index of first number bigger than sum int lo = 0, hi = pre.length; while(lo < hi){ int mid = (lo+hi) >> 1; if (pre[mid]>sum){ hi=mid; }else{ lo=mid+1; } } return lo; } private void update(int[] bit, int idx, int inc){ for (++idx; idx < bit.length; idx += idx & -idx){ bit[idx] += inc; } } private int sum(int[] bit, int idx){ int ans = 0; for (++idx; idx > 0; idx -= idx & -idx){ ans += bit[idx]; } return ans; } }
class Solution { public: using ll = long long; int countRangeSum(vector<int>& nums, int lower, int upper) { // Build prefix sums vector<ll> prefixSums(nums.size() + 1, 0); for (int i = 0; i < nums.size(); i++) { prefixSums[i + 1] = prefixSums[i] + nums[i]; } // Run merge sort and count range sum along the way tempNums.assign(prefixSums.size(), 0); splitAndMerge(prefixSums, 0, prefixSums.size(), lower, upper); return count; } void splitAndMerge(vector<ll> &nums, const int left, const int right, const int lower, const int upper) { if (right - left <= 1) return; const int mid = left + (right - left) / 2; splitAndMerge(nums, left, mid, lower, upper); splitAndMerge(nums, mid, right, lower, upper); countRangeSums(nums, left, mid, right, lower, upper); merge(nums, left, mid, right); } void countRangeSums(const vector<ll> &prefixSums, const int left, const int mid, const int right, const int lower, const int upper) { // S(i,j) == prefixSums[j+1] - prefixSums[i] (i <= j) // S(i,j) == prefixSums[k] - prefixSums[i] (let k=j+1, i < k) // // lower <= S(i,j) <= upper // => lower <= prefixSums[k] - prefixSums[i] <= upper // => lower + prefixSums[i] <= prefixSums[k] <= upper + prefixSums[i] for (int i = left; i < mid; i++) { const ll newLower = lower + prefixSums[i]; const ll newUpper = upper + prefixSums[i]; const auto findStart = prefixSums.begin() + mid; const auto findEnd = prefixSums.begin() + right; const auto itFoundLower = std::lower_bound(findStart, findEnd, newLower); const auto itFoundUpper = std::upper_bound(findStart, findEnd, newUpper); count += (itFoundUpper - itFoundLower); } } void merge(vector<ll> &nums, const int left, const int mid, const int right) { std::copy(nums.begin() + left, nums.begin() + right, tempNums.begin() + left); int i = left, j = mid; for (int k = left; k < right; k++) { if (i < mid && j < right) { if (tempNums[i] < tempNums[j]) { nums[k] = tempNums[i++]; } else { nums[k] = tempNums[j++]; } } else if (i >= mid) { nums[k] = tempNums[j++]; } else { // j >= right nums[k] = tempNums[i++]; } } } vector<ll> tempNums; int count = 0; };
var countRangeSum = function(nums, lower, upper) { let preSum = Array(nums.length + 1).fill(0); let count = 0; // create preSum array, use preSum to check the sum range for (let i = 0; i < nums.length; i++) { preSum[i + 1] = preSum[i] + nums[i]; } const sort = function(preSum) { if (preSum.length === 1) return preSum; let mid = Math.floor(preSum.length / 2); let left = sort(preSum.slice(0, mid)); let right = sort(preSum.slice(mid)) return merge(left, right); } const merge = function(left, right) { let start = 0; let end = 0; for (let i = 0; i < left.length; i++) { // all elements before start index, after subtracting left[i] are less than lower, which means all elements after start index are bigger or equal than lower while (start < right.length && right[start] - left[i] < lower) { start++; } // similarly, all elements before end index are less or euqal then upper while (end < right.length && right[end] - left[i] <= upper) { end++; } // since the initial values of start and end are the same, and upper >= lower, so end will >= start too, which means the rest of the end minus start element difference will fall between [lower, upper]. count += end - start; } let sort = []; while (left.length && right.length) { if (left[0] <= right[0]) { sort.push(left.shift()); } else { sort.push(right.shift()); } } return [...sort, ...left, ...right]; } sort(preSum); return count; };
Count of Range Sum
Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree. &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. Example 2: Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. Example 3: Input: root = [1,2,3,4,6,5,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 &lt;= Node.val &lt;= 1000
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ q = [(0, 0, root)] l = [] while q: col, row, node = q.pop() l.append((col, row, node.val)) if node.left: q.append((col-1, row+1, node.left)) if node.right: q.append((col+1, row+1, node.right)) l.sort() print(l) ans = [] ans.append([l[0][-1]]) for i in range(1, len(l)): if l[i][0] > l[i-1][0]: ans.append([l[i][-1]]) else: ans[-1].append(l[i][-1]) return ans
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private static class MNode { TreeNode Node; int hDist; int level; MNode(TreeNode node, int hd, int l) { Node = node; hDist = hd; level = l; } } public List<List<Integer>> verticalTraversal(TreeNode root) { Map<Integer, PriorityQueue<MNode>> map = new TreeMap<>(); Queue<MNode> q = new LinkedList<>(); q.add(new MNode(root, 0, 0)); while(!q.isEmpty()) { MNode curr = q.poll(); if(map.containsKey(curr.hDist)) map.get(curr.hDist).add(curr); else { PriorityQueue<MNode> pq = new PriorityQueue<> ((a,b) -> (a.level == b.level)? a.Node.val - b.Node.val: a.level - b.level); pq.add(curr); map.put(curr.hDist, pq); } if(curr.Node.left != null) q.add(new MNode(curr.Node.left, curr.hDist -1, curr.level + 1)); if(curr.Node.right != null) q.add(new MNode(curr.Node.right, curr.hDist +1, curr.level + 1)); } List<List<Integer>> ans = new ArrayList<>(); for(Integer key: map.keySet()) { List<Integer> temp = new ArrayList<>(); while(!map.get(key).isEmpty()) { temp.add(map.get(key).poll().Node.val); } ans.add(new ArrayList<>(temp)); } return ans; } }
/** * 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: // hd - horizontal distance // vertical order traversal starts from least hd to highest hd // on moving left hd decreases by 1, on moving right it increases by 1 // should do level order traversal to get the nodes with same hd in correct order vector<vector<int>> verticalTraversal(TreeNode* root) { map<int,vector<int>> mp; queue<pair<TreeNode*,int>> q; q.push({root,0}); while(!q.empty()){ int sz = q.size(); map<int,multiset<int>> temp; for(int i=0;i<sz;i++){ auto pr = q.front(); q.pop(); temp[pr.second].insert(pr.first->val); if(pr.first->left != NULL){ q.push({pr.first->left,pr.second-1}); } if(pr.first->right != NULL){ q.push({pr.first->right,pr.second+1}); } } for(auto pr:temp){ for(auto val:pr.second){ mp[pr.first].push_back(val); } } } vector<vector<int>> ans; for(auto pr:mp){ vector<int> temp; for(auto val:pr.second){ temp.push_back(val); } ans.push_back(temp); } return ans; } };
/** * 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 {number[][]} */ var verticalTraversal = function(root) { let ans = []; let l = 0, ri = 0, mi = 0; const preOrder = (r = root, mid = 0, d = 0) => { if(!r) return ; if(mid == 0) { if(ans.length < mi + 1) ans.push([]); ans[mi].push({v: r.val, d}); } else if(mid < 0) { if(mid < l) { l = mid; mi++; ans.unshift([{v: r.val, d}]); } else { let idx = mi + mid; ans[idx].push({v: r.val, d}); } } else { if(mid > ri) { ri = mid; ans.push([{v: r.val, d}]); } else { let idx = mi + mid; ans[idx].push({v: r.val, d}); } } preOrder(r.left, mid - 1, d + 1); preOrder(r.right, mid + 1, d + 1); } preOrder(); const sortByDepthOrVal = (a, b) => { if(a.d == b.d) return a.v - b.v; return a.d - b.d; } ans = ans.map(col => col.sort(sortByDepthOrVal).map(a => a.v)); return ans; };
Vertical Order Traversal of a Binary Tree
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti]. For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ). Return an array answer where answer[i] is the answer to the ith query. &nbsp; Example 1: Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] Output: [2,7,14,8] Explanation: The binary representation of the elements in the array are: 1 = 0001 3 = 0011 4 = 0100 8 = 1000 The XOR values for queries are: [0,1] = 1 xor 3 = 2 [1,2] = 3 xor 4 = 7 [0,3] = 1 xor 3 xor 4 xor 8 = 14 [3,3] = 8 Example 2: Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] Output: [8,0,4,4] &nbsp; Constraints: 1 &lt;= arr.length, queries.length &lt;= 3 * 104 1 &lt;= arr[i] &lt;= 109 queries[i].length == 2 0 &lt;= lefti &lt;= righti &lt; arr.length
class Solution: def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: """ arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] find pref xor of arr pref = [x,x,x,x] for each query find the left and right indices the xor for range (l, r) would be pref[r] xor pref[l-1] """ n, m = len(queries), len(arr) answer = [1]*n pref = [1]*m pref[0] = arr[0] if m > 1: for i in range(1,m): pref[i] = pref[i-1] ^ arr[i] for (i, (l,r)) in enumerate(queries): if l == 0: answer[i] = pref[r] else: answer[i] = pref[r] ^ pref[l-1] return answer
class Solution { public int[] xorQueries(int[] arr, int[][] queries) { int[] ans = new int[queries.length]; int[] xor = new int[arr.length]; xor[0] = arr[0]; // computing prefix XOR of arr for(int i = 1; i < arr.length; i++) { xor[i] = arr[i] ^ xor[i-1]; } for(int i = 0; i < queries.length; i++) { // if query starts from something other than 0 (say i), then we XOR all values from arr[0] to arr[i-1] if(queries[i][0] != 0) { ans[i] = xor[queries[i][1]]; for(int j = 0; j < queries[i][0]; j++) { ans[i] = arr[j] ^ ans[i]; } } // if start of query is 0, then we striaght up use the prefix XOR till ith element else ans[i] = xor[queries[i][1]]; } return ans; } }
class Solution { public: // we know that (x ^ x) = 0, // arr = [1,4,8,3,7,8], let we have to calculate xor of subarray[2,4] // (1 ^ 4 ^ 8 ^ 3 ^ 7) ^ (1 ^ 4) = (8 ^ 3 ^ 7), this is nothing but prefix[right] ^ prefix[left - 1] // (1 ^ 1 = 0) and (4 ^ 4) = 0 vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) { int n = queries.size(); // find the prefix xor of arr for(int i = 1; i < arr.size(); i++) { arr[i] = (arr[i - 1] ^ arr[i]); } // calculate each query vector<int> res(n); for(int i = 0; i < n; i++) { int left = queries[i][0]; int right = queries[i][1]; // find the xorr of the subarray int xorr = arr[right]; if(left > 0) { xorr ^= arr[left - 1]; } res[i] = xorr; } return res; } };
var xorQueries = function(arr, queries) { let n = arr.length; while ((n & (n - 1)) != 0) { n++; } const len = n; const tree = new Array(len * 2).fill(0); build(tree, 1, 0, len - 1); const res = []; for (let i = 0; i < queries.length; i++) { const [start, end] = queries[i]; const xor = query(tree, 1, 0, len - 1, start, end); res.push(xor); } return res; function build(tree, segmentIdx, segmentStart, segmentEnd) { if (segmentStart === segmentEnd) { tree[segmentIdx] = arr[segmentStart]; return; } const mid = (segmentStart + segmentEnd) >> 1; build(tree, segmentIdx * 2, segmentStart, mid); build(tree, segmentIdx * 2 + 1, mid + 1, segmentEnd); tree[segmentIdx] = tree[segmentIdx * 2] ^ tree[segmentIdx * 2 + 1]; return; } function query(tree, node, nodeStart, nodeEnd, queryStart, queryEnd) { if (queryStart <= nodeStart && nodeEnd <= queryEnd) { return tree[node]; } if (nodeEnd < queryStart || queryEnd < nodeStart) { return 0; } const mid = (nodeStart + nodeEnd) >> 1; const leftXor = query(tree, node * 2, nodeStart, mid, queryStart, queryEnd); const rightXor = query(tree, node * 2 + 1, mid + 1, nodeEnd, queryStart, queryEnd); return leftXor ^ rightXor; } }; ``
XOR Queries of a Subarray
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded. &nbsp; Example 1: Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]] Output: 7 Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram. There are a total of 7 unguarded cells, so we return 7. Example 2: Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]] Output: 4 Explanation: The unguarded cells are shown in green in the above diagram. There are a total of 4 unguarded cells, so we return 4. &nbsp; Constraints: 1 &lt;= m, n &lt;= 105 2 &lt;= m * n &lt;= 105 1 &lt;= guards.length, walls.length &lt;= 5 * 104 2 &lt;= guards.length + walls.length &lt;= m * n guards[i].length == walls[j].length == 2 0 &lt;= rowi, rowj &lt; m 0 &lt;= coli, colj &lt; n All the positions in guards and walls are unique.
class Solution: def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: dp = [[0] * n for _ in range(m)] for x, y in guards+walls: dp[x][y] = 1 directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] for x, y in guards: for dx, dy in directions: curr_x = x curr_y = y while 0 <= curr_x+dx < m and 0 <= curr_y+dy < n and dp[curr_x+dx][curr_y+dy] != 1: curr_x += dx curr_y += dy dp[curr_x][curr_y] = 2 return sum(1 for i in range(m) for j in range(n) if dp[i][j] == 0)
class Solution { public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}}; char[][] grid= new char[m][n]; int count = m*n - guards.length - walls.length; for(int[] wall : walls) { int x = wall[0], y = wall[1]; grid[x][y] = 'W'; } for(int[] guard : guards) { int x = guard[0], y = guard[1]; grid[x][y] = 'G'; } for(int[] point : guards) { for(int dir[] : dirs) { int x = point[0] + dir[0]; int y = point[1] + dir[1]; while(!(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 'G' || grid[x][y] == 'W')) { if(grid[x][y] != 'P') count--; grid[x][y] = 'P'; x += dir[0]; y += dir[1]; } } } return count; } }
class Solution { public: void dfs( vector<vector<int>> &grid,int x,int y,int m,int n,int dir){ if(x<0 || y<0 || x>=m || y>=n) return; if(grid[x][y]==2 || grid[x][y]==1) return; grid[x][y]=3; if(dir==1){ dfs(grid,x+1,y,m,n,dir); } else if(dir==2){ dfs(grid,x,y+1,m,n,dir); } else if(dir==3){ dfs(grid,x-1,y,m,n,dir); } else{ dfs(grid,x,y-1,m,n,dir); } } int countUnguarded(int m, int n, vector<vector<int>>& guards, vector<vector<int>>& walls) { vector<vector<int>> grid(m,vector<int>(n,0)); //marking guards for(int i=0;i<guards.size();i++){ int x=guards[i][0]; int y=guards[i][1]; grid[x][y]=1; } // marking walls for(int i=0;i<walls.size();i++){ int x=walls[i][0]; int y=walls[i][1]; grid[x][y]=2; } // dfs in each of 4 directions for(int i=0;i<guards.size();i++){ int x=guards[i][0]; int y=guards[i][1]; dfs(grid,x+1,y,m,n,1); dfs(grid,x,y+1,m,n,2); dfs(grid,x-1,y,m,n,3); dfs(grid,x,y-1,m,n,4); } long long int cnt=0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]==0) cnt++; } } return cnt; } };
var countUnguarded = function(m, n, guards, walls) { let board = new Array(m).fill(0).map(_=>new Array(n).fill(0)) // 0 - Empty // 1 - Guard // 2 - Wall // 3 - Guard view const DIRECTIONS = [ [-1, 0], [0, 1], [1, 0], [0, -1] ] for(let [guardRow, guardCol] of guards) board[guardRow][guardCol] = 1 for(let [wallRow, wallCol] of walls) board[wallRow][wallCol] = 2 for(let [guardRow, guardCol] of guards){ //Loop through row with the same col //Go down from current row let row = guardRow + 1 while(row < m){ //Stop if you encounter a wall or guard if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break board[row][guardCol] = 3 row++ } //Go up from current row row = guardRow - 1 while(row >= 0){ if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break board[row][guardCol] = 3 row-- } //Loop through col with the same row //Go right from current col let col = guardCol + 1 while(col < n){ if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break board[guardRow][col] = 3 col++ } //Go left from current col col = guardCol - 1 while(col >= 0){ if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break board[guardRow][col] = 3 col-- } } //Count the free cells let freeCount = 0 for(let i = 0; i < m; i++){ for(let j = 0; j < n; j++){ if(board[i][j] == 0) freeCount++ } } return freeCount };
Count Unguarded Cells in the Grid
You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. The student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Return true if the student is eligible for an attendance award, or false otherwise. &nbsp; Example 1: Input: s = "PPALLP" Output: true Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days. Example 2: Input: s = "PPALLL" Output: false Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s[i] is either 'A', 'L', or 'P'.
class Solution: def checkRecord(self, s: str) -> bool: eligible = True for i in range(0, len(s)-2): if s[i:i+3] == "LLL": eligible = False absent = 0 for i in range(len(s)): if s[i] == "A": absent +=1 if absent>=2: eligible = False return(eligible)
class Solution { public boolean checkRecord(String s) { int size=s.length(); if(s.replace("A","").length()<=size-2||s.indexOf("LLL")!=-1)return false; return true; } }
class Solution { public: bool checkRecord(string s); }; /*********************************************************/ bool Solution::checkRecord(string s) { int i, size = s.size(), maxL=0, countA=0, countL=0; for (i = 0; i < size; ++i) { if (s[i] == 'L') { ++countL; } else { countL = 0; } if (s[i] == 'A') { ++countA; } if (maxL < countL) { maxL = countL; } if( countA >= 2 || maxL >= 3) { return false; } } return true; } /*********************************************************/
var checkRecord = function(s) { let absent = 0; let lates = 0; for (let i = 0; i < s.length; i++) { if(s[i] === 'L') { lates++; if(lates > 2) return false; } else { lates = 0; if(s[i] === 'A') { absent++; if(absent > 1) return false; } } } return true; };
Student Attendance Record I
You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0. &nbsp; Example 1: Input: s = "abcd", t = "bcdf", maxCost = 3 Output: 3 Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3. Example 2: Input: s = "abcd", t = "cdef", maxCost = 3 Output: 1 Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1. Example 3: Input: s = "abcd", t = "acde", maxCost = 0 Output: 1 Explanation: You cannot make any change, so the maximum length is 1. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 t.length == s.length 0 &lt;= maxCost &lt;= 106 s and t consist of only lowercase English letters.
class Solution(object): def equalSubstring(self, s, t, maxCost): """ :type s: str :type t: str :type maxCost: int :rtype: int """ best = 0 windowCost = 0 l = 0 for r in range(len(s)): windowCost += abs(ord(s[r]) - ord(t[r])) while windowCost > maxCost: windowCost -= abs(ord(s[l]) - ord(t[l])) l+=1 best = max(best,r-l+1) return best
class Solution { public int equalSubstring(String s, String t, int maxCost) { int ans =0; int tempcost =0; int l =0 ; int r= 0 ; for(;r!=s.length();r++){ tempcost += Math.abs(s.charAt(r)-t.charAt(r)); while(tempcost>maxCost){ tempcost -= Math.abs(s.charAt(l)-t.charAt(l)); l++; } ans =Math.max(ans,r+1-l); } return ans; } }
class Solution { public: int equalSubstring(string s, string t, int maxCost) { int l = 0, r = 0, currCost = 0, n = s.length(), maxLen = 0; while(r < n) { currCost += abs(s[r] - t[r]); r++; while(currCost > maxCost) { currCost -= abs(s[l] - t[l]); l++; } maxLen = max(r - l, maxLen); } return maxLen; } };
var equalSubstring = function(s, t, maxCost) { let dp = [], ans = 0; for (let i = 0, j = 0, k = 0; i < s.length; i++) { // overlay k += dp[i] = abs(s[i], t[i]); // non first if (k > maxCost) { k -= dp[j], j++; continue; } // eligible ans++; } return ans; // get abs value function abs(a, b) { return Math.abs(a.charCodeAt(0) - b.charCodeAt(0)); } };
Get Equal Substrings Within Budget
For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. &nbsp; Example 1: Input: sequence = "ababc", word = "ab" Output: 2 Explanation: "abab" is a substring in "ababc". Example 2: Input: sequence = "ababc", word = "ba" Output: 1 Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc". Example 3: Input: sequence = "ababc", word = "ac" Output: 0 Explanation: "ac" is not a substring in "ababc". &nbsp; Constraints: 1 &lt;= sequence.length &lt;= 100 1 &lt;= word.length &lt;= 100 sequence and word&nbsp;contains only lowercase English letters.
class Solution: def maxRepeating(self, sequence: str, word: str) -> int: if word not in sequence: return 0 left = 1 right = len(sequence) // len(word) while left <= right: mid = (left + right) // 2 if word * mid in sequence: left = mid + 1 else: right = mid - 1 return left - 1
class Solution { public int maxRepeating(String s, String w) { if(w.length()>s.length()) return 0; int ans=0; StringBuilder sb=new StringBuilder(""); while(sb.length()<=s.length()){ sb.append(w); if(s.contains(sb)) ans++; else break; } return ans; } }
class Solution { public: int maxRepeating(string sequence, string word) { int k = 0; string temp = word; while(sequence.find(temp) != string::npos){ temp += word; k++; } return k; } };
var maxRepeating = function(sequence, word) { let result = 0; while (sequence.includes(word.repeat(result + 1))) { result += 1; }; return result; };
Maximum Repeating Substring
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 &lt;= a, b, c &lt;= n. &nbsp; Example 1: Input: n = 5 Output: 2 Explanation: The square triples are (3,4,5) and (4,3,5). Example 2: Input: n = 10 Output: 4 Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10). &nbsp; Constraints: 1 &lt;= n &lt;= 250
class Solution: def countTriples(self, n: int) -> int: c = 0 for i in range(1, n+1): for j in range(i+1, n+1): sq = i*i + j*j r = int(sq ** 0.5) if ( r*r == sq and r <= n ): c +=2 return c
class Solution { public int countTriples(int n) { int c = 0; for(int i=1 ; i<=n ; i++){ for(int j=i+1 ; j<=n ; j++){ int sq = ( i * i) + ( j * j); int r = (int) Math.sqrt(sq); if( r*r == sq && r <= n ) c += 2; } } return c; } }
class Solution { public: int countTriples(int n) { int res = 0; for (int a = 3, sqa; a < n; a++) { sqa = a * a; for (int b = 3, sqc, c; b < n; b++) { sqc = sqa + b * b; c = sqrt(sqc); if (c > n) break; res += c * c == sqc; } } return res; } };
var countTriples = function(n) { let count = 0; for (let i=1; i < n; i++) { for (let j=1; j < n; j++) { let root = Math.sqrt(j*j + i*i) if (Number.isInteger(root) && root <= n) { count++ } } } return count };
Count Square Sum Triples
You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7. &nbsp; Example 1: Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] Output: 4 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. Example 2: Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] Output: 6 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. Example 3: Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] Output: 9 &nbsp; Constraints: 2 &lt;= h, w &lt;= 109 1 &lt;= horizontalCuts.length &lt;= min(h - 1, 105) 1 &lt;= verticalCuts.length &lt;= min(w - 1, 105) 1 &lt;= horizontalCuts[i] &lt; h 1 &lt;= verticalCuts[i] &lt; w All the elements in horizontalCuts are distinct. All the elements in verticalCuts are distinct.
class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() mxHr = 0 prev = 0 for i in horizontalCuts: mxHr = max(mxHr, i-prev) prev = i mxHr = max(mxHr, h-horizontalCuts[-1]) mxVr = 0 prev = 0 for i in verticalCuts: mxVr = max(mxVr, i-prev) prev = i mxVr = max(mxVr, w-verticalCuts[-1]) return (mxHr * mxVr) % ((10 ** 9) + 7)
import java.math.BigInteger; class Solution { public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { Arrays.sort(horizontalCuts); Arrays.sort(verticalCuts); int i; int hMax=horizontalCuts[0]; for(i=1;i<horizontalCuts.length;i++) // if(hMax < horizontalCuts[i]-horizontalCuts[i-1]) hMax=Math.max(hMax,horizontalCuts[i]-horizontalCuts[i-1]); if(h-horizontalCuts[horizontalCuts.length-1] > hMax) hMax= h-horizontalCuts[horizontalCuts.length-1]; int vMax=verticalCuts[0]; for(i=1;i<verticalCuts.length;i++) // if(vMax < verticalCuts[i]-verticalCuts[i-1]) vMax=Math.max(vMax,verticalCuts[i]-verticalCuts[i-1]); if(w-verticalCuts[verticalCuts.length-1] > vMax) vMax= w-verticalCuts[verticalCuts.length-1]; return (int)((long)hMax*vMax%1000000007); } }
class Solution { public: int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) { int mod = 1e9 + 7; sort(horizontalCuts.begin(), horizontalCuts.end()); sort(verticalCuts.begin(), verticalCuts.end()); // cout << 1; horizontalCuts.push_back(h); verticalCuts.push_back(w); // cout << 1; int prev = 0; int vert = INT_MIN, hori = INT_MIN; for(int i = 0; i < verticalCuts.size(); i++) { if(vert < verticalCuts[i]-prev) vert = verticalCuts[i]-prev; prev = verticalCuts[i]; } //cout << 1; prev = 0; for(int i = 0; i < horizontalCuts.size(); i++) { if(hori < horizontalCuts[i]-prev) hori = horizontalCuts[i]-prev; prev = horizontalCuts[i]; } return ((long long)vert*hori) % mod; } };
var maxArea = function(h, w, horizontalCuts, verticalCuts) { horizontalCuts.sort((a,b) => a-b) verticalCuts.sort((a,b) => a-b) let max_hor_dis = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length-1]) let max_ver_dis = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length-1]) for(let i=1; i<horizontalCuts.length; i++){ max_hor_dis = Math.max(max_hor_dis, horizontalCuts[i] - horizontalCuts[i-1]) } for(let i=1; i<verticalCuts.length; i++){ max_ver_dis = Math.max(max_ver_dis, verticalCuts[i] - verticalCuts[i-1]) } return BigInt(max_hor_dis) * BigInt(max_ver_dis) % BigInt(1e9+7) };
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
Sometimes people repeat letters to represent extra feeling. For example: "hello" -&gt; "heeellooo" "hi" -&gt; "hiiii" In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo". You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more. For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -&gt; "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -&gt; "hellooo" -&gt; "helllllooo" = s. Return the number of query strings that are stretchy. &nbsp; Example 1: Input: s = "heeellooo", words = ["hello", "hi", "helo"] Output: 1 Explanation: We can extend "e" and "o" in the word "hello" to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more. Example 2: Input: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"] Output: 3 &nbsp; Constraints: 1 &lt;= s.length, words.length &lt;= 100 1 &lt;= words[i].length &lt;= 100 s and words[i] consist of lowercase letters.
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: # edge cases if len(s) == 0 and len(words) != 0: return False if len(words) == 0 and len(s) != 0: return False if len(s) == 0 and len(words) == 0: return True # helper function, compressing string and extract counts def compressor(s_word): init_string =[s_word[0]] array = [] start = 0 for i,c in enumerate(s_word): if c == init_string[-1]: continue array.append(i-start) start = i init_string += c array.append(i-start+1) return init_string,array res = len(words) s_split, s_array = compressor(s) for word in words: word_split = [''] word_array = [] word_split,word_array = compressor(word) if s_split == word_split: for num_s,num_word in zip(s_array,word_array): if num_s != num_word and num_s < 3 or num_word > num_s: res -= 1 break else: res -= 1 return res
class Solution { private String getFreqString(String s) { int len = s.length(); StringBuilder freqString = new StringBuilder(); int currFreq = 1; char prevChar = s.charAt(0); freqString.append(s.charAt(0)); for(int i = 1; i<len; i++) { if(s.charAt(i) == prevChar) { currFreq++; } else { freqString.append(currFreq); freqString.append(s.charAt(i)); currFreq = 1; } prevChar = s.charAt(i); } if(currFreq>0) { freqString.append(currFreq); } return freqString.toString(); } private boolean isGreaterButLessThanThree(char sChar, char wChar) { return sChar > wChar && sChar < '3'; } private boolean isStretchy(String s, String word) { int sLen = s.length(); int wordLen = word.length(); if(sLen != wordLen) { return false; } for(int i = 0; i<sLen; i++) { char sChar = s.charAt(i); char wChar = word.charAt(i); if(i%2 != 0) { if(sChar < wChar) { return false; } if(isGreaterButLessThanThree(sChar, wChar)) { return false; } } else if(sChar != wChar){ return false; } } return true; } public int expressiveWords(String s, String[] words) { int wordLen = words.length; if(wordLen < 1 || s.length() < 1) { return 0; } int stretchyWords = 0; String freqStringS = getFreqString(s); for(String word: words) { String freqStringWord = getFreqString(word); if(isStretchy(freqStringS, freqStringWord)) { stretchyWords++; } } return stretchyWords; } }
class Solution { public: // Basically get the length of a repeated sequence starting at pointer p. int getRepeatedLen(string& s, int p) { int res = 0; char c = s[p]; while(p < s.size() && s[p] == c) { res++; p++; } return res; } // Check if a word t is stretchy. i.e. can we turn word t into word s? bool isStretchy(string& s, string& t, unordered_set<char>& sMap) { if(s == t) return true; if(s.size() < t.size()) return false; // If t is bigger than the original string, return false since we can't take away characters. int p1 = 0; // The first pointer will point to a char in our original string. int p2 = 0; // The second pointer will point to a char in the word we want to stretch. // Loop though the target string since we know it was to be either the same length or longer. i.e. "heeellooo" is longer than "hello". while(p1 < s.size()) { if(!sMap.count(t[p2])) return false; // If we find a char in the word we want to stretch that's not even in our original string, we return false since we cannot remove chars. int want = getRepeatedLen(s,p1); // For every new char we encounter we check how many are in the orignal string. int have = getRepeatedLen(t,p2); if( have > want) return false; // Remember can't delete chars. int needToAdd = want - have; if(want != have && needToAdd + have < 3) return false; // If we need to add some chars, we have to also check if the new group size that we create follows our rules of being greater or equal to 3. p1 += want; // We don't want to repeat a char again. p2 += have; // Same as above but for the other word. } return true; } int expressiveWords(string s, vector<string>& words) { int res = 0; unordered_set<char> sMap(s.begin(),s.end()); // Useful to know what characters exits in the first place. // Basically loop through every word in the vector and check if it is stretchy. for(string& w : words) { if(isStretchy(s,w,sMap)) res++; } return res; } };
/** * @param {string} s * @param {string[]} words * @return {number} */ var expressiveWords = function(s, words) { let arr = []; let curr = 0 while(curr < s.length){ let count = 1 while(s[curr] === s[curr+1]){ count++; curr++ } arr.push([s[curr] , count]); curr++ } let ans = 0 for(let charArr of words){ let idx = 0; let i = 0; let flag = true; if(charArr.length > s.length)continue while( i < charArr.length ){ let count = 1 while(charArr[i] === charArr[i+1]){ i++; count++ } if(arr[idx][0] !== charArr[i] || arr[idx][1] < count || (arr[idx][1] <3 && arr[idx][1] !== count) ){ flag = false; break } idx++; i++ } if(idx !== arr.length)flag = false if(flag)ans++ } return ans };
Expressive Words
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. &nbsp; Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nums = [1] Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Output: 23 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -104 &lt;= nums[i] &lt;= 104 &nbsp; Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution: def maxSubArray(self, nums: List[int]) -> int: def kadane(i): if F[i] != None: return F[i] F[i] = max(nums[i],kadane(i-1) + nums[i]) return F[i] n = len(nums) F = [None for _ in range(n)] F[0] = nums[0] kadane(n-1) return max(F)
class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int currmax = 0; int gmax = nums[0]; for(int i=0;i<n;i++) { currmax+=nums[i]; gmax=Math.max(gmax, currmax); currmax=Math.max(currmax, 0); } return gmax; } }
class Solution { public: int maxSubArray(vector<int>& nums) { int m = INT_MIN, sm = 0; for (int i = 0; i < nums.size(); ++i) { sm += nums[i]; m = max(sm, m); if (sm < 0) sm = 0; } return m; } };
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { let max = Number.MIN_SAFE_INTEGER; let curr = 0; for (let i = 0; i < nums.length; i++) { if (curr < 0 && nums[i] > curr) { curr = 0; } curr += nums[i]; max = Math.max(max, curr); } return max; };
Maximum Subarray
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path. &nbsp; Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --&gt; (0, 1) --&gt; (0, 2) --&gt; (0, 3) change the arrow to down with cost = 1 --&gt; (1, 3) --&gt; (1, 2) --&gt; (1, 1) --&gt; (1, 0) change the arrow to down with cost = 1 --&gt; (2, 0) --&gt; (2, 1) --&gt; (2, 2) --&gt; (2, 3) change the arrow to down with cost = 1 --&gt; (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1 &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 100 1 &lt;= grid[i][j] &lt;= 4
class Solution: def minCost(self, grid: List[List[int]]) -> int: changes = [[float("inf") for _ in range(len(grid[0]))] for _ in range(len(grid))] heap = [(0,0,0)] dirn = [(0,1),(0,-1),(1,0),(-1,0)] while heap: dist,r,c = heapq.heappop(heap) if r >= len(grid) or r < 0 or c >= len(grid[0]) or c < 0 or changes[r][c] <= dist: continue if r == len(grid) - 1 and c == len(grid[0]) - 1: return dist changes[r][c] = dist for i in range(1,5): if i == grid[r][c]: heapq.heappush(heap,(dist,r+dirn[i-1][0],c+dirn[i-1][1])) else: heapq.heappush(heap,(dist+1,r+dirn[i-1][0],c+dirn[i-1][1])) return dist
class Solution { int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}}; private boolean isValid(int i,int j,int n,int m) { return i<n && j<m && i>=0 && j>=0; } private boolean isValidDirection(int [][]grid,int []currEle,int nx,int ny) { int nextX=currEle[0],nextY = currEle[1]; int n =grid.length,m = grid[0].length; switch(grid[currEle[0]][currEle[1]]) { case 1: nextY++; break; case 2: nextY--; break; case 3: nextX++; break; case 4: nextX--; break; } return nextX==nx && nextY==ny; } public int minCost(int[][] grid) { int n = grid.length; int m = grid[0].length; int dist[][] = new int[n][m]; boolean vis[][] = new boolean[n][m]; LinkedList<int[]> queue = new LinkedList<>(); // for performing 01 BFS for(int i=0;i<n;i++) Arrays.fill(dist[i],Integer.MAX_VALUE); queue.add(new int[]{0,0}); dist[0][0]=0; while(!queue.isEmpty()) { int[] currEle = queue.remove(); vis[currEle[0]][currEle[1]] = true; for(int[] currDir:dirs) { int nx = currDir[0]+currEle[0]; int ny = currDir[1]+currEle[1]; if(isValid(nx,ny,n,m) && vis[nx][ny]==false) { if(isValidDirection(grid,currEle,nx,ny)) { dist[nx][ny] = Math.min(dist[nx][ny],dist[currEle[0]][currEle[1]]); queue.add(0,new int[]{nx,ny}); } else { dist[nx][ny] = Math.min(dist[nx][ny],1+dist[currEle[0]][currEle[1]]); queue.add(new int[]{nx,ny}); } } } } return dist[n-1][m-1]; } }
#define vv vector<int> class Solution { public: int dx[4]={0 , 0, 1 , -1}; int dy[4]={1 , -1 , 0 , 0}; int minCost(vector<vector<int>>& grid) { int m=grid.size(); int n=grid[0].size(); priority_queue< vv , vector<vv> , greater<vv>> pq; vector<vector<int>> dp(m+3 , vector<int>(n+3 , INT_MAX)); dp[0][0]=0; pq.push({0 , 0 , 0}); // there is no need of visited // distance or u can say cost relaxation while(!pq.empty()) { auto v=pq.top(); pq.pop(); int cost=v[0]; int i=v[1]; int j=v[2]; if(i==m-1 && j==n-1) { return cost; } for(int k=0;k<4;k++) { int newi=i+dx[k]; int newj=j+dy[k]; if(newi>=0 && newj>=0 && newi<m && newj<n) { if((k+1)==grid[i][j]) { if(dp[newi][newj]>cost) { dp[newi][newj]=cost; pq.push({cost , newi , newj}); } } else { if(dp[newi][newj]>cost+1) { dp[newi][newj]=cost+1; pq.push({cost+1 , newi , newj}); } } } } } if(dp[m-1][n-1]!=INT_MAX) { return dp[m-1][n-1]; } return -1; } };
const minCost = function (grid) { const m = grid.length, n = grid[0].length, checkPos = (i, j) => i > -1 && j > -1 && i < m && j < n && !visited[i + "," + j], dir = { 1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0] }, dfs = (i, j) => { if (!checkPos(i, j)) return false; if (i === m - 1 && j === n - 1) return true; visited[i + "," + j] = true; next.push([i, j]); return dfs(i + dir[grid[i][j]][0], j + dir[grid[i][j]][1]); }, visited = {}; let changes = 0, cur = [[0, 0]], next; while (cur.length) { next = []; for (const [i, j] of cur) if (dfs(i, j)) return changes; changes++; cur = []; next.forEach(pos => { for (let d = 1; d < 5; d++) { const x = pos[0] + dir[d][0], y = pos[1] + dir[d][1]; if (checkPos(x, y)) cur.push([x, y]); } }); } };
Minimum Cost to Make at Least One Valid Path in a Grid
Alice and Bob take turns playing a game, with Alice&nbsp;starting first. You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num: Choose an index i where num[i] == '?'. Replace num[i] with any digit between '0' and '9'. The game ends when there are no more '?' characters in num. For Bob&nbsp;to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice&nbsp;to win, the sums must not be equal. For example, if the game ended with num = "243801", then Bob&nbsp;wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice&nbsp;wins because 2+4+3 != 8+0+3. Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win. &nbsp; Example 1: Input: num = "5023" Output: false Explanation: There are no moves to be made. The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3. Example 2: Input: num = "25??" Output: true Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal. Example 3: Input: num = "?3295???" Output: false Explanation: It can be proven that Bob will always win. One possible outcome is: - Alice replaces the first '?' with '9'. num = "93295???". - Bob replaces one of the '?' in the right half with '9'. num = "932959??". - Alice replaces one of the '?' in the right half with '2'. num = "9329592?". - Bob replaces the last '?' in the right half with '7'. num = "93295927". Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7. &nbsp; Constraints: 2 &lt;= num.length &lt;= 105 num.length is even. num consists of only digits and '?'.
class Solution: def sumGame(self, num: str) -> bool: n = len(num) q_cnt_1 = s1 = 0 for i in range(n//2): # get digit sum and question mark count for the first half of `num` if num[i] == '?': q_cnt_1 += 1 else: s1 += int(num[i]) q_cnt_2 = s2 = 0 for i in range(n//2, n): # get digit sum and question mark count for the second half of `num` if num[i] == '?': q_cnt_2 += 1 else: s2 += int(num[i]) s_diff = s1 - s2 # calculate sum difference and question mark difference q_diff = q_cnt_2 - q_cnt_1 return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins
class Solution { public boolean sumGame(String num) { int q = 0, d = 0, n = num.length(); for (int i = 0; i < n; i++){ if (num.charAt(i) == '?'){ q += 2* i < n? 1 : -1; }else{ d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0'); } } return (q & 1) > 0 || q * 9 + 2 * d != 0; } }
class Solution { public: bool sumGame(string num) { const int N = num.length(); int lDigitSum = 0; int lQCount = 0; int rDigitSum = 0; int rQCount = 0; for(int i = 0; i < N; ++i){ if(isdigit(num[i])){ if(i < N / 2){ lDigitSum += (num[i] - '0'); }else{ rDigitSum += (num[i] - '0'); } }else{ if(i < N / 2){ ++lQCount; }else{ ++rQCount; } } } // Case 0: Only digits (without '?') if((lQCount + rQCount) == 0){ return (lDigitSum != rDigitSum); } // Case 1: Odd number of '?' if((lQCount + rQCount) % 2 == 1){ return true; } // Case 2: Even number of '?' int minQCount = min(lQCount, rQCount); lQCount -= minQCount; rQCount -= minQCount; return (lDigitSum + 9 * lQCount / 2 != rDigitSum + 9 * rQCount / 2); } };
/** * @param {string} num * @return {boolean} */ var sumGame = function(num) { function getInfo(s) { var sum = 0; var ques = 0; for(let c of s.split('')) if (c !== '?') sum += c - 0; else ques++; return [sum, ques]; } function check(sum1, sum2, q1, q2, q) { return sum1 + 9* Math.min(q/2, q1) > sum2 + 9 * Math.min(q/2, q2); } var q = getInfo(num)[1]; var [sum1, q1] = getInfo(num.substring(0, Math.floor(num.length/2))); var [sum2, q2] = getInfo(num.substring(Math.floor(num.length/2), num.length)); if (sum1 < sum2) { [sum1, sum2] = [sum2, sum1]; [q1, q2] = [q2, q1]; } return check(sum1, sum2, q1, q2, q) || check(sum2, sum1, q2, q1, q); };
Sum Game
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: i &lt; j &lt; k, nums[j] - nums[i] == diff, and nums[k] - nums[j] == diff. Return the number of unique arithmetic triplets. &nbsp; Example 1: Input: nums = [0,1,4,6,7,10], diff = 3 Output: 2 Explanation: (1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. Example 2: Input: nums = [4,5,6,7,8,9], diff = 2 Output: 2 Explanation: (0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2. (1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2. &nbsp; Constraints: 3 &lt;= nums.length &lt;= 200 0 &lt;= nums[i] &lt;= 200 1 &lt;= diff &lt;= 50 nums is strictly increasing.
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 n = len(nums) for i in range(n): if nums[i] + diff in nums and nums[i] + 2 * diff in nums: ans += 1 return ans
class Solution { public int arithmeticTriplets(int[] nums, int diff) { int result = 0; int[] map = new int[201]; for(int num: nums) { map[num] = 1; if(num - diff >= 0) { map[num] += map[num - diff]; } if(map[num] >= 3) result += 1; } return result; } }
class Solution { public: int arithmeticTriplets(vector<int>& nums, int diff) { int ans=0; for(int i=0;i<nums.size();i++){ for(int j=i+1;j<nums.size();j++){ for(int k=j+1;k<nums.size();k++){ if((nums[j]-nums[i])==diff && (nums[k]-nums[j])==diff){ ans++; } } } } return ans; } };
/** * @param {number[]} nums * @param {number} diff * @return {number} */ var arithmeticTriplets = function(nums, diff) { count = 0 for(let i = 0; i < nums.length - 2; i++){ for(let j = i + 1; j < nums.length - 1; j++){ for(let k = j + 1; k < nums.length; k++){ if(i < j && j < k && nums[j] - nums[i] === diff && nums[k] - nums[j] === diff){ count++ } } } } return count };
Number of Arithmetic Triplets
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. &nbsp; Example 1: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] Example 2: Input: digits = "" Output: [] Example 3: Input: digits = "2" Output: ["a","b","c"] &nbsp; Constraints: 0 &lt;= digits.length &lt;= 4 digits[i] is a digit in the range ['2', '9'].
class Solution: def letterCombinations(self, digits: str) -> List[str]: mapping = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} ans = [] first = True for i in range(len(digits)): # mult: times we should print each digit mult = 1 for j in range(i+1, len(digits)): mult *= len(mapping[digits[j]]) # cycles: times we should run same filling cycle if not first: cycles = len(ans) // mult else: cycles = 1 if times > 1: cycles //= len(mapping[digits[i]]) # cyclically adding each digits to answer answer_ind = 0 for _ in range(cycles): for char in mapping[digits[i]]: for __ in range(mult): if first: ans.append(char) else: ans[answer_ind] += char answer_ind += 1 if first: first = False return ans
class Solution { String[] num = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { List<String> ll = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if (digits.length() != 0) { combination(digits.toCharArray(), ll, sb, 0); } return ll; } public void combination(char[] digits, List<String> ll, StringBuilder sb, int idx) { if (sb.length() == digits.length) { ll.add(sb.toString()); return; } String grp = num[digits[idx] - 48]; for (int i = 0; i < grp.length(); i++) { sb.append(grp.charAt(i)); combination(digits, ll, sb, idx + 1); sb.deleteCharAt(sb.length() - 1); } } }
class Solution { public: void solve(string digit,string output,int index,vector<string>&ans,string mapping[]) { // base condition if(index>=digit.length()) { ans.push_back(output); return; } // digit[index] gives character value to change in integer subtract '0' int number=digit[index]-'0'; // get the string at perticular index in mapping string value=mapping[number]; //runs loop in value string and push that value in out put string ans do recursive call for next index for(int i=0;i<value.length();i++) { output.push_back(value[i]); solve(digit,output,index+1,ans,mapping); //backtrack //backtrach because initially output is empty and one case solves now you have to solve second case in similar way output.pop_back(); } } vector<string> letterCombinations(string digits) { vector<string>ans; //if it is empty input string if(digits.length()==0) { return ans; } string output=""; int index=0; //map every index with string string mapping[10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; solve(digits,output,index,ans,mapping); return ans; } };
var letterCombinations = function(digits) { if(!digits) return [] let res = [] const alpha = { 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz" } const dfs = (i, digits, temp)=>{ if(i === digits.length){ res.push(temp.join('')) return } let chars = alpha[digits[i]] for(let ele of chars){ temp.push(ele) dfs(i+1, digits, temp) temp.pop() } } dfs(0, digits, []) return res };
Letter Combinations of a Phone Number
Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 4, k = 2 Output: 5 Explanation: The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. Example 2: Input: n = 3, k = 1 Output: 3 Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. Example 3: Input: n = 30, k = 7 Output: 796297179 Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. &nbsp; Constraints: 2 &lt;= n &lt;= 1000 1 &lt;= k &lt;= n-1
class Solution: def numberOfSets(self, n: int, k: int) -> int: MOD = 10**9 + 7 @lru_cache(None) def dp(i, k, isStart): if k == 0: return 1 # Found a way to draw k valid segments if i == n: return 0 # Reach end of points ans = dp(i+1, k, isStart) # Skip ith point if isStart: ans += dp(i+1, k, False) # Take ith point as start else: ans += dp(i, k-1, True) # Take ith point as end return ans % MOD return dp(0, k, True)
class Solution { Integer[][][] memo; int n; public int numberOfSets(int n, int k) { this.n = n; this.memo = new Integer[n+1][k+1][2]; return dp(0, k, 1); } int dp(int i, int k, int isStart) { if (memo[i][k][isStart] != null) return memo[i][k][isStart]; if (k == 0) return 1; // Found a way to draw k valid segments if (i == n) return 0; // Reach end of points int ans = dp(i+1, k, isStart); // Skip ith point if (isStart == 1) ans += dp(i+1, k, 0); // Take ith point as start else ans += dp(i, k-1, 1); // Take ith point as end return memo[i][k][isStart] = ans % 1_000_000_007; } }
class Solution { public: int MOD = 1e9+7; int sumDyp(int n, int k, vector<vector<int>> &dp, vector<vector<int>> &sumDp) { if(n < 2) return 0; if(sumDp[n][k] != -1) return sumDp[n][k]; sumDp[n][k] = ((sumDyp(n-1, k, dp, sumDp)%MOD) + (dyp(n, k, dp, sumDp)%MOD))%MOD; return sumDp[n][k]; } int dyp(int n, int k, vector<vector<int>> &dp, vector<vector<int>> &sumDp) { if(n < 2) return 0; if(dp[n][k] != -1) return dp[n][k]; if(k == 1) { dp[n][k] = ((((n-1)%MOD) * (n%MOD))%MOD)/2; return dp[n][k]; } int ans1 = dyp(n-1, k, dp, sumDp); int ans2 = sumDyp(n-1, k-1, dp, sumDp); int ans = ((ans1%MOD) + (ans2%MOD))%MOD; dp[n][k] = ans; return ans; } int numberOfSets(int n, int k) { vector<vector<int>> dp(n+1, vector<int>(k+1, -1)); vector<vector<int>> sumDp(n+1, vector<int>(k+1, -1)); return dyp(n, k, dp, sumDp); } };
var numberOfSets = function(n, k) { return combinations(n+k-1,2*k)%(1e9+7) }; var combinations=(n,k)=>{ var dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>1)) for (let i = 1; i <=n; i++) for (let k = 1; k <i; k++) dp[i][k]=(dp[i-1][k-1]+dp[i-1][k]) %(1e9+7) return dp[n][k] }
Number of Sets of K Non-Overlapping Line Segments
Given&nbsp;the array orders, which represents the orders that customers have done in a restaurant. More specifically&nbsp;orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi&nbsp;is the table customer sit at, and foodItemi&nbsp;is the item customer orders. Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. &nbsp; Example 1: Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] Explanation: The displaying table looks like: Table,Beef Burrito,Ceviche,Fried Chicken,Water 3 ,0 ,2 ,1 ,0 5 ,0 ,1 ,0 ,1 10 ,1 ,0 ,0 ,0 For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". For the table 5: Carla orders "Water" and "Ceviche". For the table 10: Corina orders "Beef Burrito". Example 2: Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] Explanation: For the table 1: Adam and Brianna order "Canadian Waffles". For the table 12: James, Ratesh and Amadeus order "Fried Chicken". Example 3: Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]] &nbsp; Constraints: 1 &lt;=&nbsp;orders.length &lt;= 5 * 10^4 orders[i].length == 3 1 &lt;= customerNamei.length, foodItemi.length &lt;= 20 customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character. tableNumberi&nbsp;is a valid integer between 1 and 500.
class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: column = ['Table'] dish = [] table_dict = {} for order_row in orders : if order_row[-1] not in dish : dish.append(order_row[-1]) for order_row in orders : if order_row[1] not in table_dict.keys() : table_dict[order_row[1]] = {} for food in dish : table_dict[order_row[1]][food] = 0 table_dict[order_row[1]][order_row[-1]] += 1 else : table_dict[order_row[1]][order_row[-1]] += 1 dish.sort() column = column + dish ans = [column] table = [] childDict = {} for key in sorted(table_dict.keys()) : table.append(int(key)) childDict[key] = [] for value in column : if value != 'Table' : childDict[key].append(str(table_dict[key][value])) table.sort() output = [ans[0]] for table_num in table : childList = [str(table_num)] output.append(childList + childDict[str(table_num)]) return output
class Solution { public List<List<String>> displayTable(List<List<String>> orders) { List<List<String>> ans = new ArrayList<>(); List<String> head = new ArrayList<>(); head.add("Table"); Map<Integer, Map<String,Integer>> map = new TreeMap<>(); for(List<String> s: orders){ if(!head.contains(s.get(2))) head.add(s.get(2)); int tbl = Integer.parseInt(s.get(1)); map.putIfAbsent(tbl, new TreeMap<>()); if(map.get(tbl).containsKey(s.get(2))){ Map<String, Integer> m = map.get(tbl); m.put(s.get(2), m.getOrDefault(s.get(2), 0)+1); }else{ map.get(tbl).put(s.get(2), 1); } } String[] arr = head.toArray(new String[0]); Arrays.sort(arr, 1, head.size()); head = Arrays.asList(arr); ans.add(head); for(Map.Entry<Integer, Map<String, Integer>> entry: map.entrySet()){ List<String> l = new ArrayList<>(); l.add(entry.getKey() + ""); Map<String,Integer> m = entry.getValue(); for(int i=1; i<arr.length; i++){ if(m.containsKey(arr[i])){ l.add(m.get(arr[i])+""); }else{ l.add("0"); } } ans.add(l); } System.out.print(map); return ans; } }
class Solution { public: vector<vector<string>> displayTable(vector<vector<string>>& orders) { vector<vector<string>>ans; map<int,map<string,int>>m; set<string>s; //Sets are useful as they dont contain duplicates as well arranges the strings in order. for(auto row:orders) { s.insert(row[2]); m[stoi(row[1])][row[2]]++; } vector<string>dem; dem.push_back("Table"); for(auto a:s) { dem.push_back(a); }//For the first row only ans.push_back(dem); for(auto it:m) { vector<string>row; row.push_back(to_string(it.first)); auto dummy=it.second; for(auto st:s)//we use set here as it has food names stored in asc order. { row.push_back(to_string(dummy[st]));//we access the number of orders. } ans.push_back(row); } return ans; } };
var displayTable = function(orders) { var mapOrders = {}; var tables = []; var dishes = []; for(var i=0;i<orders.length;i++){ //if entry of table doesn't exist in mapOrders if(mapOrders[orders[i][1]] == undefined){ //conver table number to integer var tableNo = Number(orders[i][1]) mapOrders[tableNo] = {} mapOrders[tableNo][orders[i][2]] = 1; //if table number doesn't exist in table array, push it in the table array if(!tables.includes(tableNo)){tables.push(tableNo)} //if dish doesn't exist in dishes array, push it in the dishes array if(!dishes.includes(orders[i][2])){dishes.push(orders[i][2])} }else{ //if entry of table exists in mapOrders //conver table number to integer var tableNo = Number(orders[i][1]) var entry = mapOrders[tableNo]; //check if entry of dish exists in for that table in mapOrders if(entry[orders[i][2]] == undefined){ entry[orders[i][2]] = 1; }else{ entry[orders[i][2]] = entry[orders[i][2]] + 1; } //if dish doesn't exist in dishes array, push it in the dishes array if(!dishes.includes(orders[i][2])){dishes.push(orders[i][2])} } } //sort tables and dishes tables.sort(function(a,b){return a-b}); dishes.sort(); //append word "Table" with all dish names om row[0] of result var res = [["Table"]]; for(var i=0;i<dishes.length;i++){ res[0].push(dishes[i]); } // read through map based on sorted table order for(var i=0;i<tables.length;i++){ // append result in a temp array var tmp = []; //converting number to string using ""+ tmp.push(""+tables[i]); for(var j=0;j<dishes.length;j++){ if(mapOrders[tables[i]][dishes[j]]==undefined){ //if dish doesn't exist against that table then append "0" to the result for that dish tmp.push(""+0); }else{ //if dish exists against that table then append value in mapOrders for that pair of (table,dish) to the result tmp.push(""+mapOrders[tables[i]][dishes[j]]); } } //append the temp array in result res.push(tmp); } return res; };
Display Table of Food Orders in a Restaurant
Under the grammar given below, strings can represent a set of lowercase words. Let&nbsp;R(expr)&nbsp;denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k &gt;= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents. &nbsp; Example 1: Input: expression = "{a,b}{c,{d,e}}" Output: ["ac","ad","ae","bc","bd","be"] Example 2: Input: expression = "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer. &nbsp; Constraints: 1 &lt;= expression.length &lt;= 60 expression[i] consists of '{', '}', ','or lowercase English letters. The given&nbsp;expression&nbsp;represents a set of words based on the grammar given in the description.
class Solution: def braceExpansionII(self, expression: str) -> List[str]: s = list(reversed("{" + expression + "}")) def full_word(): cur = [] while s and s[-1].isalpha(): cur.append(s.pop()) return "".join(cur) def _expr(): res = set() if s[-1].isalpha(): res.add(full_word()) elif s[-1] == "{": s.pop() # remove open brace res.update(_expr()) while s and s[-1] == ",": s.pop() # remove comma res.update(_expr()) s.pop() # remove close brace while s and s[-1] not in "},": res = {e + o for o in _expr() for e in res} return res return sorted(_expr())
class Solution { // To Get the value of index traversed in a recursive call. int index = 0; public List<String> braceExpansionII(String expression) { List<String> result = util(0, expression); Set<String> set = new TreeSet<>(); set.addAll(result); return new ArrayList<>(set); } List<String> util(int startIndex, String expression) { // This represents processed List in the current recursion. List<String> currentSet = new ArrayList<>(); boolean isAdditive = false; String currentString = ""; // This represents List that is being processed and not yet merged to currentSet. List<String> currentList = new ArrayList<>(); for (int i = startIndex; i < expression.length(); ++i) { if (expression.charAt(i) == ',') { isAdditive = true; if (currentString != "" && currentList.size() == 0) { currentSet.add(currentString); } else if (currentList.size() > 0) { for (var entry : currentList) { currentSet.add(entry); } } currentString = ""; currentList = new ArrayList<>(); } else if (expression.charAt(i) >= 'a' && expression.charAt(i) <= 'z') { if (currentList.size() > 0) { List<String> tempStringList = new ArrayList<>(); for (var entry : currentList) { tempStringList.add(entry + expression.charAt(i)); } currentList = tempStringList; } else { currentString = currentString + expression.charAt(i); } } else if (expression.charAt(i) == '{') { List<String> list = util(i + 1, expression); // System.out.println(list); // Need to merge the returned List. It could be one of the following. // 1- ..., {a,b,c} // 2- a{a,b,c} // 3- {a,b,c}{d,e,f} // 3- {a,b,c}d if (i > startIndex && expression.charAt(i - 1) == ',') { // Case 1 currentList = list; } else { if (currentList.size() > 0) { List <String> tempList = new ArrayList<>(); for (var entry1 : currentList) { for (var entry2 : list) { // CASE 3 tempList.add(entry1 + currentString + entry2); } } // System.out.println(currentList); currentList = tempList; currentString = ""; } else if (currentString != "") { List<String> tempList = new ArrayList<>(); for (var entry : list) { // case 2 tempList.add(currentString + entry); } currentString = ""; currentList = tempList; } else { // CASE 1 currentList = list; } } // Increment i to end of next recursion's processing. i = index; } else if (expression.charAt(i) == '}') { if (currentString != "") { currentSet.add(currentString); } // {a{b,c,d}} if (currentList.size() > 0) { for (var entry : currentList) { currentSet.add(entry + currentString); } currentList = new ArrayList<>(); } index = i; return new ArrayList<>(currentSet); } } if (currentList.size() > 0) { currentSet.addAll(currentList); } // {...}a if (currentString != "") { List<String> tempSet = new ArrayList<>(); if (currentSet.size() > 0) { for (var entry : currentSet) { tempSet.add(entry + currentString); } currentSet = tempSet; } else { currentSet = new ArrayList<>(); currentSet.add(currentString); } } return new ArrayList<>(currentSet); } }
class Solution { public: vector<string> braceExpansionII(string expression) { string ss; int n = expression.size(); for(int i = 0; i < n; i++){ if(expression[i] == ','){ ss += '+'; } else{ ss += expression[i]; if((isalpha(expression[i]) || expression[i] == '}') && i+1 < n && (isalpha(expression[i+1]) || expression[i+1] == '{')){ ss += '*'; } } } stack<char>stk1; vector<string>postfix; for(char c:ss){ if(c == '{'){ stk1.push(c); } else if(c == '}') { while(stk1.top() != '{'){ postfix.push_back(string(1, stk1.top())); stk1.pop(); } stk1.pop(); } else if(c == '+'){ while(!stk1.empty() && (stk1.top() == '+' || stk1.top() == '*')){ postfix.push_back(string(1, stk1.top())); stk1.pop(); } stk1.push(c); } else if(c == '*'){ while(!stk1.empty() && stk1.top() == '*'){ postfix.push_back(string(1, stk1.top())); stk1.pop(); } stk1.push(c); } else { postfix.push_back(string(1, c)); } } while(!stk1.empty()){ postfix.push_back(string(1, stk1.top())); stk1.pop(); } /*for(string sp:postfix){ cout << sp << " "; } cout << endl;*/ stack<vector<string>>cont; for(string s:postfix){ if(isalpha(s[0])){ cont.push({s}); } else { vector<string>second = cont.top(); cont.pop(); vector<string>first = cont.top(); cont.pop(); if(s[0] == '+'){ for(string sec:second){ first.push_back(sec); } cont.push(first); } else { vector<string>cartesian; for(string fst:first){ for(string sec:second){ cartesian.push_back(fst + sec); } } cont.push(cartesian); } } } set<string>sstr; for(string sc:cont.top()){ sstr.insert(sc); } vector<string>ret(sstr.begin(), sstr.end()); return ret; } };```
var braceExpansionII = function(expression) { // , mutiplier = [''] const char = ('{' + expression + '}').split('').values() const result = [...rc(char)]; result.sort((a,b) => a.localeCompare(b)); return result; }; function rc (char) { const result = new Set(); let resolved = [''] let chars = ''; let currentChar = char.next().value; while (currentChar !== '}' && currentChar) { if (currentChar === '{') { resolved = mix(mix(resolved, [chars]), rc(char)); chars = ''; } else if (currentChar === ',') { for (const v of mix(resolved, [chars])) { result.add(v); } chars = ''; resolved = ['']; } else { chars += currentChar; } currentChar = char.next().value; } for (const v of mix(resolved, [chars])) { result.add(v); } return result; // everything } function mix (a, b) { const result = []; for (const ca of a) { for (const cb of b) { result.push(ca + cb); } } return result; }
Brace Expansion II
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. A shift on s consists of moving the leftmost character of s to the rightmost position. For example, if s = "abcde", then it will be "bcdea" after one shift. &nbsp; Example 1: Input: s = "abcde", goal = "cdeab" Output: true Example 2: Input: s = "abcde", goal = "abced" Output: false &nbsp; Constraints: 1 &lt;= s.length, goal.length &lt;= 100 s and goal consist of lowercase English letters.
class Solution: def rotateString(self, s: str, goal: str) -> bool: for x in range(len(s)): s = s[-1] + s[:-1] if (goal == s): return True return False
class Solution { public boolean rotateString(String s, String goal) { int n = s.length(), m = goal.length(); if (m != n) return false; for (int offset = 0; offset < n; offset++) { if (isMatch(s, goal, offset)) return true; } return false; } private boolean isMatch(String s, String g, int offset) { int n = s.length(); for (int si = 0; si < n; si++) { int gi = (si + offset) % n; if (s.charAt(si) != g.charAt(gi)) return false; } return true; } }
class Solution { public: bool rotateString(string s, string goal) { if(s.size()!=goal.size()){ return false; } string temp=s+s; if(temp.find(goal)!=-1){ return true; } return false; } };
var rotateString = function(s, goal) { const n = s.length; for(let i = 0; i < n; i++) { s = s.substring(1) + s[0]; if(s === goal) return true; } return false; };
Rotate String
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node. &nbsp; Example 1: Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49 Output: 75 Explanation: One possible path is 0 -&gt; 1 -&gt; 0 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 + 10 + 10 = 40 &lt;= 49. The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75. Example 2: Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30 Output: 25 Explanation: One possible path is 0 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 = 20 &lt;= 30. The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25. Example 3: Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50 Output: 7 Explanation: One possible path is 0 -&gt; 1 -&gt; 3 -&gt; 1 -&gt; 0. The total time taken is 10 + 13 + 13 + 10 = 46 &lt;= 50. The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7. &nbsp; Constraints: n == values.length 1 &lt;= n &lt;= 1000 0 &lt;= values[i] &lt;= 108 0 &lt;= edges.length &lt;= 2000 edges[j].length == 3 0 &lt;= uj &lt; vj &lt;= n - 1 10 &lt;= timej, maxTime &lt;= 100 All the pairs [uj, vj] are unique. There are at most four edges connected to each node. The graph may not be connected.
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: graph = defaultdict(list) # build graph for edge in edges: graph[edge[0]].append((edge[1], edge[2])) graph[edge[1]].append((edge[0], edge[2])) q = deque() q.append((0, 0, values[0], set([0]))) cache = {} maxPoint = 0 while q: currV, currTime, currPoints, currSet = q.popleft() if currV in cache: # if vertex has been visited, and if the previousTime is # less or equal to current time but current points is lower? # then this path can't give us better quality so stop proceeding. prevTime, prevPoints = cache[currV] if prevTime <= currTime and prevPoints > currPoints: continue cache[currV] = (currTime, currPoints) # can't go over the maxTime limit if currTime > maxTime: continue # collect maxPoint only if current vertex is 0 if currV == 0: maxPoint = max(maxPoint, currPoints) for neigh, neighTime in graph[currV]: newSet = currSet.copy() # collects quality only if not collected before if neigh not in currSet: newSet.add(neigh) newPoint = currPoints + values[neigh] else: newPoint = currPoints q.append((neigh, currTime + neighTime, newPoint, newSet)) return maxPoint
class Solution { public int maximalPathQuality(int[] values, int[][] edges, int maxTime) { int n = values.length; List<int[]>[] adj = new List[n]; for (int i = 0; i < n; ++i) adj[i] = new LinkedList(); for (int[] e : edges) { int i = e[0], j = e[1], t = e[2]; adj[i].add(new int[]{j, t}); adj[j].add(new int[]{i, t}); } int[] res = new int[1]; int[] seen = new int[n]; seen[0]++; dfs(adj, 0, values, maxTime, seen, res, values[0]); return res[0]; } private void dfs(List<int[]>[] adj, int src, int[] values, int maxTime, int[] seen, int[] res, int sum) { if (0 == src) { res[0] = Math.max(res[0], sum); } if (0 > maxTime) return; for (int[] data : adj[src]) { int dst = data[0], t = data[1]; if (0 > maxTime - t) continue; seen[dst]++; dfs(adj, dst, values, maxTime - t, seen, res, sum + (1 == seen[dst] ? values[dst] : 0)); seen[dst]--; } } }
class Solution { public: int maximalPathQuality(vector<int>& values, vector<vector<int>>& edges, int maxTime) { int n = values.size(); int res = values[0]; vector<vector<pair<int,int>>> graph(n); for(int i=0;i<edges.size();i++) { graph[edges[i][0]].push_back({edges[i][1], edges[i][2]}); graph[edges[i][1]].push_back({edges[i][0], edges[i][2]}); } vector<int> visited(n, 0); dfs(graph, values, visited, res, 0, 0, 0, maxTime); return res; } void dfs(vector<vector<pair<int,int>>>& graph, vector<int>& values, vector<int>& visited, int& res, int node, int score, int time, int& maxTime) { if(time > maxTime) return; if(visited[node] == 0) score += values[node]; &nbsp; &nbsp; &nbsp; &nbsp;visited[node]++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(node == 0) res = max(res, score); for(auto it : graph[node]) { int neigh = it.first; int newTime = time + it.second; dfs(graph, values, visited, res, neigh, score, newTime, maxTime); } visited[node]--; } };
var maximalPathQuality = function(values, edges, maxTime) { const adjacencyList = values.map(() => []); for (const [node1, node2, time] of edges) { adjacencyList[node1].push([node2, time]); adjacencyList[node2].push([node1, time]); } const dfs = (node, quality, time, seen) => { // if we returned back to the 0 node, then we log it as a valid value let best = node === 0 ? quality : 0; // try to visit all the neighboring nodes within the maxTime // given while recording the max for (const [neighbor, routeTime] of adjacencyList[node]) { const totalTime = time + routeTime; if (totalTime > maxTime) continue; if (seen.has(neighbor)) { best = Math.max(best, dfs(neighbor, quality, totalTime, seen)); } else { seen.add(neighbor); best = Math.max(best, dfs(neighbor, quality + values[neighbor], totalTime, seen)); seen.delete(neighbor); } } return best; } return dfs(0, values[0], 0, new Set([0])); };
Maximum Path Quality of a Graph
A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events. Implement the MyCalendarThree class: MyCalendarThree() Initializes the object. int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar. &nbsp; Example 1: Input ["MyCalendarThree", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] Output [null, 1, 1, 2, 3, 3, 3] Explanation MyCalendarThree myCalendarThree = new MyCalendarThree(); myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking. myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking. myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking. myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking. myCalendarThree.book(5, 10); // return 3 myCalendarThree.book(25, 55); // return 3 &nbsp; Constraints: 0 &lt;= start &lt; end &lt;= 109 At most 400 calls will be made to book.
import bisect class MyCalendarThree: def __init__(self): self.events = [] def book(self, start: int, end: int) -> int: L, R = 1, 0 bisect.insort(self.events, (start, L)) bisect.insort(self.events, (end, R)) res = 0 cnt = 0 for _, state in self.events: #if an interval starts, increase the counter #othewise, decreas the counter cnt += 1 if state == L else -1 res = max(res, cnt) return res
class MyCalendarThree { TreeMap<Integer, Integer> map; public MyCalendarThree() { map = new TreeMap<>(); } public int book(int start, int end) { if(map.isEmpty()){ map.put(start, 1); map.put(end,-1); return 1; } //upvote if you like the solution map.put(start, map.getOrDefault(start,0)+1); map.put(end, map.getOrDefault(end,0)-1); int res = 0; int sum = 0; for(Map.Entry<Integer, Integer> e: map.entrySet()){ sum += e.getValue(); res = Math.max(res,sum); } return res; } }
class MyCalendarThree { public: map<int,int>mp; MyCalendarThree() { } int book(int start, int end) { mp[start]++; mp[end]--; int sum = 0; int ans = 0; for(auto it = mp.begin(); it != mp.end(); it++){ sum += it->second; ans = max(ans,sum); } return ans; } };
var MyCalendarThree = function() { this.intersections = []; this.kEvents = 0; }; /** * @param {number} start * @param {number} end * @return {number} */ MyCalendarThree.prototype.book = function(start, end) { let added = false; for(let i = 0; i < this.intersections.length; i++) { const a = this.intersections[i]; if(end <= a.start) { this.intersections.splice(i, 0, {start, end, count: 1}); this.kEvents = Math.max(this.kEvents, 1); this.added = true; break; } if(start < a. start) { this.intersections.splice(i, 0, {start, end: a.start, count: 1}); i++; start = a.start; } if(a.start < start && start < a.end ) { this.intersections.splice(i, 0, {start: a.start, end: start, count: a.count}); i++; a.start = start; } if(end < a.end) { this.intersections.splice(i + 1, 0, {start: end, end: a.end, count: a.count}); a.count++; a.end = end; this.kEvents = Math.max(this.kEvents, a.count); this.added = true; break; } if(end === a.end) { a.count++; a.end = end; this.kEvents = Math.max(this.kEvents, a.count); this.added = true; break; } if(a.start === start && a.end < end ) { a.count++; this.kEvents = Math.max(this.kEvents, a.count); start = a.end; } } if(!added) { this.intersections.push({start, end, count: 1}); this.kEvents = Math.max(this.kEvents, 1); } return this.kEvents; };
My Calendar III
You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid. A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1. &nbsp; Example 1: Input: grid = [[2,4],[6,8]], x = 2 Output: 4 Explanation: We can make every element equal to 4 by doing the following: - Add x to 2 once. - Subtract x from 6 once. - Subtract x from 8 twice. A total of 4 operations were used. Example 2: Input: grid = [[1,5],[2,3]], x = 1 Output: 5 Explanation: We can make every element equal to 3. Example 3: Input: grid = [[1,2],[3,4]], x = 2 Output: -1 Explanation: It is impossible to make every element equal. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 105 1 &lt;= m * n &lt;= 105 1 &lt;= x, grid[i][j] &lt;= 104
class Solution: def minOperations(self, grid: List[List[int]], x: int) -> int: m = len(grid) n = len(grid[0]) # handle the edge case if m==1 and n==1: return 0 # transform grid to array, easier to operate arr = [] for i in range(m): arr+=grid[i] arr.sort() # the median is arr[len(arr)//2] when len(arr) is odd # or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even. cand1 = arr[len(arr)//2] cand2 = arr[len(arr)//2-1] return min( self.get_num_operations_to_target(grid, cand1, x), self.get_num_operations_to_target(grid, cand2, x) ) def get_num_operations_to_target(self, grid, target,x): """Get the total number of operations to transform all grid elements to the target value.""" ans = 0 for i in range(len(grid)): for j in range(len(grid[0])): if abs(grid[i][j]-target)%x!=0: return -1 else: ans+=abs(grid[i][j]-target)//x return ans
class Solution { public int minOperations(int[][] grid, int x) { int[] arr = new int[grid.length * grid[0].length]; int index = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { arr[index++] = grid[i][j]; } } Arrays.sort(arr); int median = arr[(arr.length - 1) / 2]; int steps = 0; for (int num : arr) { if (num == median) { continue; } if (Math.abs(num - median) % x != 0) { return -1; } steps += (Math.abs(num - median) / x); } return steps; } }
class Solution { public: int minOperations(vector<vector<int>>& grid, int x) { vector<int>nums; int m=grid.size(),n=grid[0].size(); for(int i=0;i<m;i++) for(int j=0;j<n;j++) nums.push_back(grid[i][j]); sort(nums.begin(),nums.end()); int target=nums[m*n/2],ans=0; for(int i=m*n-1;i>=0;i--){ if(abs(nums[i]-target)%x!=0) return -1; else ans+=abs(nums[i]-target)/x; } return ans; } };
var minOperations = function(grid, x) { let remainder = -Infinity, flatten = [], res = 0; for(let i = 0;i<grid.length;i++){ for(let j = 0;j<grid[i].length;j++){ if(remainder === -Infinity) remainder = grid[i][j] % x; else if(remainder !== grid[i][j] % x){ return -1; } flatten.push(grid[i][j]) } } flatten.sort((a,b)=> a-b); let median = flatten[~~(flatten.length/2)] for(let i = 0;i<flatten.length;i++){ res += Math.abs(flatten[i] - median) / x } return res; };
Minimum Operations to Make a Uni-Value Grid
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b. A node a is an ancestor of b if either: any child of a is equal to b&nbsp;or any child of a is an ancestor of b. &nbsp; Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. Example 2: Input: root = [1,null,2,null,0,3] Output: 3 &nbsp; Constraints: The number of nodes in the tree is in the range [2, 5000]. 0 &lt;= Node.val &lt;= 105
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: self.max_diff = float('-inf') def dfs(node,prev_min,prev_max): if not node: return dfs(node.left,min(prev_min,node.val),max(prev_max,node.val)) dfs(node.right,min(prev_min,node.val),max(prev_max,node.val)) self.max_diff = max(abs(node.val-prev_min),abs(node.val-prev_max),self.max_diff) dfs(root,root.val,root.val) return self.max_diff
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int maxAncestorDiff(TreeNode root) { if (root == null) return 0; return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE); } public int find(TreeNode root, int min, int max) { if (root == null) return Math.abs(max-min); min = Math.min(min, root.val); max = Math.max(max, root.val); return Math.max(find(root.left, min, max), find(root.right, min, max)); } }
class Solution { private: int maxDiff; pair <int, int> helper(TreeNode* root) { if (root == NULL) return {INT_MAX, INT_MIN}; pair <int, int> L = helper(root -> left), R = helper(root -> right); pair <int, int> minMax = {min(L.first, R.first), max(L.second, R.second)}; if (minMax.first != INT_MAX) maxDiff = max(maxDiff, max(abs(root -> val - minMax.first), abs(root -> val - minMax.second))); return {min(root -> val, minMax.first), max(root -> val, minMax.second)}; } public: int maxAncestorDiff(TreeNode* root) { maxDiff = INT_MIN; helper(root); return maxDiff; } };
var maxAncestorDiff = function(root) { let ans = 0; const traverse = (r = root, mx = root.val, mn = root.val) => { if(!r) return; ans = Math.max(ans, Math.abs(mx - r.val), Math.abs(mn - r.val)); mx = Math.max(mx, r.val); mn = Math.min(mn, r.val); traverse(r.left, mx, mn); traverse(r.right, mx, mn); } traverse(); return ans; };
Maximum Difference Between Node and Ancestor
Let's play the minesweeper game (Wikipedia, online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), digit ('1' to '8') represents how many mines are adjacent to this revealed square, and 'X' represents a revealed mine. You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). Return the board after revealing this position according to the following rules: If a mine 'M' is revealed, then the game is over. You should change it to 'X'. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed. &nbsp; Example 1: Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] Example 2: Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2] Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]] &nbsp; Constraints: m == board.length n == board[i].length 1 &lt;= m, n &lt;= 50 board[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'. click.length == 2 0 &lt;= clickr &lt; m 0 &lt;= clickc &lt; n board[clickr][clickc] is either 'M' or 'E'.
class Solution: def calMines(self,board,x,y): directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)] mines = 0 for d in directions: r, c = x+d[0],y+d[1] if self.isValid(board,r,c) and (board[r][c] == 'M' or board[r][c] == 'X'): mines+=1 return mines def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: x,y = click[0],click[1] options = [] if board[x][y] == "M": board[x][y] = "X" else: count = self.calMines(board,x,y) if count == 0: board[x][y] = "B" for r in range(x-1,x+2): for c in range(y-1,y+2): if self.isValid(board,r,c) and board[r][c]!='B': self.updateBoard(board,[r,c]) else: board[x][y] = str(count) return board def isValid(self,board,a,b): return 0<=a<len(board) and 0<=b<len(board[0])
class Solution { public char[][] updateBoard(char[][] board, int[] click) { int r = click[0]; int c = click[1]; if(board[r][c] == 'M') { board[r][c] = 'X'; return board; } dfs(board, r, c); return board; } private void dfs(char[][]board, int r, int c) { if(r < 0 || r >= board.length || c >= board[0].length || c < 0 || board[r][c] == 'B')//Stop case return; int num = countMine(board, r, c);//count how many adjacent mines if(num != 0) { board[r][c] = (char)('0' + num); return; } else { board[r][c] = 'B'; dfs(board, r + 1, c);//recursively search all neighbors dfs(board, r - 1, c); dfs(board, r, c + 1); dfs(board, r, c - 1); dfs(board, r - 1, c - 1); dfs(board, r + 1, c - 1); dfs(board, r - 1, c + 1); dfs(board, r + 1, c + 1); } } private int countMine(char[][]board, int r, int c) { int count = 0; for(int i = r - 1; i <= r + 1; ++i) { for(int j = c - 1; j <= c + 1; ++j) { if(i >= 0 && i < board.length && j >= 0 && j < board[0].length) { if(board[i][j] == 'M') count++; } } } return count; } }
class Solution { public: int m, n ; vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) { if(board[click[0]][click[1]] == 'M'){ board[click[0]][click[1]] = 'X' ; return board ; } else{ m = board.size(), n = board[0].size() ; dfs(click[0], click[1], board) ; } return board ; } const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; const int dy[8] = {0, -1, 0, 1, 1, -1, -1, 1}; void dfs(int cr, int cc, vector<vector<char>> &board){ int count = 0 ; for(int i = 0 ; i < 8 ; i++){ int nr = cr + dx[i], nc = cc + dy[i] ; if(nr<0 || nr>=m || nc<0 || nc >=n || board[nr][nc]!='M') continue; count++ ; } if(count!=0){ board[cr][cc] = '0'+count ; return ; }else{ board[cr][cc] = 'B' ; for(int i = 0 ; i < 8 ; i++){ int nr = cr + dx[i], nc = cc + dy[i] ; if(nr<0 || nr>=m || nc<0 || nc >=n || board[nr][nc]!='E') continue; dfs(nr, nc, board) ; } } } };
var updateBoard = function(board, click) { const [clickR, clickC] = click; const traverseAround = ({ currentRow, currentCol, fun }) => { for (let row = -1; row <= 1; row++) { for (let col = -1; col <= 1; col++) { fun(currentRow + row, currentCol + col); } } }; const getMinesCount = (currentRow, currentCol) => { let result = 0; function check(row, col) { const value = board[row]?.[col]; if (value == 'M') result += 1; } traverseAround({ currentRow, currentCol, fun: check }); return result; }; const dfs = (row = clickR, col = clickC) => { const currnet = board[row]?.[col]; if (currnet !== 'E') return; const minesCount = getMinesCount(row, col); board[row][col] = minesCount === 0 ? 'B' : `${minesCount}`; if (minesCount > 0) return; traverseAround({ currentRow: row, currentCol: col, fun: dfs }); }; board[clickR][clickC] === 'M' ? board[clickR][clickC] = 'X' : dfs(); return board; };
Minesweeper
You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can: Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j]. Replace the leaf node in trees[i] with trees[j]. Remove trees[j] from trees. Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST. A BST (binary search tree) is a binary tree where each node satisfies the following property: Every node in the node's left subtree has a value&nbsp;strictly less&nbsp;than the node's value. Every node in the node's right subtree has a value&nbsp;strictly greater&nbsp;than the node's value. A leaf is a node that has no children. &nbsp; Example 1: Input: trees = [[2,1],[3,2,5],[5,4]] Output: [3,2,5,1,null,4] Explanation: In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1]. Delete trees[0], so trees = [[3,2,5,1],[5,4]]. In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0]. Delete trees[1], so trees = [[3,2,5,1,null,4]]. The resulting tree, shown above, is a valid BST, so return its root. Example 2: Input: trees = [[5,3,8],[3,2,6]] Output: [] Explanation: Pick i=0 and j=1 and merge trees[1] into trees[0]. Delete trees[1], so trees = [[5,3,8,2,6]]. The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null. Example 3: Input: trees = [[5,4],[3]] Output: [] Explanation: It is impossible to perform any operations. &nbsp; Constraints: n == trees.length 1 &lt;= n &lt;= 5 * 104 The number of nodes in each tree is in the range [1, 3]. Each node in the input may have children but no grandchildren. No two roots of trees have the same value. All the trees in the input are valid BSTs. 1 &lt;= TreeNode.val &lt;= 5 * 104.
class Solution: def canMerge(self, trees: List[TreeNode]) -> TreeNode: n = len(trees) if n == 1: return trees[0] value_to_root = {} # Map each integer root value to its node appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf self.saw_conflict = False # If this is ever true, break out of function and return None leaf_value_to_parent_node = {} def is_leaf_node(curr: TreeNode) -> bool: return curr.left is None and curr.right is None def get_size(curr: TreeNode) -> int: # DFS to count Binary Tree Size if curr is None: return 0 return 1 + get_size(curr.left) + get_size(curr.right) def is_valid_bst(curr: TreeNode, lo=-math.inf, hi=math.inf) -> bool: # Standard BST validation code if curr is None: return True return all((lo < curr.val < hi, is_valid_bst(curr.left, lo, curr.val), is_valid_bst(curr.right, curr.val, hi))) def process_child(child_node: TreeNode, parent: TreeNode) -> None: if child_node is None: return None elif child_node.val in leaf_value_to_parent_node or child_node.val in appeared_as_middle_child: self.saw_conflict = True # Already saw this child node's value in a non-root node elif is_leaf_node(child_node): leaf_value_to_parent_node[child_node.val] = parent elif child_node.val in value_to_root: self.saw_conflict = True else: appeared_as_middle_child.add(child_node.val) process_child(child_node.left, child_node) process_child(child_node.right, child_node) def process_root(curr_root: TreeNode) -> None: value_to_root[curr_root.val] = curr_root if curr_root.val in appeared_as_middle_child: self.saw_conflict = True else: process_child(curr_root.left, curr_root) process_child(curr_root.right, curr_root) for root_here in trees: process_root(root_here) if self.saw_conflict: return None final_expected_size = len(leaf_value_to_parent_node) + len(appeared_as_middle_child) + 1 final_root = None # The root of our final BST will be stored here while value_to_root: root_val, root_node_to_move = value_to_root.popitem() if root_val not in leaf_value_to_parent_node: # Possibly found main root if final_root is None: final_root = root_node_to_move else: return None # Found two main roots else: new_parent = leaf_value_to_parent_node.pop(root_val) if new_parent.left is not None and new_parent.left.val == root_val: new_parent.left = root_node_to_move continue elif new_parent.right is not None and new_parent.right.val == root_val: new_parent.right = root_node_to_move else: return None # Didn't find a place to put this node # Didn't find any candidates for main root, or have a cycle, or didn't use all trees if final_root is None or not is_valid_bst(final_root) or get_size(final_root) != final_expected_size: return None return final_root
class Solution { public TreeNode canMerge(List<TreeNode> trees) { //Map root value to tree HashMap<Integer, TreeNode> map = new HashMap<>(); for(TreeNode t : trees){ map.put(t.val, t); } // Merge trees for(TreeNode t : trees){ if(map.containsKey(t.val)){ merger(t, map); } } //After merging we should have only one tree left else return null if(map.size() != 1) return null; else { //Return the one tree left after merging for(int c : map.keySet()) { //Check if final tree is valid else return null if(isValidBST(map.get(c))){ return map.get(c); } else return null; } } return null; } void merger(TreeNode t, HashMap<Integer, TreeNode> map){ map.remove(t.val); // Remove current tree to prevent cyclical merging For. 2->3(Right) and 3->2(Left) //Merge on left if(t.left != null && map.containsKey(t.left.val) ){ // Before merging child node, merge the grandchild nodes merger(map.get(t.left.val), map); t.left = map.get(t.left.val); map.remove(t.left.val); } // Merge on right if(t.right!=null && map.containsKey(t.right.val) ){ // Before merging child node, merge the grandchild nodes merger(map.get(t.right.val), map); t.right = map.get(t.right.val); map.remove(t.right.val); } // Add tree back to map once right and left merge is complete map.put(t.val, t); } // Validate BST public boolean isValidBST(TreeNode root) { return helper(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean helper(TreeNode root, long min, long max){ if(root == null) return true; if(root.val <= min || root.val >= max) return false; return helper(root.left, min, root.val) && helper(root.right, root.val, max); } }
/** * 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* canMerge(vector<TreeNode*>& trees) { //store the leaves of every node unordered_map<int,TreeNode*> mp; //store the current min and current max nodes in the current tree unordered_map<TreeNode*,pair<int,int>> mini; for(int i=0;i<trees.size();i++) { pair<int,int> ans={trees[i]->val,trees[i]->val}; if(trees[i]->left) { mp[trees[i]->left->val]={trees[i]}; ans.first=trees[i]->left->val; } if(trees[i]->right) { mp[trees[i]->right->val]=trees[i]; ans.second=trees[i]->right->val; } mini[trees[i]]=ans; } //store the number of merging operations we will be doing int count=0; int rootCount=0; TreeNode* root=NULL; //now for every node get the root for(int i=0;i<trees.size();i++) { //if the current tree can be merged into some other tree if(mp.find(trees[i]->val)!=mp.end()) { count++; //merge them TreeNode* parent=mp[trees[i]->val]; if(trees[i]->val < parent->val) { //left child //if the maximum of the current sub tree is greater than the parent value //then return NULL if(parent->val <= mini[trees[i]].second) return NULL; //change the minimum value of the parent tree to the current min value of the tree mini[parent].first=mini[trees[i]].first; //merge the trees parent->left=trees[i]; } else if(trees[i]->val > parent->val) { //right child //if the minimum of the current tree is lesser than the parent value //we cannot merge //so return NULL if(parent->val >= mini[trees[i]].first) return NULL; //change the parent tree maximum to the current tree maximum mini[parent].second=mini[trees[i]].second; //merge the trees parent->right=trees[i]; } //erase the current tree value mp.erase(trees[i]->val); } else{ //it has no other tree to merge //it is the root node we should return if(rootCount==1) return NULL; else { rootCount++; root=trees[i]; } } } //if we are not able to merge all trees return NULL if(count!=trees.size()-1) return NULL; return root; } };
var canMerge = function(trees) { let Node={},indeg={} // traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node let dfs=(node,leftparent=null,rightparent=null)=>{ if(!node)return indeg[node.val]=indeg[node.val]||Number(leftparent!==null||rightparent!==null) node.lp=leftparent,node.rp=rightparent dfs(node.left,node,null),dfs(node.right,null,node) } for(let root of trees) Node[root.val]=root, dfs(root) //there are a lot of potential roots=> no bueno if(Object.values(indeg).reduce((a,b)=>a+b)!=Object.keys(indeg).length-1) return null //find THE root let bigRoot,timesMerged=0 for(let root of trees) if(indeg[root.val]===0) bigRoot=root // traverse the tree while replacing each leaf that can be replaced let rec=(node=bigRoot)=>{ if(!node) return if(!node.left&&!node.right){ let toadd=Node[node.val] Node[node.val]=undefined //invalidating the trees you already used if(toadd===undefined) return //make the change if(node.lp===null&&node.rp===null) return else if(node.lp!==null) node.lp.left=toadd else node.rp.right=toadd timesMerged++ rec(toadd) } else rec(node.left),rec(node.right) } rec() var isValidBST = function(node,l=-Infinity,r=Infinity) { //l and r are the limits node.val should be within if(!node) return true if(node.val<l || node.val >r) return false return isValidBST(node.left,l,node.val-1)&&isValidBST(node.right,node.val+1,r) }; //check if every item was used and if the result bst is valid return !isValidBST(bigRoot)||timesMerged!==trees.length-1?null:bigRoot };
Merge BSTs to Create Single BST
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: Water the plants in order from left to right. After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. You cannot refill the watering can early. You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. &nbsp; Example 1: Input: plants = [2,2,3,3], capacity = 5 Output: 14 Explanation: Start at the river with a full watering can: - Walk to plant 0 (1 step) and water it. Watering can has 3 units of water. - Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water. - Since you cannot completely water plant 2, walk back to the river to refill (2 steps). - Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water. - Since you cannot completely water plant 3, walk back to the river to refill (3 steps). - Walk to plant 3 (4 steps) and water it. Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14. Example 2: Input: plants = [1,1,1,4,2,3], capacity = 4 Output: 30 Explanation: Start at the river with a full watering can: - Water plants 0, 1, and 2 (3 steps). Return to river (3 steps). - Water plant 3 (4 steps). Return to river (4 steps). - Water plant 4 (5 steps). Return to river (5 steps). - Water plant 5 (6 steps). Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30. Example 3: Input: plants = [7,7,7,7,7,7,7], capacity = 8 Output: 49 Explanation: You have to refill before watering each plant. Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49. &nbsp; Constraints: n == plants.length 1 &lt;= n &lt;= 1000 1 &lt;= plants[i] &lt;= 106 max(plants[i]) &lt;= capacity &lt;= 109
class Solution: def wateringPlants(self, plants: List[int], capacity: int) -> int: result = 0 curCap = capacity for i in range(len(plants)): if curCap >= plants[i]: curCap -= plants[i] result += 1 else: result += i * 2 + 1 curCap = capacity - plants[i] return result
class Solution { public int wateringPlants(int[] plants, int capacity) { int count=0,c=capacity; for(int i=0;i<plants.length;i++){ if(c>=plants[i]){ c-=plants[i]; count++; } else { c=capacity; count=count+i+(i+1); c-=plants[i]; } } return count; } }
class Solution { public: int wateringPlants(vector<int>& plants, int capacity) { int result = 0; int curCap = capacity; for (int i=0; i < plants.size(); i++){ if (curCap >= plants[i]){ curCap -= plants[i]; result++; } else{ result += i * 2 + 1; curCap = capacity - plants[i]; } } return result; } };
var wateringPlants = function(plants, capacity) { var cap = capacity; var steps = 0; for(let i = 0; i < plants.length;i++){ if(cap >= plants[i]){ steps = steps + 1; }else{ cap = capacity; steps = steps + (2 *i + 1); } cap = cap - plants[i]; } return steps; };
Watering Plants
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i &lt; j and nums[i] &lt; pivot and nums[j] &lt; pivot, then pi &lt; pj. Similarly for elements greater than pivot, if i &lt; j and nums[i] &gt; pivot and nums[j] &gt; pivot, then pi &lt; pj. Return nums after the rearrangement. &nbsp; Example 1: Input: nums = [9,12,5,10,14,3,10], pivot = 10 Output: [9,5,3,10,10,12,14] Explanation: The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array. The elements 12 and 14 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings. Example 2: Input: nums = [-3,4,3,2], pivot = 2 Output: [-3,2,4,3] Explanation: The element -3 is less than the pivot so it is on the left side of the array. The elements 4 and 3 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -106 &lt;= nums[i] &lt;= 106 pivot equals to an element of nums.
class Solution: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: left=[] mid=[] right=[] for i in nums: if(i<pivot): left.append(i) elif(i==pivot): mid.append(i) else: right.append(i) return left+mid+right
// Time complexity = 2n = O(n) // Space complexity = O(1), or O(n) if the result array is including in the complexity analysis. class Solution { public int[] pivotArray(int[] nums, int pivot) { int[] result = new int[nums.length]; int left = 0, right = nums.length - 1; for(int i = 0; i < nums.length; i++) { if(nums[i] < pivot) { result[left++] = nums[i]; } if(nums[nums.length - 1 - i] > pivot) { result[right--] = nums[nums.length - 1 - i]; } } while(left <= right) { result[left++] = pivot; result[right--] = pivot; } return result; } }
class Solution { public: vector<int> pivotArray(vector<int>& nums, int pivot) { int i = 0; vector<int> res; int cnt = count(nums.begin(), nums.end(), pivot); while(--cnt >= 0) { res.push_back(pivot); } for(int k = 0; k < nums.size(); k++) { if(nums[k] < pivot) { res.insert(res.begin() + i, nums[k]); i++; } else if(nums[k] > pivot) { res.push_back(nums[k]); } else continue; } return res; } };
/** * @param {number[]} nums * @param {number} pivot * @return {number[]} */ var pivotArray = function(nums, pivot) { let n=nums.length; //first Solution with 3 separet Array let lessPivot=[] let equalPivot=[] let bigerPivot=[] for(let i=0;i<n;i++){ if(nums[i]<pivot)lessPivot.push(nums[i]) else if(nums[i]===pivot)equalPivot.push(nums[i]) else bigerPivot.push(nums[i]) } return lessPivot.concat(equalPivot.concat(bigerPivot)) //second Solution with one Array let result=[] for(let num of nums){ if(num<pivot)result.push(num) } for(let num of nums){ if(num===pivot)result.push(num) } for(let num of nums){ if(num>pivot)result.push(num) } return result };
Partition Array According to Given Pivot
A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). Return true if so, or false otherwise. &nbsp; Example 1: Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" Output: true Explanation: The numbers in s are: 1, 3, 4, 6, 12. They are strictly increasing from left to right: 1 &lt; 3 &lt; 4 &lt; 6 &lt; 12. Example 2: Input: s = "hello world 5 x 5" Output: false Explanation: The numbers in s are: 5, 5. They are not strictly increasing. Example 3: Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" Output: false Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing. &nbsp; Constraints: 3 &lt;= s.length &lt;= 200 s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive. The number of tokens in s is between 2 and 100, inclusive. The tokens in s are separated by a single space. There are at least two numbers in s. Each number in s is a positive number less than 100, with no leading zeros. s contains no leading or trailing spaces.
class Solution: def areNumbersAscending(self, s): nums = re.findall(r'\d+', s) return nums == sorted(set(nums), key=int)
// Space Complexity: O(1) // Time Complexity: O(n) class Solution { public boolean areNumbersAscending(String s) { int prev = 0; for(String token: s.split(" ")) { try { int number = Integer.parseInt(token); if(number <= prev) return false; prev = number; } catch(Exception e) {} } return true; } }
class Solution { public: bool areNumbersAscending(string s) { s.push_back(' '); // for last number calculation int prev = -1; string num; for(int i = 0 ; i < s.size() ; ++i) { char ch = s[i]; if(isdigit(ch)) num += ch; else if(ch == ' ' and isdigit(s[i - 1])) { if(stoi(num) <= prev) // number is not strictly increasing return false; prev = stoi(num); num = ""; } } return true; } };
var areNumbersAscending = function(s) { const numbers = []; const arr = s.split(" "); for(let i of arr) { if(isFinite(i)) { if(numbers.length > 0 && numbers[numbers.length - 1] >= i) { return false; } numbers.push(+i); } } return true };
Check if Numbers Are Ascending in a Sentence
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique. &nbsp; Example 1: Input: encoded = [1,2,3], first = 1 Output: [1,0,2,1] Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] Example 2: Input: encoded = [6,2,7,3], first = 4 Output: [4,2,0,7,4] &nbsp; Constraints: 2 &lt;= n &lt;= 104 encoded.length == n - 1 0 &lt;= encoded[i] &lt;= 105 0 &lt;= first &lt;= 105
class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: return [first] + [first:= first ^ x for x in encoded]
class Solution { public int[] decode(int[] encoded, int first) { int[] ans = new int[encoded.length + 1]; ans[0] = first; for (int i = 0; i < encoded.length; i++) { ans[i + 1] = ans[i] ^ encoded[i]; } return ans; } }
class Solution { public: vector<int> decode(vector<int>& encoded, int first) { vector<int> ans{first}; for(int x: encoded) ans.push_back(first^=x); return ans; } };
var decode = function(encoded, first) { return [first].concat(encoded).map((x,i,a)=>{return i===0? x : a[i] ^= a[i-1]}); };
Decode XORed Array
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating. &nbsp; Example 1: Input: s = "0100" Output: 1 Explanation: If you change the last character to '1', s will be "0101", which is alternating. Example 2: Input: s = "10" Output: 0 Explanation: s is already alternating. Example 3: Input: s = "1111" Output: 2 Explanation: You need two operations to reach "0101" or "1010". &nbsp; Constraints: 1 &lt;= s.length &lt;= 104 s[i] is either '0' or '1'.
class Solution: def minOperations(self, s: str) -> int: count = 0 count1 = 0 for i in range(len(s)): if i % 2 == 0: if s[i] == '1': count += 1 if s[i] == '0': count1 += 1 else: if s[i] == '0': count += 1 if s[i] == '1': count1 += 1 return min(count, count1)
class Solution { public int minOperations(String s) { int count0 = 0; // changes required when the string starts from 0 int count1 = 0; // changes required when the string starts from 1 for(int i = 0; i < s.length(); i++){ // string starts with 1 => all chars at even places should be 1 and that at odd places should be 0 if((i % 2 == 0 && s.charAt(i) == '0') || (i % 2 != 0 && s.charAt(i) == '1')) count1++; // string starts with 0 => all chars at even places should be 0 and that at odd places should be 1 else if((i % 2 == 0 && s.charAt(i) == '1') || (i % 2 != 0 && s.charAt(i) == '0')) count0++; } // return minimum of the two return Math.min(count0, count1); } }
class Solution { public: int minOperations(string s) { int n=s.size(), ans=0; for(int i=0;i<n;i++) { if(s[i]-'0' != i%2) ans++; } return min(ans, n-ans); } };
/** * @param {string} s * @return {number} */ var minOperations = function(s) { let counter1=0; let counter2=0; for(let i=0;i<s.length;i++){ if(i%2===0){ if(s[i]==="0"){ counter1++; } if(s[i]==="1"){ counter2++; } } if(i%2===1){ if(s[i]==="1"){ counter1++; } if(s[i]==="0"){ counter2++; } } } return Math.min(counter1,counter2); };
Minimum Changes To Make Alternating Binary String
In a string s&nbsp;of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and&nbsp;"yy". A group is identified by an interval&nbsp;[start, end], where&nbsp;start&nbsp;and&nbsp;end&nbsp;denote the start and end&nbsp;indices (inclusive) of the group. In the above example,&nbsp;"xxxx"&nbsp;has the interval&nbsp;[3,6]. A group is considered&nbsp;large&nbsp;if it has 3 or more characters. Return&nbsp;the intervals of every large group sorted in&nbsp;increasing order by start index. &nbsp; Example 1: Input: s = "abbxxxxzzy" Output: [[3,6]] Explanation: "xxxx" is the only large group with start index 3 and end index 6. Example 2: Input: s = "abc" Output: [] Explanation: We have groups "a", "b", and "c", none of which are large groups. Example 3: Input: s = "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]] Explanation: The large groups are "ddd", "eeee", and "bbb". &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s contains lowercase English letters only.
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: i=0 c=1 prev="" l=len(s) ans=[] while i<l: if s[i]==prev: c+=1 if (i==l-1) & (c>=3): ans.append([i+1-c,i]) else: if c>=3: ans.append([i-c,i-1]) c=1 prev=s[i] i+=1 return ans
class Solution { public List<List<Integer>> largeGroupPositions(String s) { List<List<Integer>> res = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); int count = 1; for (int i = 0; i < s.length() - 1; i++) { // Increment the count until the next element is the same as the previous element. Ex: "aaa" if (s.charAt(i) == s.charAt(i + 1)) { count++; } // Add the first and last indices of the substring to the list when the next element is different from the previous element. Ex: "aaab" else if (s.charAt(i) != s.charAt(i + 1) && count >= 3) { // gives the starting index of substring tmp.add(i - count + 1); // gives the last index of substring tmp.add(i); res.add(tmp); count = 1; tmp = new ArrayList<>(); } else { count = 1; } } // Check for a large group at the end of the string. Ex: "abbb". if (count >= 3) { tmp.add(s.length() - count); tmp.add(s.length() - 1); res.add(tmp); } return res; } }
class Solution { public: vector<vector<int>> largeGroupPositions(string s) { vector<vector<int>> res; int st = 0; int en = 1; while(en < s.size()) { if(s[en] != s[st]) { if(en-st >= 3) { res.push_back({st, en-1}); } st = en; en = st+1; } else { en++; } } if(en-st >= 3) { res.push_back({st, en-1}); } return res; } };
// 77 ms, faster than 97.56% // 45 MB, less than 87.81% var largeGroupPositions = function(s) { let re = /(.)\1{2,}/g; let ans = []; while ((rslt = re.exec(s)) !== null) { ans.push([rslt.index, rslt.index + rslt[0].length-1]); } return ans; };
Positions of Large Groups
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m. &nbsp; Example 1: Input: n = 2 Output: false Explantion: 2 has only two divisors: 1 and 2. Example 2: Input: n = 4 Output: true Explantion: 4 has three divisors: 1, 2, and 4. &nbsp; Constraints: 1 &lt;= n &lt;= 104
import math class Solution: def isThree(self, n: int) -> bool: primes = {3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1, 67:1, 71:1, 73:1, 79:1, 83:1, 89:1, 97:1} if n == 4: return True else: a = math.sqrt(n) if primes.get(a,0): return True else: return False
class Solution { public boolean isThree(int n) { if(n<4 ) return false; int res = (int)Math.sqrt(n); for(int i=2;i*i<n;i++){ if(res%i ==0) return false; } return true; }}
class Solution { public: bool isPrime(int n) { for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true; } bool isThree(int n) { return n != 1 && n != 2 && (int)sqrt(n)*sqrt(n) == n && isPrime(sqrt(n)); } };
var isThree = function(n) { var set = new Set(); for(var i = 1; i<=Math.sqrt(n) && set.size <= 3; i++) { if(n % i === 0) { set.add(i); set.add(n / i); } } return set.size===3; };
Three Divisors
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum. Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized: Answers within 10-5 of the actual value will be accepted. &nbsp; Example 1: Input: positions = [[0,1],[1,0],[1,2],[2,1]] Output: 4.00000 Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve. Example 2: Input: positions = [[1,1],[3,3]] Output: 2.82843 Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843 &nbsp; Constraints: 1 &lt;= positions.length &lt;= 50 positions[i].length == 2 0 &lt;= xi, yi &lt;= 100
class Solution: def getMinDistSum(self, positions: List[List[int]]) -> float: n = len(positions) if n == 1: return 0 def gradient(x,y): ans = [0,0] for i in range(n): denom = math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2)) ans[0] += (x-positions[i][0])/denom if denom else 0 ans[1] += (y-positions[i][1])/denom if denom else 0 return ans def fn(x, y): res = 0 for i in range(n): res += math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2)) return res x = sum(x for x,_ in positions)/n y = sum(y for _,y in positions)/n lr = 1 while lr > 1e-7: dx, dy = gradient(x,y) x -= lr*dx y -= lr*dy lr *= 0.997 if not dx and not dy: lr /= 2 return fn(x,y)
class Solution { private static final double MIN_STEP = 0.0000001; private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; public double getMinDistSum(int[][] positions) { double cx = 0, cy = 0; int n = positions.length; for (int[] pos: positions) { cx += pos[0]; cy += pos[1]; } cx /= n; cy /= n; Node center = new Node(cx, cy, totalDistance(positions, cx, cy)); double step = 50.0; while (step > MIN_STEP) { Node min = center; for (int[] direction: DIRECTIONS) { double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step; double totalDist = totalDistance(positions, dx, dy); if (totalDist < center.dist) min = new Node(dx, dy, totalDist); } if (center == min) step /= 2; center = min; } return center.dist; } private double sq(double p) { return p * p; } private double dist(int[] pos, double x, double y) { return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1])); } private double totalDistance(int[][] positions, double x, double y) { double dist = 0; for (int[] pos: positions) dist += dist(pos, x, y); return dist; } private static class Node { double x, y, dist; Node (double x, double y, double dist) { this.x = x; this.y = y; this.dist = dist; } } }
class Solution { public: const double MIN_STEP = 0.000001; // With 0.00001 not AC const int dx[4] = {0, 0, 1,-1}; const int dy[4] = {1, -1, 0, 0}; double totalDist(vector<vector<int>>& positions, double cx, double cy) { double dist = 0; for (auto p : positions) { dist += hypot(p[0] - cx, p[1] - cy); } return dist; } double getMinDistSum(vector<vector<int>>& positions) { int n = (int)positions.size(); double cx = 0, cy = 0; for (auto p : positions) { cx += p[0], cy += p[1]; } cx /= n, cy /= n; pair<double, double> minDistCenter = {cx, cy}; double minDist = totalDist(positions, cx, cy); //printf("cx = %.4lf, cy = %.4lf, minDist = %.4lf\n", minDistCenter.first, minDistCenter.second, minDist); double step = 50.0; // Because max value of x, y could be 100. So half of that while (step > MIN_STEP) { pair<double, double> tempCenter = minDistCenter; double tempDist = minDist; for (int k = 0; k < 4; k++) { double xx = minDistCenter.first + dx[k] * step; double yy = minDistCenter.second + dy[k] * step; double d = totalDist(positions, xx, yy); //printf("d = %.4lf\n", d); if (d < minDist) { tempCenter = {xx, yy}; tempDist = d; } } if (minDistCenter == tempCenter) step /= 2; minDistCenter = tempCenter; minDist = tempDist; } //printf("minDist = %.4lf\n", minDist); return minDist; } };
/** * @param {number[][]} positions * @return {number} */ var getMinDistSum = function(positions) { /** identify the vertical range and horizontal range start from the center of positions calc the distance test the 4 direction with a certain step if any distance is closer, choose it as the new candidate if all 4 are further, reduce the step **/ let xSum = 0; let ySum = 0; for (const [x, y] of positions) { xSum += x; ySum += y; } let n = positions.length; let x = xSum / n; let y = ySum / n; let step = 0.5; const dirs = [[0, 1], [0, -1], [-1, 0], [1, 0]]; while (step >= 10 ** -5) { const dist = calcDist(x, y); let found = false; for (const [xDiff, yDiff] of dirs) { const newX = x + xDiff * step; const newY = y + yDiff * step; const newDist = calcDist(newX, newY); // console.log(x, y, newDist, dist); if (newDist < dist) { x = newX; y = newY; found = true; break; } } if (!found) { step /= 2; } } return calcDist(x, y); function calcDist(x, y) { let dist = 0; for (const [posX, posY] of positions) { dist += Math.sqrt((x - posX) ** 2 + (y - posY) ** 2); } return dist; } };
Best Position for a Service Centre
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to&nbsp;target. The test cases are generated so that the answer can fit in a 32-bit integer. &nbsp; Example 1: Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Example 2: Input: nums = [9], target = 3 Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 200 1 &lt;= nums[i] &lt;= 1000 All the elements of nums are unique. 1 &lt;= target &lt;= 1000 &nbsp; Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target+1) dp[0] = 1 for i in range(1, target+1): for num in nums: num_before = i - num if num_before >= 0: dp[i] += dp[num_before] return dp[target]
class Solution { public int combinationSum4(int[] nums, int target) { Integer[] memo = new Integer[target + 1]; return recurse(nums, target, memo); } public int recurse(int[] nums, int remain, Integer[] memo){ if(remain < 0) return 0; if(memo[remain] != null) return memo[remain]; if(remain == 0) return 1; int ans = 0; for(int i = 0; i < nums.length; i++){ ans += recurse(nums, remain - nums[i], memo); } memo[remain] = ans; return memo[remain]; } }
class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector<unsigned int> dp(target+1, 0); dp[0] = 1; for (int i = 1; i <= target; i++) { for (auto x : nums) { if (x <= i) { dp[i] += dp[i - x]; } } } return dp[target]; } };
var combinationSum4 = function(nums, target) { const dp = Array(target + 1).fill(0); nums.sort((a,b) => a - b); for(let k=1; k <= target; k++) { for(let n of nums) { if(k < n) break; dp[k] += (k == n) ? 1 : dp[k-n]; } } return dp[target]; };
Combination Sum IV
You are given an array of integers distance. You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not. &nbsp; Example 1: Input: distance = [2,1,1,2] Output: true Example 2: Input: distance = [1,2,3,4] Output: false Example 3: Input: distance = [1,1,1,1] Output: true &nbsp; Constraints: 1 &lt;=&nbsp;distance.length &lt;= 105 1 &lt;=&nbsp;distance[i] &lt;= 105
class Solution: def isSelfCrossing(self, x): n = len(x) if n < 4: return False for i in range(3, n): if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] and 0<=x[i-3]-x[i-1]<=x[i-5]: return True return False
class Solution { public boolean isSelfCrossing(int[] x) { boolean arm = false; boolean leg = false; for (int i = 2; i < x.length; ++i) { int a = f(x, i - 2) - f(x, i - 4); int b = f(x, i - 2); if (arm && x[i] >= b) return true; // cross [i - 2] if (leg && x[i] >= a && a > 0) return true; // cross [i - 4] if (x[i] < a) arm = true; else if (x[i] <= b) leg = true; } return false; } private int f(int[] x, int index) { return (index < 0) ? 0 : x[index]; } }
class Solution { public: bool isSelfCrossing(vector<int>& distance) { if (distance.size() <= 3) return false; //only can have intersection with more than 4 lines distance.insert(distance.begin(), 0); //for the edge case: line i intersect with line i-4 at (0, 0) for (int i = 3; i < distance.size(); i++) { //check line i-3 if (distance[i - 2] <= distance[i] && distance[i - 1] <= distance[i - 3]) return true; //check line i-5 if (i >= 5) { if (distance[i - 1] <= distance[i - 3] && distance[i - 1] >= distance[i - 3] - distance[i - 5] && distance[i - 2] >= distance[i - 4] && distance[i - 2] <= distance[i - 4] + distance[i]) return true; } } return false; } };
class Solution { public boolean isSelfCrossing(int[] x) { boolean arm = false; boolean leg = false; for (int i = 2; i < x.length; ++i) { int a = f(x, i - 2) - f(x, i - 4); int b = f(x, i - 2); if (arm && x[i] >= b) return true; // cross [i - 2] if (leg && x[i] >= a && a > 0) return true; // cross [i - 4] if (x[i] < a) arm = true; else if (x[i] <= b) leg = true; } return false; } private int f(int[] x, int index) { return (index < 0) ? 0 : x[index]; } }
Self Crossing
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the TreeAncestor class: TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array. int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1. &nbsp; Example 1: Input ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] Output [null, 1, 0, -1] Explanation TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor &nbsp; Constraints: 1 &lt;= k &lt;= n &lt;= 5 * 104 parent.length == n parent[0] == -1 0 &lt;= parent[i] &lt; n for all 0 &lt; i &lt; n 0 &lt;= node &lt; n There will be at most 5 * 104 queries.
from math import ceil, log2 from typing import List NO_PARENT = -1 class TreeAncestor: def __init__(self, n: int, parent: List[int]): self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))] self.__initialize(parent) def __initialize(self, parent: List[int]): self.parent[0], prev = parent, parent for jump_pow in range(1, len(self.parent)): cur = self.parent[jump_pow] for i, p in enumerate(prev): if p != NO_PARENT: cur[i] = prev[p] prev = cur def getKthAncestor(self, node: int, k: int) -> int: jump_pow = self.jump_pow while k > 0 and node != NO_PARENT: jumps = 1 << jump_pow if k >= jumps: node = self.parent[jump_pow][node] k -= jumps else: jump_pow -= 1 return node @property def jump_pow(self) -> int: return len(self.parent) - 1
class TreeAncestor { int n; int[] parent; List<Integer>[] nodeInPath; int[] nodeIdxInPath; public TreeAncestor(int n, int[] parent) { this.n = n; this.parent = parent; nodeInPath = new ArrayList[n]; nodeIdxInPath = new int[n]; fill(); } private void fill() { boolean[] inner = new boolean[n]; for (int i = 1; i < n; i++) { inner[parent[i]] = true; } for (int i = 1; i < n; i++) { if (inner[i] || nodeInPath[i] != null) { continue; } List<Integer> path = new ArrayList<>(); int k = i; while (k != -1) { path.add(k); k = parent[k]; } int m = path.size(); for (int j = 0; j < m; j++) { int node = path.get(j); if (nodeInPath[node] != null) break; nodeInPath[node] = path; nodeIdxInPath[node] = j; } } } public int getKthAncestor(int node, int k) { List<Integer> path = nodeInPath[node]; int idx = nodeIdxInPath[node] + k; return idx >= path.size() ? -1 : path.get(idx); } }
class TreeAncestor { public: //go up by only powers of two vector<vector<int>> lift ; TreeAncestor(int n, vector<int>& parent) { lift.resize(n,vector<int>(21,-1)) ; //every node's first ancestor is parent itself for(int i = 0 ; i < n ; ++i ) lift[i][0] = parent[i] ; for(int i = 0 ; i < n ; ++i ){ for(int j = 1 ; j <= 20 ; ++j ){ if(lift[i][j-1] == -1) continue ; lift[i][j] = lift[lift[i][j-1]][j-1] ; } } } int getKthAncestor(int node, int k) { for(int i = 0 ; i <= 20 ; ++i ){ if(k & (1 << i)){ node = lift[node][i] ; if(node == -1) break; } } return node ; } };
/** * @param {number} n * @param {number[]} parent */ var TreeAncestor = function(n, parent) { this.n = n; this.parent = parent; }; /** * @param {number} node * @param {number} k * @return {number} */ /* Qs: 1. Is the given tree a binary tree or n-ary tree? 2. Can k be greater than possible (the total number of ancestors of given node)? Every node has a parent except the root. 1. Check if given node has a parent. If not, return -1. 2. Set given node as the current ancestor and start a while loop which continues while k is greater than 0. At each iteration, we set `ancestor` to the parent of current `ancestor` and decrement k. If k is still greater than 0 but ancestor is -1, that means k is greater than possible. Hence, we return -1. Else, while loop will end when we are at the correct k-th ancestor. We return ancestor. */ TreeAncestor.prototype.getKthAncestor = function(node, k) { // check if given node has a parent if (this.parent[node] === -1) return -1; let ancestor = node; while (k > 0) { if (ancestor === -1) return -1; // k is greater than total number of ancestors of given node ancestor = this.parent[ancestor]; k--; } return ancestor; // T.C: O(k) };
Kth Ancestor of a Tree Node
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col&nbsp;grid&nbsp;of integers, how many 3 x 3 "magic square" subgrids are there?&nbsp; (Each subgrid is contiguous). &nbsp; Example 1: Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]] Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: while this one is not: In total, there is only one magic square inside the given grid. Example 2: Input: grid = [[8]] Output: 0 &nbsp; Constraints: row == grid.length col == grid[i].length 1 &lt;= row, col &lt;= 10 0 &lt;= grid[i][j] &lt;= 15
class Solution: digits = {1, 2, 3, 4, 5, 6, 7, 8, 9} @classmethod def magic_3_3(cls, square: List[List[int]]) -> bool: if set(sum(square, [])) != Solution.digits: return False sum_row0 = sum(square[0]) for r in range(1, 3): if sum(square[r]) != sum_row0: return False if any(sum(col) != sum_row0 for col in zip(*square)): return False sum_main_diagonal = sum_second_diagonal = 0 for i in range(3): sum_main_diagonal += square[i][i] sum_second_diagonal += square[i][2 - i] return sum_main_diagonal == sum_second_diagonal == sum_row0 def numMagicSquaresInside(self, grid: List[List[int]]) -> int: count = 0 rows, cols = len(grid), len(grid[0]) for r in range(rows - 2): for c in range(cols - 2): if Solution.magic_3_3([grid[row_idx][c: c + 3] for row_idx in range(r, r + 3)]): count += 1 return count
class Solution { public int numMagicSquaresInside(int[][] grid) { int n=grid.length,m=grid[0].length,count=0; for(int i=0;i<n-2;i++) { for(int j=0;j<m-2;j++) { if(sum(i,j,grid)) count++; } } return count; } public boolean sum(int x,int y,int[][] grid) { int sum=grid[x][y]+grid[x][y+1]+grid[x][y+2],sum1=0,sum2=0; int []count=new int[10]; for(int i=0;i<3;i++) { sum1=0; sum2=0; for(int j=0;j<3;j++) { sum1+=grid[x+i][y+j]; sum2+=grid[x+j][y+i]; if(grid[x+i][y+j]<1 ||grid[x+i][y+j]>9 ||count[grid[x+i][y+j]]!=0) return false; count[grid[x+i][y+j]]=1; } if(sum1!=sum || sum!=sum2 || sum1!=sum2) return false; } sum1=grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2]; sum2=grid[x][y+2]+grid[x+1][y+1]+grid[x+2][y]; if(sum1!=sum2 || sum1!=sum) return false; return true; }
class Solution { public: int numMagicSquaresInside(vector<vector<int>>& grid) { int result = 0; for(int i = 0; i < grid.size(); i++){ for(int j = 0; j < grid[i].size() ; j++){ if(isMagicSquare(grid, i, j)){ result++; } } } return result; } bool isMagicSquare(vector<vector<int>>& grid, int i, int j){ if(i + 2 < grid.size() && j+2 < grid[i].size()){ int col1 = grid[i][j] + grid[i+1][j] + grid[i+2][j]; int col2 = grid[i][j+1] + grid[i+1][j+1] + grid[i+2][j+1]; int col3 = grid[i][j+2] + grid[i+1][j+2] + grid[i+2][j+2]; int row1 = grid[i][j] + grid[i][j+1] + grid[i][j+2]; int row2 = grid[i+1][j] + grid[i+1][j+1] + grid[i+1][j+2]; int row3 = grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2]; int diag1 = grid[i][j] + grid[i+1][j+1] + grid[i+2][j+2]; int diag2 = grid[i+2][j] + grid[i+1][j+1] + grid[i][j+2]; if( (col1 == col2) && (col1 == col3) && (col1 == row1) && (col1 == row2) && (col1 == row3) && (col1 == diag1) && (col1 == diag2)) { set<int> s({1,2,3,4,5,6,7,8,9}); for(int r = 0 ; r < 3 ; r++){ for(int c = 0; c < 3 ; c++){ s.erase(grid[i + r][j + c]); } } return s.empty(); } } return false; } };
var numMagicSquaresInside = function(grid) { let res = 0; for(let i = 0; i < grid.length - 2; i++){ for(let j = 0; j < grid[0].length - 2; j++){ //only check 4 if(grid[i][j]+grid[i][j+1]+grid[i][j+2]==15 && grid[i][j]+grid[i+1][j]+grid[i+2][j]==15 && grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]==15 && grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]==15){ let set = new Set(); for(let a = i; a<=i+2; a++){ for(let b = j; b<=j+2; b++){ if(grid[a][b]>=1&&grid[a][b]<=9) set.add(grid[a][b]); }} if(set.size===9) res++; }}} return res; };
Magic Squares In Grid
A string is a valid parentheses string (denoted VPS) if it meets one of the following: It is an empty string "", or a single character not equal to "(" or ")", It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(C) = 0, where C is a string with a single character not equal to "(" or ")". depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's. depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's. Given a VPS represented as string s, return the nesting depth of s. &nbsp; Example 1: Input: s = "(1+(2*3)+((8)/4))+1" Output: 3 Explanation: Digit 8 is inside of 3 nested parentheses in the string. Example 2: Input: s = "(1)+((2))+(((3)))" Output: 3 &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'. It is guaranteed that parentheses expression s is a VPS.
class Solution: def maxDepth(self, s: str) -> int: ans = cur = 0 for c in s: if c == '(': cur += 1 ans = max(ans, cur) elif c == ')': cur -= 1 return ans
class Solution { public int maxDepth(String s) { int count = 0; //count current dept of "()" int max = 0; //count max dept of "()" for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { count++; } else if (s.charAt(i) == ')') { count--; } max = Math.max(count, max); } return max; } }
class Solution { public: int maxDepth(string s) { int maxi=0,curr=0; for(int i=0;i<s.size();i++){ if(s[i]=='('){ maxi=max(maxi,++curr); }else if(s[i]==')'){ curr--; } } return maxi; } };
var maxDepth = function(s) { let maxCount = 0, count = 0; for (let i = 0; i < s.length; i++) { if (s[i] === '(') { maxCount = Math.max(maxCount, ++count); } else if (s[i] === ')') { count--; } } return maxCount; };
Maximum Nesting Depth of the Parentheses
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order. &nbsp; Example 1: Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 Output: [0,1,2,3,5] Explanation: At time 0, person 0 shares the secret with person 1. At time 5, person 1 shares the secret with person 2. At time 8, person 2 shares the secret with person 3. At time 10, person 1 shares the secret with person 5.​​​​ Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. Example 2: Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 Output: [0,1,3] Explanation: At time 0, person 0 shares the secret with person 3. At time 2, neither person 1 nor person 2 know the secret. At time 3, person 3 shares the secret with person 0 and person 1. Thus, people 0, 1, and 3 know the secret after all the meetings. Example 3: Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 Output: [0,1,2,3,4] Explanation: At time 0, person 0 shares the secret with person 1. At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. Note that person 2 can share the secret at the same time as receiving it. At time 2, person 3 shares the secret with person 4. Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. &nbsp; Constraints: 2 &lt;= n &lt;= 105 1 &lt;= meetings.length &lt;= 105 meetings[i].length == 3 0 &lt;= xi, yi &lt;= n - 1 xi != yi 1 &lt;= timei &lt;= 105 1 &lt;= firstPerson &lt;= n - 1
class Solution: def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: class UnionFind: def __init__(self): self.parents = {} self.ranks = {} def insert(self, x): if x not in self.parents: self.parents[x] = x self.ranks[x] = 0 def find_parent(self, x): if self.parents[x] != x: self.parents[x] = self.find_parent(self.parents[x]) return self.parents[x] def union(self, x, y): self.insert(x) self.insert(y) x, y = self.find_parent(x), self.find_parent(y) if x == y: return if self.ranks[x] > self.ranks[y]: self.parents[y] = x else: self.parents[x] = y if self.ranks[x] == self.ranks[y]: self.ranks[y] += 1 time2meets = defaultdict(list) for x, y, t in meetings: time2meets[t].append((x, y)) time2meets = sorted(time2meets.items()) curr_know = set([0, firstPerson]) for time, meets in time2meets: uf = UnionFind() for x, y in meets: uf.union(x, y) groups = defaultdict(set) for idx in uf.parents: groups[uf.find_parent(idx)].add(idx) for group in groups.values(): if group & curr_know: curr_know.update(group) return list(curr_know)
class Solution { public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) { // create <time, index> map Map<Integer, List<Integer>> timeToIndexes = new TreeMap<>(); int m = meetings.length; for (int i = 0; i < m; i++) { timeToIndexes.putIfAbsent(meetings[i][2], new ArrayList<>()); timeToIndexes.get(meetings[i][2]).add(i); } UF uf = new UF(n); // base uf.union(0, firstPerson); // for every time we have a pool of people that talk to each other // if someone knows a secret proir to this meeting - all pool will too // if not - reset unions from this pool for (int time : timeToIndexes.keySet()) { Set<Integer> pool = new HashSet<>(); for (int ind : timeToIndexes.get(time)) { int[] currentMeeting = meetings[ind]; uf.union(currentMeeting[0], currentMeeting[1]); pool.add(currentMeeting[0]); pool.add(currentMeeting[1]); } // meeting that took place now should't affect future // meetings if people don't know the secret for (int i : pool) if (!uf.connected(0, i)) uf.reset(i); } // if the person is conneted to 0 - they know a secret List<Integer> ans = new ArrayList<>(); for (int i = 0; i < n; i++) if (uf.connected(i,0)) ans.add(i); return ans; } // regular union find private static class UF { int[] parent, rank; public UF(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; } else { parent[rootQ] = rootP; rank[rootP]++; } } public int find(int p) { while (parent[p] != p) { p = parent[parent[p]]; } return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public void reset(int p) { parent[p] = p; rank[p] = 0; } } }
class Solution { public: vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) { vector<int> res; set<int> ust; ust.insert(0); ust.insert(firstPerson); map<int,vector<pair<int,int>>> mp; for (auto &m : meetings) { mp[m[2]].push_back({m[0],m[1]}); } for (auto &m : mp) { for (auto &v : m.second) { //front to back if (ust.count(v.first)) { ust.insert(v.second); } if (ust.count(v.second)) { ust.insert(v.first); } } for (auto it = m.second.rbegin(); it != m.second.rend(); ++it) { //back to front if (ust.count((*it).first)) { ust.insert((*it).second); } if (ust.count((*it).second)) { ust.insert((*it).first); } } } for (auto it = ust.begin(); it != ust.end(); ++it) res.push_back(*it); return res; } };
var findAllPeople = function(n, meetings, firstPerson) { const timeToMeeting = mapSortedTimeToMeetings(meetings); const peopleThatCurrentlyHaveSecret = new Set([0, firstPerson]); for (const peopleInMeetings of timeToMeeting.values()) { const personToMeetingsWithPeople = mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings); let peopleInMeetingsWithSecret = findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret); // BFS algorithm while (peopleInMeetingsWithSecret.size > 0) { const nextPeopleInMeetingsWithSecret = new Set(); for (const attendee of peopleInMeetingsWithSecret) { for (const personInMeetingWithAttendee of personToMeetingsWithPeople[attendee]) { // only add new people that have the secret otherwise there will be an // infinite loop if (!peopleThatCurrentlyHaveSecret.has(personInMeetingWithAttendee)) { nextPeopleInMeetingsWithSecret.add(personInMeetingWithAttendee); peopleThatCurrentlyHaveSecret.add(personInMeetingWithAttendee); } } } peopleInMeetingsWithSecret = nextPeopleInMeetingsWithSecret; } } return [...peopleThatCurrentlyHaveSecret]; }; // groups all the meetings by time // keys (time) is sorted in ascending order function mapSortedTimeToMeetings(meetings) { meetings.sort((a, b) => a[2] - b[2]); const timeToMeeting = new Map(); for (const [person1, person2, time] of meetings) { if (!timeToMeeting.has(time)) { timeToMeeting.set(time, []); } timeToMeeting.get(time).push([person1, person2]); } return timeToMeeting; } // creates an adjacency list of people and people they are having meetings with function mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings) { const personToMeetingsWithPeople = {}; for (const [person1, person2] of peopleInMeetings) { if (!personToMeetingsWithPeople[person1]) { personToMeetingsWithPeople[person1] = []; } if (!personToMeetingsWithPeople[person2]) { personToMeetingsWithPeople[person2] = []; } personToMeetingsWithPeople[person1].push(person2); personToMeetingsWithPeople[person2].push(person1); } return personToMeetingsWithPeople; } // finds all the people that are in meetings that have the secret // set data structue is used so that people are not duplicated function findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret) { const peopleInMeetingsWithSecret = new Set(); for (const peopleInMeeting of peopleInMeetings) { for (const person of peopleInMeeting) { if (peopleThatCurrentlyHaveSecret.has(person)) { peopleInMeetingsWithSecret.add(person); } } } return peopleInMeetingsWithSecret; }
Find All People With Secret
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. &nbsp; Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. Example 2: Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common subsequence is "abc" and its length is 3. Example 3: Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such common subsequence, so the result is 0. &nbsp; Constraints: 1 &lt;= text1.length, text2.length &lt;= 1000 text1 and text2 consist of only lowercase English characters.
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: def lcs(ind1,ind2): prev=[0 for i in range(ind2+1)] curr=[0 for i in range(ind2+1)] for i in range(1,ind1+1): for j in range(1,ind2+1): if text1[i-1]==text2[j-1]: curr[j]=1+prev[j-1] else: curr[j]=max(prev[j],curr[j-1]) prev=list(curr) # remember to use a new list for prev return prev[-1] ans=lcs(len(text1),len(text2)) return ans
class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(); int n = text2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = 1 + dp[i - 1][j - 1]; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n]; } }
class Solution { public: int longestCommonSubsequence(string text1, string text2) { int dp[1001][1001] = {0}; for(int i = 1; i <= text1.size(); i++) for(int j = 1; j <= text2.size(); j++) if(text1[i-1] == text2[j-1]) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); return dp[text1.size()][text2.size()]; } };
/** * @param {string} text1 * @param {string} text2 * @return {number} */ let memo const dp=(a,b,i,j)=>{ if(i===0||j===0)return 0; if(memo[i][j]!=-1)return memo[i][j]; if(a[i-1]===b[j-1]){ return memo[i][j]= 1+ dp(a,b,i-1,j-1); }else{ return memo[i][j]=Math.max(dp(a,b,i-1,j),dp(a,b,i,j-1)); } } const bottomUp=(a,b)=>{ for(let i=1;i<=a.length;i++){ for(let j=1;j<=b.length;j++){ if(a[i-1]===b[j-1]){ memo[i][j]=1+memo[i-1][j-1] }else{ memo[i][j]=Math.max(memo[i-1][j],memo[i][j-1]); } } } return memo[a.length][b.length] } var longestCommonSubsequence = function(text1, text2) { memo=[]; for(let i=0;i<=text1.length;i++){ memo[i]=[]; for(let j=0;j<=text2.length;j++){ if(i===0||j===0)memo[i][j]=0; else memo[i][j]=-1; } } return bottomUp(text1,text2,text1.length,text2.length); // return dp(text1,text2,text1.length,text2.length); };
Longest Common Subsequence
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText. &nbsp; Example 1: Input: encodedText = "ch ie pr", rows = 3 Output: "cipher" Explanation: This is the same example described in the problem description. Example 2: Input: encodedText = "iveo eed l te olc", rows = 4 Output: "i love leetcode" Explanation: The figure above denotes the matrix that was used to encode originalText. The blue arrows show how we can find originalText from encodedText. Example 3: Input: encodedText = "coding", rows = 1 Output: "coding" Explanation: Since there is only 1 row, both originalText and encodedText are the same. &nbsp; Constraints: 0 &lt;= encodedText.length &lt;= 106 encodedText consists of lowercase English letters and ' ' only. encodedText is a valid encoding of some originalText that does not have trailing spaces. 1 &lt;= rows &lt;= 1000 The testcases are generated such that there is only one possible originalText.
class Solution: def decodeCiphertext(self, encodedText: str, rows: int) -> str: n = len(encodedText) cols = n // rows step = cols + 1 res = "" for i in range(cols): for j in range(i, n, step): res += encodedText[j] return res.rstrip()
class Solution { public String decodeCiphertext(String str, int rows) { //first find column size!! int cols=str.length()/rows; StringBuilder res=new StringBuilder(),new_res=new StringBuilder();; for(int i=0;i<cols;i++) { //iterating diagonally!! for(int j=i;j<str.length();j+=cols+1) res.append(str.charAt(j)); } //removing last spaces!!! int fg=0; for(int i=res.length()-1;i>=0;i--) { if(fg==0&&res.charAt(i)==' ') continue; fg=1; new_res.append(res.charAt(i)); } return new_res.reverse().toString(); } }
class Solution { public: string decodeCiphertext(string encodedText, int rows) { int n = encodedText.size(); // Determining the number of columns int cols = n / rows; vector<vector<char>> mat(rows, vector<char>(cols, ' ')); int i = 0, j = 0; int k = 0; string ans = ""; // Filling the matrix using encodedText // Row wise for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { mat[i][j] = encodedText[k++]; } } // Only the upper triangular part of the matrix will // contain characters of the originalText // so, this loop traverses that area for(int k = 0; k < n - (rows * (rows - 1)) / 2; k++) { // i, j are the two pointers for tracking rows and columns ans.push_back(mat[i++][j++]); // If any boundary is hit, then column pointer is subtracted // by row_pointer - 1 // and row pointer is reset to 0 if(i == rows || j == cols) { j -= (i - 1); i = 0; } } // Removing all trailing spaces while(ans.back() == ' ') ans.pop_back(); return ans; } };
var decodeCiphertext = function(encodedText, rows) { const numColumns = encodedText.length / rows; const stringBuilder = []; let nextCol = 1; let row = 0; let col = 0; let index = 0 while (index < encodedText.length) { stringBuilder.push(encodedText[index]); if (row === rows - 1 || col === numColumns - 1) { row = 0; col = nextCol; nextCol++; } else { row++; col++; } index = calcIndex(row, col, numColumns); } while (stringBuilder[stringBuilder.length - 1] === ' ') { stringBuilder.pop(); } return stringBuilder.join(''); }; function calcIndex(row, col, numColumns) { return row * numColumns + col; }
Decode the Slanted Ciphertext
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return "" if not possible. &nbsp; Example 1: Input: s = "aab" Output: "aba" Example 2: Input: s = "aaab" Output: "" &nbsp; Constraints: 1 &lt;= s.length &lt;= 500 s consists of lowercase English letters.
class Solution: def reorganizeString(self, s: str) -> str: c = Counter(s) # for counting the distinct element pq = [] for k,v in c.items(): heapq.heappush(pq,(-v,k)) #multipy by -1 to make max heap ans = '' while pq : c, ch = heapq.heappop(pq) if ans and ans[-1] == ch: if not pq: return '' // if heap is empty we cant make the ans return empty string c2, ch2 = heapq.heappop(pq) ans += ch2 c2 += 1 if c2: heapq.heappush(pq,(c2,ch2)) else: ans += ch c += 1 if c: heapq.heappush(pq,(c,ch)) return ans
class Solution { public String reorganizeString(String s) { StringBuilder ans=new StringBuilder(""); char[] charArray=new char[s.length()]; Map<Character,Integer> hashMap=new HashMap<>(); Queue<CharOccurence> queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence); charArray=s.toCharArray(); for(int i=0;i<charArray.length;i++) { Integer occurence=hashMap.get(charArray[i]); if(occurence==null) hashMap.put(charArray[i],1); else hashMap.put(charArray[i],occurence+1); } queue.addAll(hashMap.entrySet() .stream() .parallel() .map(e->new CharOccurence(e.getKey(),e.getValue())) .collect(Collectors.toList())); while(!queue.isEmpty()) { Queue<CharOccurence> tmpQueue=new LinkedList<>(); int sizeQueue=queue.size(); int stringLength=ans.length(); int startSub=(stringLength-1<0)?0:stringLength-1; int endSub=stringLength; String lastLetter=ans.substring(startSub,endSub); boolean letterAdded=false; for(int i=0;i<sizeQueue;i++) { CharOccurence letter=queue.poll(); if(!lastLetter.contains(String.valueOf(letter.letter))) { letter.occurence--; ans.append(String.valueOf(letter.letter)); if(letter.occurence>0) tmpQueue.add(letter); letterAdded=true; break; } else { tmpQueue.add(letter); } } if(!letterAdded) return ""; queue.addAll(tmpQueue); } return ans.toString(); } class CharOccurence{ public Character letter; public int occurence; public CharOccurence(Character letter, int occurence) { this.letter=letter; this.occurence=occurence; } } }
class Solution { public: string reorganizeString(string s) { // Step1: insert elements to the map so that we will get the frequency unordered_map<char, int> mp; for(auto i: s){ mp[i]++; } //Step2: Create a max heap to store all the elements according to there frequency priority_queue<pair<int, char>> pq; for(auto it: mp){ pq.push({it.second, it.first}); } //Step3: Now take two elements from the heap and do this till the map becomes size 1 // why one : cause we are taking two top elements like pq.top is a then will pop and again pq.top is b and will add to answer string ans = ""; while(mp.size() > 1){ //get the top two elements from heap char ch1 = pq.top().second; ans+=ch1; pq.pop(); char ch2 = pq.top().second; ans+=ch2; pq.pop(); //now reduce the size in the mp // now we have added two char in the ans so reduce the cound in map mp[ch1]--; mp[ch2]--; //Now check if it's size is still greater than 0 then push // if size is greater in map than 0 then we again need to push into the map so that we can make the ans string if(mp[ch1] > 0){ pq.push({mp[ch1],ch1}); } else{ //if the size is 0 then decrese the map means erase the map mp.erase(ch1); } if(mp[ch2] > 0){ pq.push({mp[ch2],ch2}); } else{ mp.erase(ch2); } } //Step4 : Now check wheather any element is present into it // Now we have zero size of the map so check top element size is greater than 1 or not if greater the we cannot split it since it''s only that char if not add to ans if(mp.size() == 1){ if(mp[pq.top().second] > 1){ return ""; } ans += pq.top().second; } //returrn ans return ans; } };
var reorganizeString = function(s) { const charMap = {}; const res = []; // Store the count of each char for (let char of s) { charMap[char] = (charMap[char] || 0) + 1; } // Sort in descending order by count const sortedMap = Object.entries(charMap).sort((a, b) => b[1] - a[1]); // Check if we can distribute the first char by every other position. // We only need to check the first char b/c the chars are ordered by count // so if the first char succeeds, all following chars will succeed if (sortedMap[0][1] > Math.floor((s.length + 1) / 2)) return ''; let position = 0; for (let entry of sortedMap) { const char = entry[0] const count = entry[1]; for (let j = 0; j < count; j++) { // Distribute the current char every other position. The same char // will never be placed next to each other even on the 2nd loop // for placing chars in odd positions res[position] = char; position +=2; // This will only happen once since total number of chars // will be exactly equal to the length of s if (position >= s.length) position = 1; } } return res.join(''); };
Reorganize String
There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'. Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'. Alice and Bob cannot remove pieces from the edge of the line. If a player cannot make a move on their turn, that player loses and the other player wins. Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. &nbsp; Example 1: Input: colors = "AAABABB" Output: true Explanation: AAABABB -&gt; AABABB Alice moves first. She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. Now it's Bob's turn. Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. Thus, Alice wins, so return true. Example 2: Input: colors = "AA" Output: false Explanation: Alice has her turn first. There are only two 'A's and both are on the edge of the line, so she cannot move on her turn. Thus, Bob wins, so return false. Example 3: Input: colors = "ABBBBBBBAAA" Output: false Explanation: ABBBBBBBAAA -&gt; ABBBBBBBAA Alice moves first. Her only option is to remove the second to last 'A' from the right. ABBBBBBBAA -&gt; ABBBBBBAA Next is Bob's turn. He has many options for which 'B' piece to remove. He can pick any. On Alice's second turn, she has no more pieces that she can remove. Thus, Bob wins, so return false. &nbsp; Constraints: 1 &lt;=&nbsp;colors.length &lt;= 105 colors&nbsp;consists of only the letters&nbsp;'A'&nbsp;and&nbsp;'B'
class Solution: def winnerOfGame(self, s: str) -> bool: a = b = 0 for i in range(1,len(s)-1): if s[i-1] == s[i] == s[i+1]: if s[i] == 'A': a += 1 else: b += 1 return a>b
class Solution { public boolean winnerOfGame(String colors) { int cntA=0,cntB=0; for(int i=1;i<colors.length()-1;i++){ if(colors.charAt(i)=='A'&&colors.charAt(i-1)=='A'&&colors.charAt(i+1)=='A')cntA++; if(colors.charAt(i)=='B'&&colors.charAt(i-1)=='B'&&colors.charAt(i+1)=='B')cntB++; } return cntA>cntB; } }
class Solution { public: bool winnerOfGame(string colors) { if (colors.size() < 3) return false; int a = 0, b = 0; for (int i = 0; i < colors.size()-2; i++) { if (colors.substr(i, 3) == "AAA") a++; else if (colors.substr(i, 3) == "BBB") b++; } return a > b; } };
var winnerOfGame = function(colors) { const n = colors.length; const stack = []; let alice = 0; let bob = 0; for (let i = 0; i < n; ++i) { const char = colors[i]; if (stack.length > 1 && stack[stack.length - 1] === char && stack[stack.length - 2] === char) { stack.pop(); if (char === "A") ++alice; else ++bob; } stack.push(char); } return alice > bob ? true : false; };
Remove Colored Pieces if Both Neighbors are the Same Color