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

This dataset contains: problems and solutions in Leetcode, crawled from: https://github.com/AnasImloul/Leetcode-Solutions

The format of data:

  • title: title of the problem
  • algo_input: the description of the problem
  • solution_py: the solution in Python
  • solution_js: the solution in Js
  • solution_java: the solution in Java
  • solution_c: the solution in C
Downloads last month
0
Edit dataset card