algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last ...
from collections import deque class Solution: def minJumps(self, arr: List[int]) -> int: minSteps = 0 queue = deque() queue.append(0) n = len(arr) visited = set() visited.add(0) d = {i:[] for i in arr} for i, val in enumerate(arr): ...
/* Here we are using map and queue map for storing the array elements and where are the other indices of the same element and queue for BFS Initially we start with 0 index So we offer it to the queue Now until the queue is empty we have to do few things for a given position i> check the next index (i+1) ii> check the ...
class Solution { public: int minJumps(vector<int>& arr) { int n = arr.size(); unordered_map<int, vector<int>>mp; for (int i = 0; i < n; i++) mp[arr[i]].push_back(i); queue<int>q; vector<bool>visited(n, false); q.push(0); int steps = 0; wh...
/** * @param {number[]} arr * @return {number} */ var minJumps = function(arr) { if(arr.length <= 1) return 0; const graph = {}; for(let idx = 0; idx < arr.length; idx ++) { const num = arr[idx]; if(graph[num] === undefined) graph[num] = []; graph[num].push(idx); } ...
Jump Game IV
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All ...
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: length = len(quiet) arr = [i for i in range(length)] indegree = [0 for _ in range(length)] graph = collections.defaultdict(list) dq = collections.deque([]) for a, b...
class Solution { ArrayList<ArrayList<Integer>> adj =new ArrayList<>(); int res[]; public int[] loudAndRich(int[][] richer, int[] quiet) { int n=quiet.length; res=new int[n]; Arrays.fill(res,-1); for(int i=0;i<n;i++) adj.add(new ArrayList<Integer>()); ...
class Solution { public: int dfs(int node,vector<int> &answer,vector<int> adjList[],vector<int>& quiet) { if(answer[node]==-1) { answer[node] = node; for(int child:adjList[node]) { int cand = dfs(child,answer,adjList,quiet); if...
var loudAndRich = function(richer, quiet) { const map = new Map(); for (const [rich, poor] of richer) { map.set(poor, (map.get(poor) || new Set()).add(rich)); } const memo = new Map(); const getQuietest = (person) => { if (memo.has(person)) return memo.get(person); ...
Loud and Rich
Given an integer number n, return the difference between the product of its digits and the sum of its digits. &nbsp; Example 1: Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: Input: n = 4421 Output: 21 Explanation: Product...
class Solution: def subtractProductAndSum(self, n: int) -> int: n_to_list = list(str(n)) sum_of_digits = 0 for num in n_to_list: sum_of_digits = sum_of_digits + int(num) product_of_digits = 1 for num in n_to_list: product_of_digits =...
class Solution { public int subtractProductAndSum(int n) { int mul=1,sum=0; while(n!=0){ sum=sum+n%10; mul=mul*(n%10); n=n/10; } return mul-sum; } }
class Solution { public: int subtractProductAndSum(int n) { vector<int> digit; int product=1; int sum=0; while(n>0){ digit.push_back(n%10); n/=10; } for(int i=0;i<digit.size();i++){ product*=digit[i]; sum+=digit[i]; ...
var subtractProductAndSum = function(n) { let product=1,sum=0 n=n.toString().split('') n.forEach((x)=>{ product *=parseInt(x) sum +=parseInt(x) } ) return product-sum };
Subtract the Product and Sum of Digits of an Integer
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] &lt; perm[i + 1], and s[i] == 'D' if perm[i] &gt; perm[i + 1]. Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permu...
class Solution: def diStringMatch(self, s: str) -> List[int]: result = [] min_ = 0 max_ = len(s) for x in s: if x=="I": result.append(min_) min_ += 1 elif x=="D": result.append(max_) max_ -= 1 ...
class Solution { public int[] diStringMatch(String s) { int low = 0; int high = s.length(); int[] ans = new int[s.length() + 1]; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == 'I'){ ans[i] = low++; } else{ ans[i] = high-...
class Solution { public: vector<int> diStringMatch(string s) { int p=0, j=s.size(); vector<int>v; for(int i=0; i<=s.size(); i++) { if(s[i]=='I')v.push_back(p++); else v.push_back(j--); } return v; } };
var diStringMatch = function(s) { let i = 0, d = s.length, arr = []; for(let j = 0; j <= s.length; j += 1) { if(s[j] === 'I') arr.push(i++); else arr.push(d--); } return arr; };
DI String Match
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is a...
class Solution: def partitionArray(self, nums: List[int], k: int) -> int: nums.sort() ans = 1 # To keep track of starting element of each subsequence start = nums[0] for i in range(1, len(nums)): diff = nums[i] - start if diff > k: # If differen...
class Solution { public int partitionArray(int[] nums, int k) { Arrays.sort(nums); int c = 1, prev = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] - nums[prev] <= k) continue; c++; prev = i; } return c; } }
class Solution { public: int partitionArray(vector<int>& nums, int k) { int n(size(nums)), res(0); sort(begin(nums), end(nums)); for (int start=0, next=0; start<n;) { while (next<n and nums[next]-nums[start] <= k) next++; start = next; ...
/** * @param {number[]} nums * @param {number} k * @return {number} */ var partitionArray = function(nums, k) { nums.sort((a,b) =>{ return a-b}) let n = nums.length ,ans=0 for(let i=0 ; i<n; i++){ let ele = nums[i] while(i<n && nums[i]-ele<=k) i++ i-- ans++ } r...
Partition Array Such That Maximum Difference Is K
For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 &lt;= i &lt; j &lt; nums.length and nums[i] &gt; nums[j]. Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it...
class Solution: def kInversePairs(self, n: int, k: int) -> int: # Complexity: # - Time: O(N*K) # - Space: O(K) # Special cases that can be short-circuited right away # - For k=0, there's only one solution, which is having the numbers in sorted order # DP(n, 0) = ...
class Solution { public int kInversePairs(int n, int k) { int MOD = 1000000007; int[][] opt = new int[k + 1][n]; for (int i = 0; i <= k; i++) { for (int j = 0; j < n; j++) { if (i == 0) { opt[i][j] = 1; } else if (j > 0) { ...
class Solution { public: int mod = (int)(1e9 + 7); int dp[1001][1001] = {}; int kInversePairs(int n, int k) { //base case if(k<=0) return k==0; if(dp[n][k]==0){ dp[n][k] = 1; for(int i=0; i<n; i++){ dp[n][k] = (dp[n][...
var kInversePairs = function(n, k) { const dp = new Array(n+1).fill(0).map(el => new Array(k+1).fill(0)) const MOD = Math.pow(10, 9) + 7 for(let i = 0; i < n+1; i++) { dp[i][0] = 1 } for(let i = 1; i <= n; i++) { for(let j = 1; j <= k; j++) { dp[i][j] = (dp[i][j-1] + dp...
K Inverse Pairs Array
You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. &nbsp; Example 1: Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3] Example 2: Input: root =...
# 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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: def search(root): if not root:return ...
class Solution { public TreeNode searchBST(TreeNode root, int val) { if (root == null) return root; if (root.val == val) { return root; } else { return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val); } } }
// Recursive class Solution { public: TreeNode* searchBST(TreeNode* root, int& val) { if(root==NULL) return NULL; if(root->val==val) return root; if(root->val>val) return searchBST(root->left,val); return searchBST(root->right,val); } }; // Iterative class Solution { public: ...
//====== Recursion ====== var searchBST = function(root, val) { if (!root) return null; if (root.val===val) return root; return searchBST(root.left, val) || searchBST(root.right, val) } //====== Iteration ====== var searchBST = function(root, val) { if (!root) return null; let node = root whil...
Search in a Binary Search Tree
You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by followi...
class Solution: def scoreOfStudents(self, s: str, answers: List[int]) -> int: @cache def fn(lo, hi): """Return possible answers of s[lo:hi].""" if lo+1 == hi: return {int(s[lo])} ans = set() for mid in range(lo+1, hi, 2): for...
class Solution { HashMap<String , HashSet<Integer>> cache ; public int scoreOfStudents(String s, int[] answers) { cache = new HashMap(); HashSet<Integer> total_possible_ans = getPossibleAns(s); int correct_ans = getCorrectAns(s); int total_score = 0 ; for(int i=0 ; i...
class Solution { int eval(int a, int b, char op) { if (op == '+') { return a + b; } else { return a * b; } } unordered_map<string_view, unordered_set<int>> mp; unordered_set<int> potential; unordered_set<int>& solve(string_view s) { i...
var scoreOfStudents = function(s, answers) { let correct=s.split('+').reduce((a,c)=>a+c.split('*').reduce((b,d)=>b*d,1),0), n=s.length,dp=[...Array(n)].map(d=>[...Array(n)]) let dfs=(i=0,j=n-1)=>{ if(dp[i][j]!==undefined) return dp[i][j] if(i===j) return dp[i][j]=...
The Score of Students Solving Math Expression
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix: 0 means the cell cannot be walked through. 1 represents an empty cell that can be walked through. A number greater than 1 represents a tree in a cell that can be walked through, and th...
from collections import deque class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: a = [] n = len(forest) m = len(forest[0]) for i in range(n): for j in range(m): if forest[i][j] > 1: a.append(forest[i][j]) a.s...
class Solution { //approach: 1st store all the positions in the min heap acc. to their height //now start removing the elements from the heap and calculate their dis using bfs // if at any point we cann't reach at the next position return -1; // else keep on adding the distances and return; public i...
class Solution { public: #define vi vector<int> #define vvi vector<vi> vvi forests; vvi moves; int R; int C; bool isValid(int x,int y){ return x>=0&&x<R&&y>=0&&y<C; } int getShortestDistance(int sx,int sy,int ex,int ey){ vvi vis = vvi...
var cutOffTree = function(forest) { const trees = forest.flat().filter(x => x && x !== 1).sort((a, b) => b - a); let currPos = [0, 0], totalDist = 0; while(trees.length) { const grid = [...forest.map(row => [...row])]; const res = getDist(currPos, trees.pop(), grid); if(res == null)...
Cut Off Trees for Golf Event
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. For example: houses = [1,2,2...
class Solution: def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: @cache def dp(i, p, h): if (h > target) or (i == m and h != target): return inf if i == m: return 0 if houses[i] != 0: ...
class Solution { public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp) { if(idx==houses.length || neigh>target) { if(neigh==target) return 0; return Integer.MAX_VALUE; } if(dp[idx][prevC...
class Solution { int dp[101][22][101]; vector<int> h;//m vector<vector<int>> c;//n int mm; int nn; int t; int dfs(int idx, int prev, int curt){ if(curt<1) return INT_MAX; if(idx==mm) return (curt==1)?0:INT_MAX; if(dp[idx][prev][curt]!=-1) r...
var minCost = function(houses, cost, m, n, target) { let map = new Map(); function dfs(idx = 0, prevColor = -1, neighborhoods = 0) { if (idx === m) return neighborhoods === target ? 0 : Infinity; let key = `${idx}-${prevColor}-${neighborhoods}`; if (map.has(key)) return map.get(key); ...
Paint House III
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). &nbsp; Example 1: Input: s = "1 + 1" Output: 2 Example ...
```class Solution: def calculate(self, s: str) -> int: curr,output,sign,stack = 0,0,1,[] for ch in s: if ch.isdigit(): curr = curr * 10 + int(ch) elif ch == '+': output += sign * curr sign = 1 curr = 0 ...
class Solution { int idx; // this index traverse the string in one pass, between different level of recursion public int calculate(String s) { idx = 0; // Initialization should be here return helper(s); } private int helper(String s) { int res = 0, num = 0, preSign = 1, n = ...
class Solution { public: int calculate(string s) { stack<pair<int,int>> st; // pair(prev_calc_value , sign before next bracket () ) long long int sum = 0; int sign = +1; for(int i = 0 ; i < s.size() ; ++i) { char ch = s[i]; if(isdig...
var calculate = function(s) { const numStack = [[]]; const opStack = []; const isNumber = char => !isNaN(char); function calculate(a, b, op){ if(op === '+') return a + b; if(op === '-') return a - b; } let number = ''; for (let i = 0; i < s.length; i++) { const char = s[i]; if (char === ' ') continu...
Basic Calculator
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth qu...
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = dict() for (n, d), v in zip(equations, values): if n not in graph: graph[n] = [] if d not in graph: ...
class Solution { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { int len = equations.size(); Map<String, Integer> varMap = new HashMap<>(); int varCnt = 0; for (int i = 0; i < len; i++) { if (!varMap.containsKey(eq...
class Solution { public: vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { map<string, vector<pair<string, double>>> graph; map<string, double> dist; map<string, bool> visited; for(int i=0;i<equations.size();i++){ ...
var calcEquation = function(equations, values, queries) { const res = [] for(let i = 0; i < queries.length; i++) { const currQuery = queries[i] const [currStart, currDestination] = currQuery const adj = {} const additionalEdges = [] const a...
Evaluate Division
Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: arr = [1,3,5] Output: 4 Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,8,5]. Odd sums are [1,9,3,5] ...
class Solution: def numOfSubarrays(self, arr: List[int]) -> int: ce, co = 0, 0 s = 0 for x in arr: if x % 2 == 0: ce += 1 else: old_co = co co = ce + 1 ce = old_co s += co ...
//odd-even=odd //even-odd=odd class Solution { public int numOfSubarrays(int[] arr) { long ans=0; int even=0; int odd=0; long sum=0; for(int i=0;i<arr.length;i++){ sum+=arr[i]; if(sum%2==0){ ans+=odd; ...
class Solution { public: int mod = 1e9 + 7; int solve(int ind, int n, vector<int> &arr, int req, vector<vector<int>> &dp) { if(ind == n) return 0; if(dp[ind][req] != -1) return dp[ind][req]; if(req == 1) { if(arr[ind] % 2 == 0) { return dp[ind][req] =...
var numOfSubarrays = function(arr) { let mod=1e9+7,sum=0,odds=0,evens=0 //Notice that I do not need to keep track of the prefixSums, I just need the total count of odd and even PrefixSums for(let i=0;i<arr.length;i++){ sum+=arr[i] odds+=Number(sum%2==1) evens+=Number(sum%2==0) } ...
Number of Sub-arrays With Odd Sum
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. &nbsp; Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary corresponds to the decimal value 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary...
class Solution: def concatenatedBinary(self, n: int) -> int: modulo = 10 ** 9 + 7 shift = 0 # tracking power of 2 res = 0 for i in range(1, n+1): if i & (i - 1) == 0: # see if num reaches a greater power of 2 shift += 1 res = ((res << ...
class Solution { public int concatenatedBinary(int n) { long res = 0; for (int i = 1; i <= n; i++) { res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007; } return (int) res; } }
class Solution { public: int numberOfBits(int n) { return log2(n) + 1; } int concatenatedBinary(int n) { long ans = 0, MOD = 1e9 + 7; for (int i = 1; i <= n; ++i) { int len = numberOfBits(i); ans = ((ans << len) % MOD + i) % MOD; } ...
var concatenatedBinary = function(n) { let num = 0; for(let i = 1; i <= n; i++) { //OR num *= (1 << i.toString(2).length) num *= (2 ** i.toString(2).length) num += i; num %= (10 ** 9 + 7) } return num; };
Concatenation of Consecutive Binary Numbers
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. &nbsp; Example 1: Input: s = "()" Output: true Exa...
class Solution: def isValid(self, string: str) -> bool: while True: if '()' in string: string = string.replace('()', '') elif '{}' in string: string = string.replace('{}', '') elif '[]' in string: string = string.replace('[...
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); // create an empty stack for (char c : s.toCharArray()) { // loop through each character in the string if (c == '(') // if the character is an opening parenthesis stack.pu...
class Solution { public: // Ref: balanced parenthesis video from LUV bhaiya YT channel unordered_map<char,int>symbols={{'[',-1},{'{',-2},{'(',-3},{']',1},{'}',2},{')',3}}; stack<char>st; bool isValid(string s) { for(auto &i:s){ if(symbols[i]<0){ st.push(i); } ...
var isValid = function(s) { const stack = []; for (let i = 0 ; i < s.length ; i++) { let c = s.charAt(i); switch(c) { case '(': stack.push(')'); break; case '[': stack.push(']'); break; case '{': stack.push('}'); ...
Valid Parentheses
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. &nbsp; Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -104 &lt;= nums[i] &lt;= 1...
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: return [i[0] for i in Counter(nums).most_common(k)]
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.merge(num, 1, Integer::sum); } return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .map(Map.Entry::getKey) ...
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> map; for(int num : nums){ map[num]++; } vector<int> res; // pair<first, second>: first is frequency, second is number priority_queue<pair<int,int...
var topKFrequent = function(nums, k) { let store = {}; for(let i=0;i<nums.length;i++){ store[nums[i]] = store[nums[i]]+1||1 } //returns an array of keys in sorted order let keyArr = Object.keys(store).sort((a,b)=>store[a]-store[b]) let arrLength = keyArr.length; let slicedArr = keyArr....
Top K Frequent Elements
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network ...
class Solution(object): def __init__(self): self.parents = [] self.count = [] def makeConnected(self, n, connections): """ :type n: int :type connections: List[List[int]] :rtype: int """ if len(connections) < n-1: return -1 sel...
class Solution { public int makeConnected(int n, int[][] connections) { int m = connections.length; if(m < n - 1) return -1; UnionFind uf = new UnionFind(n); for(int[] connection: connections){ uf.union(connection[0], connection[1]); } return uf.g...
class Solution { public: // Union Find Approach vector<int> root; int find(int node){ if(root[node] != node){ return find(root[node]); } return node; } int makeConnected(int n, vector<vector<int>>& connections) { int m = connections.size(); if(m < n-1){ return -1; } for(int i=0 ; i<n ; i...
/** * @param {number} n * @param {number[][]} connections * @return {number} */ class UnionFind { constructor(n) { this.root = new Array(n).fill().map((_, index)=>index); this.components = n; } find(x) { if(x == this.root[x]) return x; return this.root[x] = this.find(this...
Number of Operations to Make Network Connected
Given two strings&nbsp;s&nbsp;and&nbsp;t, your goal is to convert&nbsp;s&nbsp;into&nbsp;t&nbsp;in&nbsp;k&nbsp;moves or less. During the&nbsp;ith&nbsp;(1 &lt;= i &lt;= k)&nbsp;move you can: Choose any index&nbsp;j&nbsp;(1-indexed) from&nbsp;s, such that&nbsp;1 &lt;= j &lt;= s.length&nbsp;and j&nbsp;has not been chos...
class Solution: def canConvertString(self, s: str, t: str, k: int) -> bool: if len(s) != len(t): return False cycles, extra = divmod(k, 26) shifts = [cycles + (shift <= extra) for shift in range(26)] for cs, ct in zip(s, t): shift = (ord(ct) - ord(cs)) % 26 ...
class Solution { public boolean canConvertString(String s, String t, int k) { //if strings lengths not equal return false if(s.length()!=t.length())return false; //array to count number of times a difference can repeat int b[]=new int[26]; int h=k/26; int h1=k%26; ...
class Solution { public: bool canConvertString(string s, string t, int k) { int m = s.length(), n = t.length(), count = 0; if (m != n) return false; unordered_map<int, int> mp; for (int i = 0; i < m; i++) { if (t[i] == s[i]) continue; int diff = t[i] - s[i] < ...
/** * @param {string} s * @param {string} t * @param {number} k * @return {boolean} */ var canConvertString = function(s, t, k) { let res = true; if(s.length === t.length){ let tmp = []; let countMap = new Map(); for(let i=0; i<s.length; i++){ let n1 = s[i].charCodeAt()...
Can Convert String in K Moves
You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want...
class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: n = len(s) nums = [] sums = 0 for i in shifts[::-1]: sums = (sums+i)%26 nums.append(sums) nums = nums[::-1] res = '' for i, ch in enumerate(s): ...
class Solution { public String shiftingLetters(String s, int[] shifts) { char[] arr = s.toCharArray(); int[] arr1 = new int[shifts.length]; arr1[arr1.length-1] = (shifts[shifts.length-1])%26; for(int i =shifts.length -2 ;i>=0 ;i--){ arr1[i] = (shifts[i] + arr1[i+1])%26; ...
class Solution { void shift(string& s, int times, int amt) { const int clampL = 97; const int clampR = 123; for (int i = 0; i <= times; i++) { int op = (s[i] + amt) % clampR; if (op < clampL) op += clampL; ...
// 848. Shifting Letters var shiftingLetters = function(s, shifts) { let res = '', i = shifts.length; shifts.push(0); while (--i >= 0) { shifts[i] += shifts[i+1]; res = String.fromCharCode((s.charCodeAt(i) - 97 + shifts[i]) % 26 + 97) + res; } return res; };
Shifting Letters
Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer a...
class RangeFreqQuery: def __init__(self, arr: List[int]): self.l = [[] for _ in range(10001)] for i, v in enumerate(arr): self.l[v].append(i) def query(self, left: int, right: int, v: int) -> int: return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)
class RangeFreqQuery { //Use map's key to store arr's value, map's value to keep <value's location, cummulative arr's value count> HashMap<Integer, TreeMap<Integer, Integer>> map; public RangeFreqQuery(int[] arr) { //O(nlog(n)) map = new HashMap<>(); for(int i = 0; i < arr.length; i+...
class RangeFreqQuery { private: int size; unordered_map< int, vector<int> > mp; public: RangeFreqQuery(vector<int>& arr) { size=arr.size(); for (int i=0; i<size;i++){ mp[arr[i]].push_back(i); } } int query(int left, int right, int value) { int first = lowe...
var RangeFreqQuery = function(arr) { this.array = arr; this.subRangeSize = Math.sqrt(this.array.length) >> 0; this.subRangeFreqs = []; let freq = {}; for(let i = 0; i < arr.length; i++) { const num = arr[i]; if(i >= this.subRangeSize && i % this.subRangeSize === 0) { ...
Range Frequency Queries
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively ...
class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: def valid(r,c,matrix): return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0]) dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))] dp[0][0] = 1 ^ obstacleGrid[0]...
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] path = new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ //if there is an obstacle at the current block then you cannot get th...
class Solution { public: int dp[101][101]; int paths(int i,int j,int &m, int &n,vector<vector<int>> &grid){ if(i>=m || j>=n) return 0; if(grid[i][j] == 1) return 0; if(i== m-1 && j== n-1) return 1; if(dp[i][j] != -1) return dp[i][j]; in...
var uniquePathsWithObstacles = function(grid) { let m=grid.length, n=grid[0].length; const dp = [...Array(m+1)].map((e) => Array(n+1).fill(0)); dp[0][1]=1; for(let i=1;i<m+1;i++){ for(let j=1;j<n+1;j++){ dp[i][j]=grid[i-1][j-1]==1 ? 0:dp[i][j-1]+dp[i-1][j]; ...
Unique Paths II
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. &nbsp; Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", maga...
from collections import Counter class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: ransomNote_count = dict(Counter(ransomNote)) magazine_count = dict(Counter(magazine)) for key , value in ransomNote_count.items(): if ke...
class Solution { public boolean canConstruct(String ransomNote, String magazine) { char[] rs = ransomNote.toCharArray(); char[] ms = magazine.toCharArray(); HashMap<Character, Integer> rm = new HashMap<>(); HashMap<Character, Integer> mz = new HashMap<>(); f...
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int cnt[26] = {0}; for(char x: magazine) cnt[x-'a']++; for(char x: ransomNote) { if(cnt[x-'a'] == 0) return false; cnt[x-'a']--; } ...
var canConstruct = function(ransomNote, magazine) { map = {}; for(let i of magazine){ map[i] = (map[i] || 0) + 1; } for(let i of ransomNote){ if(!map[i]){ return false } map[i]--; } return true };
Ransom Note
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise....
class Solution: def makeEqual(self, words: List[str]) -> bool: map_ = {} for word in words: for i in word: if i not in map_: map_[i] = 1 else: map_[i] += 1 n = len(words) for k,v in map_.items(): ...
class Solution { public boolean makeEqual(String[] words) { HashMap<Character, Integer> map = new HashMap<>(); for(String str : words){ for(int i=0; i<str.length(); i++){ char ch = str.charAt(i); map.put(ch, ...
class Solution { public: bool makeEqual(vector<string>& words) { int mp[26] = {0}; for(auto &word: words){ for(auto &c: word){ mp[c - 'a']++; } } for(int i = 0;i<26;i++){ if(mp[i] % words.size() != 0) return false; ...
/** * @param {string[]} words * @return {boolean} */ var makeEqual = function(words) { let length = words.length let map = {} for( let word of words ) { for( let ch of word ) { map[ch] = ( map[ch] || 0 ) + 1 } } for( let key of Object.keys(map)) { if( map[ke...
Redistribute Characters to Make All Strings Equal
You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s b...
''' w: BFS h: for each possible number (node), we have two possible operations (add, rotate) it seems to be a 2^100 possible number, however, note: 1) add a to number of odd index, we will get to the same number after 10 rounds of add 2) s has even length, if b is odd, we can get the same number after n rou...
class Solution { private String result; public String findLexSmallestString(String s, int a, int b) { result = "z"; HashSet<String> set = new HashSet<>(); dfs(s, a, b, set); return result; } private void dfs(String s, int a, int b, HashSet<String> set) { if(set.co...
class Solution { public: void dfs(string &s, string &small, int a, int b, unordered_map<string, string> &memo) { if (memo.count(s)) return; string res = s, str = res; memo[s] = res; rotate(str.begin(), str.begin() + b, str.end()); // rotate current string dfs(str, small, a, b...
var findLexSmallestString = function(s, a, b) { const n = s.length; const visited = new Set(); const queue = []; visited.add(s); queue.push(s); let minNum = s; while (queue.length > 0) { const currNum = queue.shift(); if (currNum < minNum) minNum = currNum; const...
Lexicographically Smallest String After Applying Operations
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 &lt;= i &lt; nums1.length, find the index j such that nums1[i] == nums2[j] ...
class Solution: def nextGreaterElement(self, nums1, nums2): dic, stack = {}, [] for num in nums2[::-1]: while stack and num > stack[-1]: stack.pop() if stack: dic[num] = stack[-1] stack.append(num) retu...
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>(); Stack<Integer> stack = new Stack<>(); int[] ans = new int[nums1.length]; for(int i = 0; i < nums2.length; i++){ while(!stack.isEmpty() && nums2[i] >...
class Solution { public: vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) { vector<int>vc; int len1=nums1.size(); int len2=nums2.size(); unordered_map<int,int>ump; int e,f; for(e=0;e<len2;e++) { for(f=e+1;f<len2;f++) ...
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var nextGreaterElement = function(nums1, nums2) { // [Value, Index] of all numbers in nums2 const indexMap = new Map() for(let i = 0; i < nums2.length; i++){ indexMap.set(nums2[i], i) } // Stores the next gr...
Next Greater Element I
Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. &nbsp; Example 1: Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4] Example 2: Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8] &nbsp; Constraints: The numb...
# 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: l1,l2=[],...
class Solution { public List<Integer> getAllElements(TreeNode root1, TreeNode root2) { Stack<TreeNode> st1 = new Stack<>(); Stack<TreeNode> st2 = new Stack<>(); List<Integer> res = new ArrayList<>(); while(root1 != null || root2 != null || !st1.empty() || !st2.empty...
class Solution { public: vector<int> v; void Temp(TreeNode* root) { if(root!=NULL){ Temp(root->left); v.push_back(root->val); Temp(root->right); } } vector<int> getAllElements(TreeNode* root1, TreeNode* root2) { Temp(root1); Temp(root2); ...
var getAllElements = function(root1, root2) { const ans = []; const traverse = (r) => { if(!r) return; traverse(r.left); ans.push(r.val); traverse(r.right); } traverse(root1); traverse(root2); return ans.sort((a, b) => a - b); };
All Elements in Two Binary Search Trees
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this convers...
class Solution: def convert(self, s: str, numRows: int) -> str: # safety check to not process single row if numRows == 1: return s # safety check to not process strings shorter/equal than numRows if len(s) <= numRows: return s # safety check to not ...
class Solution { public String convert(String s, int numRows) { if (numRows==1)return s; StringBuilder builder = new StringBuilder(); for (int i=1;i<=numRows;i++){ int ind = i-1; boolean up = true; while (ind < s.length()){ builder.append(s...
class Solution { public: string convert(string s, int numRows) { vector<vector<char>> v(numRows); int j=0,t=1; if(numRows ==1) return s; for(int i=0;i<s.size();i++) { v[j].push_back((char)s[i]); if(j==numRows-1 ) t=0; ...
var convert = function(s, numRows) { let result = []; let row = 0; let goingUp = false; for (let i = 0; i < s.length; i++) { result[row] = (result[row] || '') + s[i]; // append letter to active row if (goingUp) { row--; if (row === 0) goingUp = false; // reverse direction if goingUp and reac...
Zigzag Conversion
You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible ...
class Solution: def minAbsDifference(self, nums: List[int], goal: int) -> int: # When goal 0 we can just choose no elements if goal == 0: return 0 n = len(nums) mid = n // 2 # Split the list in 2 parts and then find all possible subset sums # T = O(2^n/2) to build...
class Solution { int[] arr; public int minAbsDifference(int[] nums, int goal) { arr = nums; int n = nums.length; List<Integer> first = new ArrayList<>(); List<Integer> second = new ArrayList<>(); generate(0,n/2,0, first); //generate all possible...
class Solution { public: void find(vector<int>&v, int i, int e, int sum, vector<int>&sumv){ if(i==e){ sumv.push_back(sum); return; } find(v,i+1,e,sum+v[i],sumv); find(v,i+1,e,sum,sumv); } int minAbsDifference(vector<int>& nums, int goal) { int...
var minAbsDifference = function(nums, goal) { let mid = Math.floor(nums.length / 2); let part1 = nums.slice(0, mid), part2 = nums.slice(mid); function findSubsetSums(arr, set, idx = 0, sum = 0) { if (idx === arr.length) return set.add(sum); findSubsetSums(arr, set, idx + 1, sum); fi...
Closest Subsequence Sum
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. &nbsp; Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation:...
class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ b = set(chars) anwser = 0 for i in words: a = set(i) if a.issubset(b): test = [o for o ...
class Solution { public int countCharacters(String[] words, String chars) { int[] freq = new int[26]; for (int i = 0; i < chars.length(); i++) { // char - char is a kind of clever way to get the position of // the character in the alphabet. 'a' - 'a' would give you 0. ...
class Solution { public: int countCharacters(vector<string>& words, string chars) { vector<int> dp(26,0); vector<int> dp2(26,0); for(int i=0;i<chars.size();i++){ dp[chars[i]-'a']++; } dp2 = dp; bool flg = false; int cnt=0; for(int i=0;i<wor...
var countCharacters = function(words, chars) { let arr = []; loop1: for(word of words){ let characters = chars; loop2: for( char of word ){ if(characters.indexOf(char) === -1){ continue loop1; } characters = characters.replace(char,''); ...
Find Words That Can Be Formed by Characters
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. &nbsp; Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 &nbsp; Constraints: 1 ...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: ans=0 prefsum=0 d={0:1} for num in nums: prefsum = prefsum + num if prefsum-k in d: ans = ans + d[prefsum-k] if prefsum not in d: d[prefsum] = 1 else: d[prefsum] = d[prefsum]+1 return ans
/* */ class Solution { public int subarraySum(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); map.put(0,1); int count = 0; int sum = 0; for(int i=0; i<nums.length; i++){ sum += nums[i]; if(map.containsKey(sum - k)){ ...
/********************************* Solution Using HashMap / Prefix ********************/ class Solution { public: int subarraySum(vector<int>& nums, int k) { unordered_map<int, int> prefixSum {{0, 1}}; int sum = 0; int numOfSubArr = 0; int size = nums.size(); ...
var subarraySum = function(nums, k) { const obj = {}; let res = 0; let sum = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (sum == k) res++; if (obj[sum - k]) res += obj[sum - k]; obj[sum] ? obj[sum] += 1 : obj[sum] ...
Subarray Sum Equals K
You have k lists of sorted integers in non-decreasing&nbsp;order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a &lt; d - c or a &lt; c if b - a == d - c. &nbsp; Example 1: Input: nums = [[4,10,15,24,26],[0,9,12,20]...
from queue import PriorityQueue class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: q = PriorityQueue() maxi = -10**7 mini = 10**7 for i in range(len(nums)): maxi = max(maxi,nums[i][0]) mini = min(mini,nums[i][0]) q.put((nums[i][0],i,0)) s, e = mini, maxi wh...
class Solution { class Pair implements Comparable<Pair> { int val; int li; int di; public Pair(int val, int li, int di) { this.val = val; this.li = li; this.di = di; } public int compareTo(Pair other) { ...
#include <vector> #include <queue> #include <limits> using namespace std; struct Item { int val; int r; int c; Item(int val, int r, int c): val(val), r(r), c(c) { } }; struct Comp { bool operator() (const Item& it1, const Item& it2) { return it2.val < it1.val; } }; class Sol...
var smallestRange = function(nums) { let minHeap = new MinPriorityQueue({ compare: (a,b) => a[0] - b[0] }); let start = 0, end = Infinity; let maxSoFar = -Infinity; for (let num of nums) { minHeap.enqueue([num[0], 0, num]); maxSoFar = Math.max(maxSoFar, num[0]); } ...
Smallest Range Covering Elements from K Lists
Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: s = "0110111" Output: 9 Explanation: There are 9 substring in total with only 1's characters. "1" -&gt; 5 times. "11" -&gt; 3 times. "111" -&gt; 1 tim...
class Solution(object): def numSub(self, s): res, currsum = 0,0 for digit in s: if digit == '0': currsum = 0 else: currsum += 1 res+=currsum return res % (10**9+7)
class Solution { public int numSub(String s) { char[] ch = s.toCharArray(); long count =0; long result =0; for(int i=0; i<ch.length; i++){ if(ch[i] == '1'){ count++; result += count; } else{ count = 0...
class Solution { /* To calculate the substring the formula is (n*n+1)/2 so just find the range and calculate the substrings. */ int mod=1e9+7; long calculateNumbeOfSubstrings(string &s,int &l,int &r){ long range=r-l; long ans=range*(range+1)/2; return ans; } public: int n...
var numSub = function(s) { const mod = Math.pow(10, 9)+7; let r = 0, tot = 0; while (r<s.length) { if (s[r]==='1') { let tmp = r; while (tmp < s.length && s[tmp] === '1') { tot += tmp - r + 1; tot%=mod; tmp++; }...
Number of Substrings With Only 1s
Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. &nbsp; Example 1: Input: s = "hello" Output: "holle" Example 2: Input: s = "leetcode" Output: "leotcede" &nbsp; Constraints: 1 &lt;= s.length &lt;= 3 * 105 s c...
class Solution: def reverseVowels(self, s: str) -> str: s=list(s) vow=[] for i,val in enumerate(s): if val in ('a','e','i','o','u','A','E','I','O','U'): vow.append(val) s[i]='_' vow=vow[::-1] c=0 print(vow) ...
class Solution { public String reverseVowels(String s) { Set<Character> set = new HashSet<>(); set.add('a'); set.add('e'); set.add('i'); set.add('o'); set.add('u'); set.add('A'); set.add('E'); set.add('I'); set.add('O'); set.add...
class Solution { public: bool isVowel(char s) { if(s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u' or s == 'A' or s == 'E' or s == 'I' or s == 'O' or s == 'U') return true; return false; } string reverseVowels(string s) { if(s.size() == 0) return "";...
var reverseVowels = function(s) { const VOWELS = { 'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1 }; const arr = s.split(''); let i = 0, j = arr.length - 1; while (i < j) { if (VOWELS[arr[i]] && VOWELS[arr[j]]) { [arr[i], arr[j]] = [arr[j], arr[i]]; ...
Reverse Vowels of a String
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. &nbsp; Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a" Out...
class Solution: def isPallindrom(self, s: str, l, r) -> bool: st = s[l: r+1] rev = st[::-1] return st == rev def minCut(self, s: str) -> int: N = len(s) if not s: return 0 if self.isPallindrom(s, 0, N-1): return 0 dp = [sys.maxsize] * (N+1) dp...
class Solution { int dp[]; public boolean pali(int i,int j,String s){ // int j=s.length()-1,i=0; while(i<=j){ if(s.charAt(i)!=s.charAt(j))return false; i++;j--; } return true; } public int cut(String s,int i,int n,int dp[]){ ...
class Solution { public: // function to precompute if every substring of s is a palindrome or not vector<vector<bool>> isPalindrome(string& s){ int n = s.size(); vector<vector<bool>> dp(n, vector<bool>(n, false)); for(int i=0; i<n; i++){ dp[i][i] = true; } ...
var minCut = function(s) { function isPal(l, r) { while (l < r) { if (s[l] === s[r]) l++, r--; else return false; } return true; } let map = new Map(); function dfs(idx = 0) { if (idx === s.length) return 0; if (map.has(idx)) return map.get(idx); ...
Palindrome Partitioning II
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123&nbsp; 34 8&nbsp; 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "...
class Solution: def numDifferentIntegers(self, word: str) -> int: word = re.findall('(\d+)', word) numbers = [int(i) for i in word] return len(set(numbers))
class Solution { public int numDifferentIntegers(String word) { String[] arr = word.replaceAll("[a-zA-Z]", " ").split("\\s+"); Set<String> set = new HashSet<String>(); for (String str : arr) { if (!str.isEmpty()) set.add(String.valueOf(str.replaceAll("^0*","")));...
class Solution { public: int numDifferentIntegers(string word) { unordered_map<string, int> hmap; for (int i = 0; i < word.size(); i++) { if (isdigit(word[i])) { string str; while (word[i] == '0') i++; while (isdigit(wor...
const CC0 = '0'.charCodeAt(0); var numDifferentIntegers = function(word) { const numStrSet = new Set(); // get numbers as strings const numStrs = word.split(/[^0-9]+/); // drop leading zeros for (const numStr of numStrs) { if (numStr.length > 0) { let i = 0; ...
Number of Different Integers in a String
Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: MyHashMap() initializes the object with an empty map. void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. int get(int key) r...
class MyHashMap: def __init__(self): self.data = [None] * 1000001 def put(self, key: int, val: int) -> None: self.data[key] = val def get(self, key: int) -> int: val = self.data[key] return val if val != None else -1 def remove(self, key: int) -> None: self.data[k...
class MyHashMap { /** Initialize your data structure here. */ LinkedList<Entry>[] map; public static int SIZE = 769; public MyHashMap() { map = new LinkedList[SIZE]; } /** value will always be non-negative. */ public void put(int key, int value) { int bucket = key % SIZE; if(map[bucket] == null) { map...
class MyHashMap { vector<vector<pair<int, int>>> map; const int size = 10000; public: /** Initialize your data structure here. */ MyHashMap() { map.resize(size); } /** value will always be non-negative. */ void put(int key, int value) { int index = key % size; vector<pair<int, int>> &row = map[index...
var MyHashMap = function() { this.hashMap = []; }; /** * @param {number} key * @param {number} value * @return {void} */ MyHashMap.prototype.put = function(key, value) { this.hashMap[key] = [key, value]; }; /** * @param {number} key * @return {number} */ MyHashMap.prototype.get = function(key) { re...
Design HashMap
Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: arr = [1,4,2,5,3] Output: 58 Explanation: The odd-length subarrays of arr and their sums are: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4...
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: n = len(arr) ans = 0 for i in range(n): total = (i+1) * (n-1-i+1) ans = ans + (total//2 + total%2) * arr[i] return ans
class Solution { public int sumOddLengthSubarrays(int[] arr) { // Using two loops in this question... int sum = 0; for(int i=0 ; i<arr.length ; i++){ int prevSum = 0; for(int j=i ; j<arr.length ; j++){ prevSum+=arr[j]; if((j-i+...
class Solution { public: int sumOddLengthSubarrays(vector<int>& arr) { int sum=0; int sum1=0; for(int i=0;i<arr.size();i++) { int count=0; sum+=arr[i]; for(int j=i;j<arr.size();j++) { sum1+=arr[j]; count+...
/* Suppose N is the length of given array. Number of subarrays including element arr[i] is i * (N-i) + (N-i) because there are N-i subarrays with arr[i] as first element and i * (N-i) subarrays with arr[i] as a not-first element. arr[i] appears in (N-i) subarrays for each preceding element and therefore we have i*(N-i...
Sum of All Odd Length Subarrays
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array knowled...
class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: knowledge = dict(knowledge) answer, start = [], None for i, char in enumerate(s): if char == '(': start = i + 1 elif char == ')': answer.append(knowledge.ge...
class Solution { public String evaluate(String s, List<List<String>> knowledge) { Map<String, String> map = new HashMap<>(); for(List<String> ele : knowledge) { map.put(ele.get(0), ele.get(1)); } StringBuilder sb = new StringBuilder(); int b_start = -1; fo...
class Solution { public: string evaluate(string s, vector<vector<string>>& knowledge) { string ans; // resultant string int n = s.size(); if(n < 2) return s; // because () will come in pair so, size should be more than 2 int sz = knowledge.size(); for(int i=0; i<sz; ++i){ ...
var evaluate = function(s, knowledge) { // key => value hash map can be directly constructed using the Map constructor const map = new Map(knowledge); // since bracket pairs can't be nested we can use a RegExp to capture keys and replace using a map constructed in the line above return s.replace(/\(([a-z...
Evaluate the Bracket Pairs of a String
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After th...
class Solution: def maxRunTime(self, n: int, batteries: List[int]) -> int: batteries.sort() total=sum(batteries) while batteries[-1]>total//n: n-=1 total-=batteries.pop() return total//n
class Solution { private boolean canFit(int n, long k, int[] batteries) { long currBatSum = 0; long target = n * k; for (int bat : batteries) { if (bat < k) { currBatSum += bat; } else { currBatSum += k; } if ...
class Solution { public: bool canFit(int n,long timeSpan,vector<int>batteries) { long currBatSum=0; long targetBatSum=n*timeSpan; for(auto it:batteries) { if(it<timeSpan) currBatSum+=it; else currBatSum+=timeSpan; if(currBatSum>=targetBatSum) ...
var maxRunTime = function(n, batteries) { let total = batteries.reduce((acc,x)=>acc+x,0) let batts = batteries.sort((a,b)=>b-a) let i = 0 while(1){ let average_truncated = parseInt(total / n) let cur = batts[i] if(cur > average_truncated){ total -= cur // remove all o...
Maximum Running Time of N Computers
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 &lt;= i &lt;= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, return the number of the beautifu...
class Solution: def countArrangement(self, n: int) -> int: self.count = 0 self.backtrack(n, 1, []) return self.count def backtrack(self, N, idx, temp): if len(temp) == N: self.count += 1 return for i in range(1, N+1): ...
class Solution { int N; Integer[][] memo; public int countArrangement(int n) { this.N = n; memo = new Integer[n+1][1<<N]; return permute(1, 0); } private int permute(int index, int mask) { if (mask == (1<<N)-1) return 1; if (memo[index][mask] ...
class Solution { public: int ans = 0; bool isBeautiful(vector<int> &v) { int i = v.size() - 1; if (v[i] % (i + 1) == 0 || (i + 1) % v[i] == 0) return true; return false; } void solve(int n, vector<int> &p, vector<bool> &seen) { if (p.size() == n) { ans++; ...
var countArrangement = function(n) { let result = 0; const visited = Array(n + 1).fill(false); const dfs = (next = n) => { if (next === 0) { result += 1; return; } for (let index = 1; index <= n; index++) { if (visited[index] || index % next && ne...
Beautiful Arrangement
You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the follo...
class Solution: def judgePoint24(self, cards: List[int]) -> bool: return self.allComputeWays(cards, 4, 24) def allComputeWays(self, nums, l, target): if l == 1: if abs(nums[0] - target) <= 1e-6: return True return False for first in range(...
// 0 ms. 100% class Solution { private static final double EPS = 1e-6; private boolean backtrack(double[] A, int n) { if(n == 1) return Math.abs(A[0] - 24) < EPS; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { double a = A[i], b = A[j]; ...
class Solution { public: double cor=0.001; void dfs(vector<double> &cards,bool &res){ if(res==true) return; if(cards.size()==1){ if(abs(cards[0]-24)<cor) res=true; return; } for(int i=0;i<cards.size();i++){ for(int j=0;j<i;j++){ ...
/** * @param {number[]} cards * @return {boolean} 1487 7-1 8-4 */ var judgePoint24 = function(cards) { let minV = 0.00000001; let numL = []; cards.forEach(card=>numL.push(card)); function judge(nums){ if(nums.length === 1) return Math.abs(nums[0]-24)<=minV; else{ for(let i...
24 Game
A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Given an m x n integer grid, return the size (i.e., the side length k) of...
class Solution: def largestMagicSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # dimensions rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row cols = [[0]*n for _ in range(m+1)] # prefix sum along column for i in range(m): fo...
class Solution { public int largestMagicSquare(int[][] grid) { int m = grid.length; int n = grid[0].length; // every row prefix sum int[][] rowPrefix = new int[m][n]; for (int i = 0; i < m; i++) { rowPrefix[i][0] = grid[i][0]; for (int j = 1; j < n; j++) { rowPrefix[i][j] = row...
class Solution { public: bool isValid(int r1, int r2, int c1, int c2, vector<vector<int>>& grid, vector<vector<int>>& rg, vector<vector<int>>& cg,int checkSum){ //Checking all row sums between top and bottom row for(int i = r1 + 1; i<r2; i++){ int sum = rg[i][c2]; if(c1>0)sum...
var largestMagicSquare = function(grid) { const row = grid.length; const col = grid[0].length; const startSize = row <= col ? row : col; for(let s = startSize; s > 1; s--){ for(let r = 0; r < grid.length - s + 1; r++){ for(let c = 0; c < grid[0].length - s + 1; c++){ if(isMa...
Largest Magic Square
Given a string s, find the length of the longest substring without repeating characters. &nbsp; Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest_s = '' curr_s = '' for i in s: if i not in curr_s: curr_s += i if len(curr_s) >= len(longest_s): longest_s = curr_s else: ...
class Solution { public int lengthOfLongestSubstring(String s) { Map<Character, Integer> hash = new HashMap<>(); int count = 0; int ans = 0; for(int i=0; i < s.length(); i++){ if(hash.containsKey(s.charAt(i))){ i = hash.get(s.charAt(i)) + 1; ...
class Solution { public: int lengthOfLongestSubstring(string s) { map<char, int> mp; int ans = 1; for(auto ch : s) { if(mp.find(ch) != mp.end()) { while(mp.find(ch) != mp.end()) mp.erase(mp.begin()); } mp.insert({ch, 1}); if(mp....
var lengthOfLongestSubstring = function(s) { // keeps track of the most recent index of each letter. const seen = new Map(); // keeps track of the starting index of the current substring. let start = 0; // keeps track of the maximum substring length. let maxLen = 0; for(let i = 0; i < s.len...
Longest Substring Without Repeating Characters
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. &nbsp; Example 1: Input: nums = [1,3], n = 6 Output: 1 Explanation: Combination...
class Solution: def minPatches(self, nums: List[int], n: int) -> int: #pre-process for convenience nums.append(n+1) t=1 sum=1 rs=0 if nums[0]!=1: nums=[1]+nums rs+=1 # the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go for...
class Solution { public int minPatches(int[] nums, int n) { long sum = 0; int count = 0; for (int x : nums) { if (sum >= n) break; while (sum+1 < x && sum < n) { ++count; sum += sum+1; } sum += x; } ...
class Solution { public: int minPatches(vector<int>& nums, int n) { nums.push_back(0); sort(nums.begin(), nums.end()); long sum = 0; int ans = 0; for(int i = 1; i < nums.size(); i++){ while((long)nums[i] > (long)(sum + 1)){ ans++; s...
// time complexity: // while loop is - o(n) beacuse we can potentially get to n with nums array full of ones and we will pass on each of them // in some cases it will hit o(logn) if the nums array is pretty empty var minPatches = function(nums, n) { // nums is sorted so we don't have to sort it let index = 0; ...
Patching Array
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
class Bank: def __init__(self, bal: List[int]): self.store = bal # storage list def transfer(self, a1: int, a2: int, money: int) -> bool: try: # checking if both accounts exist. and if the transaction would be valid if self.store[a1 - 1] >= money and self.store[a2 - 1] ...
class Bank { int N; long[] balance; public Bank(long[] balance) { this.N = balance.length; this.balance = balance; } public boolean transfer(int account1, int account2, long money) { if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < ...
class Bank { public: vector<long long> temp; int n; Bank(vector<long long>& balance) { temp=balance; n=balance.size(); } bool transfer(int account1, int account2, long long money) { if(account1<=n && account2<=n && account1>0 && account2>0 && temp[account1-1]>=money){ temp[account1-1]-=money; temp[acc...
/** * @param {number[]} balance */ var Bank = function(balance) { this.arr = balance; }; /** * @param {number} account1 * @param {number} account2 * @param {number} money * @return {boolean} */ Bank.prototype.transfer = function(account1, account2, money) { if (this.arr[account1-1] >= money && this.a...
Simple Bank System
You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray, return -1. A subarray is a contiguous non-empty sequence of elements within an...
class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: nums = [0] + nums + [0] stack = [0] for i in range(1,len(nums)): while nums[i] < nums[stack[-1]]: tmp = nums[stack.pop()] if tmp > threshold / (i - stack[-1] - 1):...
class Solution { public int validSubarraySize(int[] nums, int threshold) { int n = nums.length; int[] next_small = new int[n]; int[] prev_small = new int[n]; Stack<Integer> stack = new Stack<>(); stack.push(0); Arrays.fill(next_small, n); Arrays.fill(prev_smal...
class Solution { public: int validSubarraySize(vector<int>& nums, int threshold) { int n = nums.size(); vector<long long> lr(n, n), rl(n, -1); vector<int> s; for(int i = 0; i < n; ++i) { while(!s.empty() and nums[i] < nums[s.back()]) { lr[s.back()...
/** * @param {number[]} nums * @param {number} threshold * @return {number} */ var validSubarraySize = function(nums, threshold) { /* Approach: Use monotonous increasing array */ let stack=[]; for(let i=0;i<nums.length;i++){ let start = i; while(stack.length>0 && stack[stack.leng...
Subarray With Elements Greater Than Varying Threshold
Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order. The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. &nbsp; Example 1...
class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: def backtracking(nums,path): # to ensure that the base array has at least 2 elements if len(path)>=2: res.add(tuple(path)) for i in range(len(nums)): # to ensure...
class Solution { HashSet<List<Integer>> set; public List<List<Integer>> findSubsequences(int[] nums) { set=new HashSet<>(); dfs(nums,0,new ArrayList<>()); List<List<Integer>> ans=new ArrayList<>(); if(set.size()>0){ ans.addAll(set); } return ans; ...
class Solution { public: set<vector<int>>ans; void solve(int start, int n, vector<int>&nums, vector<int>&result){ if(result.size()>1)ans.insert(result); if(start==n){ return; } for(int i=start; i<n; i++){ if(result.empty() || result.back()<=nums[i]){ ...
var findSubsequences = function(nums) { const result = []; const set = new Set(); function bt(index=0,ar=[]){ if(!set.has(ar.join("_")) && ar.length >=2){ set.add(ar.join("_")); result.push(ar); } for(let i =index; i<nums.length; i++){ if...
Increasing Subsequences
You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively. Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. Return the string formed after mapping. The test cases ar...
class Solution: def freqAlphabets(self, s: str) -> str: for i in range(26,0,-1): s = s.replace(str(i)+"#"*(i>9),chr(96+i)) return s
class Solution { public String freqAlphabets(String str) { HashMap<String, Character> map = new HashMap<>(); int k = 1; for (char ch = 'a'; ch <= 'z'; ch++) { if (ch < 'j') map.put(String.valueOf(k++), ch); else map.put(String.valueOf(k...
class Solution { public: string freqAlphabets(string s) { int n=s.size(); string ans=""; for(int i=0;i<n;){ if(i+2<n && s[i+2]=='#'){ ans+= (s[i]-'0')*10 + (s[i+1]-'0') +96; i+=3; } else{ ans+=(s[i]-'0') + 96; i++; } } return ans; } };
var freqAlphabets = function(s) { const ans = [] for (let i = 0, len = s.length; i < len; ++i) { const c = s.charAt(i) if (c === '#') { ans.length = ans.length - 2 ans.push(String.fromCharCode(parseInt(`${s.charAt(i - 2)}${s.charAt(i - 1)}`, 10) + 96)) continue } ans.push(String.fr...
Decrypt String from Alphabet to Integer Mapping
Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: &lt;IntegerPart&gt;, &lt;NonR...
class Solution: # inspired from: # https://coolconversion.com/math/recurring-decimals-as-a-fraction/ # to which we wouldn't have access during interview. import typing def isRationalEqual(self, s: str, t: str) -> bool: # intuition: # write each numbes as fraction: num / den ...
class Solution { private List<Double> ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999); public boolean isRationalEqual(String S, String T) { return Math.abs(computeValue(S) - computeValue(T)) < 1e-9; } private double computeValue(String s) { if (!s.contains("(")) ...
class Solution { public: double toDouble(string s){ // Strings for each integral, fractional, and repeating part string in="", fn="", rn=""; int i=0; // Integral while(i<s.size() && s[i]!='.'){ in+=s[i]; i++; } // Fractional i++; while(i<s.size() && s...
var isRationalEqual = function(s, t) { return calculate(s) === calculate(t); function calculate(v) { let start = v.split('(')[0] || v; let newer = v.split('(')[1] && v.split('(')[1].split(')')[0] || '0'; start = start.includes('.') ? start : start + '.'; newer = newer.padEnd(10...
Equal Rational Numbers
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of "first second third". &nbsp; Example 1: Input: text = "alice is a ...
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: pattern = r"(?<=\b" + first +" " + second + r" )[a-z]*" txt = re.findall(pattern,text) return txt
class Solution { public String[] findOcurrences(String text, String first, String second) { List<String> list = new ArrayList<>(); String[] arr = text.split(" "); for(int i = 0; i < arr.length - 2; i++) { if(arr[i].equals(first) && arr[i + 1].equals(second)) { ...
class Solution { public: vector<string> findOcurrences(string text, string first, string second) { vector<string>ans; int i=0; while(i<text.length()) { string word = ""; string secondWord=""; while(i<text.length() && text[i]!=' ') { word = word+text[i]; i++; } if(word == first) { ...
var findOcurrences = function(text, first, second) { let result = []; let txt = text.split(' '); for(let i = 0; i<txt.length - 2; i++) { if(txt[i] === first && txt[i+1] === second) result.push(txt[i+2]); } return result; };
Occurrences After Bigram
Given an integer&nbsp;k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n &gt; 2. It is guaranteed that for the given constraints we can always find such Fibonac...
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib_sq = [1, 1] while fib_sq[-1] + fib_sq[-2] <= k: fib_sq.append(fib_sq[-1]+fib_sq[-2]) counter = 0 for i in range(len(fib_sq)-1, -1, -1): if fib_sq[i] <= k: counter += 1 ...
class Solution { public int findMinFibonacciNumbers(int k) { int ans = 0; while (k > 0) { // Run until solution is reached int fib2prev = 1; int fib1prev = 1; while (fib1prev <= k) { // Generate Fib values, stop when fib1prev is > k, we have the fib number...
class Solution { public: int findMinFibonacciNumbers(int k) { vector<int> fibb; int a = 1; int b = 1; fibb.push_back(a); fibb.push_back(b); int next = a + b; while (next <= k) { fibb.push_back(next); a = b; b = ...
var findMinFibonacciNumbers = function(k) { let sequence = [1, 1], sum = sequence[0] + sequence[1]; let i = 2; while (sum <= k) { sequence.push(sum); i++; sum = sequence[i-1]+sequence[i-2]; } let j = sequence.length-1, res = 0; while (k) { if (k >= sequence[j]) k ...
Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
Given the head of a linked&nbsp;list, rotate the list to the right by k places. &nbsp; Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1] &nbsp; Constraints: The number of nodes in the list is in the range [0, 500]. -100 &lt;= Node.val &lt;...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if k==0 or head is None or head.next is None: retu...
class Solution { public ListNode rotateRight(ListNode head, int k) { if(k<=0 || head==null || head.next==null){ return head; } int length=1; ListNode first=head; ListNode curr=head; ListNode node=head; while(node.next!=null){ ...
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: // like if it is useful t...
var rotateRight = function(head, k) { if(k === 0 || !head) return head; let n = 0; let end = null; let iterator = head; while(iterator) { n += 1; end = iterator; iterator = iterator.next; } const nodesToRotate = k % n; if(nodesToRotate === 0) return head; ...
Rotate List
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller...
# 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 BSTIterator: def __init__(self, root: Optional[TreeNode]): self.root=root self.tree=[]#list to store ...
class BSTIterator { TreeNode root; TreeNode current; Stack<TreeNode> st = new Stack<>(); public BSTIterator(TreeNode root) { this.root = root; //init(root); current = findLeft(root); //System.out.println("Init: stack is: "+st); } public int next() { ...
//TC O(1) and O(H) Space //MIMIC inorder class BSTIterator { public: stack<TreeNode*> stk; BSTIterator(TreeNode* root) { pushAll(root); // left is done } int next() { //root handled TreeNode* node = stk.top(); int ans = node->val; stk.pop(); ...
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var BSTIterator = function(root) { th...
Binary Search Tree Iterator
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. For example, when num = "5489355142": ...
class Solution: def getMinSwaps(self, num: str, k: int) -> int: num = list(num) orig = num.copy() for _ in range(k): for i in reversed(range(len(num)-1)): if num[i] < num[i+1]: ii = i+1 while ii < len(num) and n...
class Solution { public int getMinSwaps(String num, int k) { int[] nums=new int[num.length()]; int[] org=new int[num.length()]; for(int i=0;i<num.length();i++){ int e=Character.getNumericValue(num.charAt(i)); nums[i]=e; org[i]=e; } while(...
class Solution { public: // GREEDY APPROACH // min steps to make strings equal int minSteps(string s1, string s2) { int size = s1.length(); int i = 0, j = 0; int result = 0; while (i < size) { j = i; while (s1[j] != s2[i]) j++; while (i...
var getMinSwaps = function(num, k) { const digits = [...num] const len = digits.length; // helper function to swap elements in digits in place const swap = (i, j) => [digits[i], digits[j]] = [digits[j], digits[i]] // helper function to reverse elements in digits from i to the end of d...
Minimum Adjacent Swaps to Reach the Kth Smallest Number
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array hei...
class Solution: def heightChecker(self, heights: List[int]) -> int: heightssort = sorted(heights) import numpy as np diff = list(np.array(heightssort) - np.array(heights)) return (len(diff) - diff.count(0))
class Solution { public int heightChecker(int[] heights) { int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length); Arrays.sort(dupheights); int count = 0; for(int i=0 ; i< heights.length ; i++){ if(heights[i] != dupheights[i]){ count++; } } ...
class Solution { public: int heightChecker(vector<int>& heights) { vector<int> expected=heights; int count=0; sort(expected.begin(),expected.end()); for(int i=0;i<heights.size();i++){ if(heights[i]!=expected[i]) count++; } return count; } }...
var heightChecker = function(heights) { let count = 0; const orderedHeights = [...heights].sort((a, b) => a-b) for (let i = 0; i < heights.length; i++) { heights[i] !== orderedHeights[i] ? count++ : null } return count };
Height Checker
An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an addi...
class Solution: def isAdditiveNumber(self, num: str) -> bool: def isadditive(num1,num2,st): if len(st) == 0: return True num3 = str(num1+num2) l = len(num3) return num3 == st[:l] and isadditive(num2,int(num3),st[l:]) for i in range(1,len(num)-1): for...
class Solution { public boolean isAdditiveNumber(String num) { return backtrack(num, 0, 0, 0, 0); } public boolean backtrack(String num, int idx, long sum, long prev, int length){ if(idx == num.length()){ return length >= 3; } long currLong = 0; ...
class Solution { public: bool isAdditiveNumber(string num) { vector<string> adds; return backtrack(num, 0, adds); } private: bool backtrack(string num, int start, vector<string> &adds) { if (start >= num.size() && adds.size() >= 3) return true; int maxSi...
const getNum = (str, i, j) => { str = str.slice(i, j); if(str[0] == '0' && str.length > 1) return -1000 return Number(str); } var isAdditiveNumber = function(num) { // i = 3 say and make theory and proof that const len = num.length; for(let b = 2; b < len; b++) { for(let i = 0; i < b - ...
Additive Number
Given an&nbsp;integer n, return a string with n&nbsp;characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. &nbsp; &nbsp; Example 1: Input: n = 4 Output: "pppz" Explan...
class Solution: def generateTheString(self, n: int) -> str: alpha = "abcdefghijklmnopqrstuvwxyz" res="" while n>0: curr, alpha = alpha[0], alpha[1:] if n%2: res += curr*n n-=n else: res += curr*(n-1) ...
class Solution { public String generateTheString(int n) { String s = ""; String string ="a"; for (int i = 0; i < n-1; i++) s += string; if(n%2==0) return s+"b"; return s+"a"; } }
class Solution { public: string generateTheString(int n) { string s=""; if(n%2!=0){ for(int i=0;i<n;i++) s+="a"; } else{ for(int i=0;i<n-1;i++) s+="a"; s+="b"; } return s; } };
// C++ Code class Solution { public: string generateTheString(int n) { string res = ""; if (n%2 == 0) { res += 'a'; n -= 1; } for (int i=0;i < n;i++) res += 'k'; return res; } }; // JavaScript Code var generateTheString = func...
Generate a String With Characters That Have Odd Counts
A critical point in a linked list is defined as either a local maxima or a local minima. A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next nod...
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: idx, i = [], 1 prev, cur = head, head.next while cur and cur.next: if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val: idx.append(i) pre...
class Solution { public int[] nodesBetweenCriticalPoints(ListNode head) { int res[]=new int[]{-1,-1}; if(head==null||head.next==null||head.next.next==null) return res; int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1; ListNode prev=head,ptr=head.next; int idx=1,minD=Integer...
class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { if(!head or !head->next or !head->next->next) return {-1,-1}; int mini = 1e9; int prevInd = -1e9; int currInd = 0; int start = -1e9; int prev = head->val; head = head->next; ...
var nodesBetweenCriticalPoints = function(head) { const MAX = Number.MAX_SAFE_INTEGER; const MIN = Number.MIN_SAFE_INTEGER; let currNode = head.next; let prevVal = head.val; let minIdx = MAX; let maxIdx = MIN; let minDist = MAX; let maxDist = MIN; for (let i = 1; ...
Find the Minimum and Maximum Number of Nodes Between Critical Points
Given a string s, return the longest palindromic substring in s. &nbsp; Example 1: Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s consist of only digits and English letters.
class Solution: def longestPalindrome(self, s: str) -> str: res = "" for i in range(len(s)): left, right = i - 1, i + 1 while (right < len(s) and s[right] == s[i]): right += 1 while (0 <= left < right < len(s) and s[left] == s[right]): ...
class Solution { String max = ""; private void checkPalindrome(String s, int l, int r) { while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { if (r - l >= max.length()) { max = s.substring(l, r + 1); } l--; r++; ...
class Solution { public: string longestPalindrome(string s) { if(s.size() <= 1) return s; string longest = ""; for (int i = 0; i < s.size(); i++) { string sub1 = expand(s, i, i+1); string sub2 = expand(s, i, i); string sub3 = sub1.size() > sub2.size() ?...
I solve the problem distinguishing two different cases. First I consider the case when the length of the palindrome to be found is odd (there is a center). I then expand the search to left and right from the possible found center. Then I consider the case when the length of the palindrome to be found is pair (there i...
Longest Palindromic Substring
Given an array of string words. Return all strings in words which is substring of another word in any order.&nbsp; String words[i] is substring of words[j],&nbsp;if&nbsp;can be obtained removing some characters to left and/or right side of words[j]. &nbsp; Example 1: Input: words = ["mass","as","hero","superhero"] O...
class Solution: def stringMatching(self, words: List[str]) -> List[str]: ans=set() l=len(words) for i in range(l): for j in range(l): if (words[i] in words[j]) & (i!=j): ans.add(words[i]) return ans
class Solution { public List<String> stringMatching(String[] words) { List<String>ans = new ArrayList<>(); for(int i=0; i<words.length; i++){ String s = words[i]; for(int j=0; j<words.length; j++){ if(i == j){ continue; } ...
class Solution { public: vector<string> stringMatching(vector<string>& words) { vector<string> res; //output for(int i = 0 ; i < words.size(); i++) { for(int j = 0; j < words.size(); j++) { if(i != j && words[j].find(words[i]) != -1) {...
var stringMatching = function(words) { let res = []; for (let i = 0; i < words.length; i++) { for (let j = 0; j < words.length; j++) { if (j === i) continue; if (words[j].includes(words[i])) { res.push(words[i]); break; } } ...
String Matching in an Array
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: nums1[i] == nums2[j], and the line we draw does not inters...
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: @lru_cache(None) def dp(a,b): if a>=len(nums1) or b>=len(nums2): return 0 if nums1[a]==nums2[b]: return 1+dp(a+1,b+1) else: return max(dp(a+1,b),dp(a,b+1)) ...
class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int[][] dp = new int[m + 1][n + 1]; for(int i = 1; i <= m; i ++){ for(int j = 1; j <= n; j ++){ if(nums1[i - 1] == nums2[j - 1]) ...
class Solution { public: int solve(int n1,int n2,vector<int>& nums1, vector<int>& nums2,vector<vector<int>> &dp) { if(n1<0 || n2<0) return 0; if(dp[n1][n2]!=-1) return dp[n1][n2]; if(nums1[n1]==nums2[n2]) return dp[n1][n2]=1+solve(n1-...
/** https://leetcode.com/problems/uncrossed-lines/ * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var maxUncrossedLines = function(nums1, nums2) { // Array to hold the combination of connected numbers let dp = []; // We look up the connected numbers with matrix for (let i=0;i< ...
Uncrossed Lines
You are given an integer array nums. In one move, you can pick an index i where 0 &lt;= i &lt; nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input: nums = [1,2...
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() c=0 i=1 num=[] while i<len(nums): if nums[i]<=nums[i-1]: a=nums[i-1]+1 c+=(a-nums[i]) nums[i]=a i+=1 r...
class Solution { public int minIncrementForUnique(int[] nums) { //Approach - 1 : Using a Count array // TC : O(N) // SC : O(N) int max = 0; for(int i : nums) max = Math.max(max, i); int count[] = new int[nums.length + ma...
class Solution { public: int minIncrementForUnique(vector<int>& nums) { int minElePossible=0,ans=0; sort(nums.begin(),nums.end()); for(int i=0;i<nums.size();i++){ if(nums[i]<minElePossible){ ans+=minElePossible-nums[i]; nums[i]+=minElePossible-nums...
var minIncrementForUnique = function(nums) { let ans = 0, arr = nums.sort((a, b) => a - b); for (let i = 0; i < arr.length; i++) { if (arr[i] === arr[i + 1]) { arr[i + 1]++; ans++; } else if (arr[i] > arr[i + 1]) { if(arr[i] - arr[i - 1] === 1){ ans += arr[i] - arr[i + 1] + 1 ...
Minimum Increment to Make Array Unique
An array arr a mountain if the following properties hold: 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] Given a mountain array arr, return the index i s...
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: beg = 0 end = len(arr)-1 while beg <= end: mid = (beg+end)//2 if arr[mid] < arr[mid+1]: beg = mid +1 elif arr[mid] > arr[mid+1]: end = mid -...
class Solution { public int peakIndexInMountainArray(int[] arr) { int start = 0; int end = arr.length - 1; while( start < end){ int mid = start + (end - start)/2; // if mid < mid next if(arr[mid] < arr[mid + 1]){ start = mid + 1; } // otherwise it can ei...
class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { return max_element(arr.begin(), arr.end()) - arr.begin(); } };
var peakIndexInMountainArray = function(arr) { //lets assume we have peak it divides array in two parts // first part is increasing order , second part is decreasing // when we find the middle we'll compare arr[middle] > arr[middle+1], it means //we can only find max in first part of arr (increasing pa...
Peak Index in a Mountain Array
You are given a list of&nbsp;preferences&nbsp;for&nbsp;n&nbsp;friends, where n is always even. For each person i,&nbsp;preferences[i]&nbsp;contains&nbsp;a list of friends&nbsp;sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list.&nbsp;Friends...
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: dd = {} for i,x in pairs: dd[i] = preferences[i][:preferences[i].index(x)] dd[x] = preferences[x][:preferences[x].index(i)] ans = 0 ...
class Solution { public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { int[][] rankings = new int[n][n]; // smaller the value, higher the preference int[] pairedWith = new int[n]; for (int i = 0; i < n; i++) { for (int rank = 0; rank < n - 1; rank++) { int j = preferences[i]...
class Solution { public: bool check(int x , int y , int u , int v ,int n , vector<vector<int>>& pref){ int id_x = 0 , id_y = 0 , id_u = 0 , id_v = 0 ; //check indices of (y and u) in pref[x] ; for(int i = 0 ; i < n - 1; ++i ){ if(pref[x][i] == y) id_y = i ; if(pref[x...
var unhappyFriends = function(n, preferences, pairs) { let happyMap = new Array(n); for (let [i, j] of pairs) { happyMap[i] = preferences[i].indexOf(j); happyMap[j] = preferences[j].indexOf(i); } let unhappy = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < happyMap...
Count Unhappy Friends
You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] repr...
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: t = float('inf') tx, ty = target for i, j in ghosts: t = min(t, abs(tx - i) + abs(ty - j)) return t > abs(tx) + abs(ty)
// Escape The Ghosts // Leetcode: https://leetcode.com/problems/escape-the-ghosts/ class Solution { public boolean escapeGhosts(int[][] ghosts, int[] target) { int dist = Math.abs(target[0]) + Math.abs(target[1]); for (int[] ghost : ghosts) { if (Math.abs(ghost[0] - target[0]) + Math.ab...
class Solution { public: bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) { int minimumstepsreqbyplayer = abs(target[0]) + abs(target[1]); int minimumstepsreqbyanyghost = INT_MAX; for(auto x: ghosts){ minimumstepsreqbyanyghost = min(minimumstepsre...
var escapeGhosts = function(ghosts, target) { const getDistance = (target, source = [0, 0]) => { return ( Math.abs(target[0] - source[0]) + Math.abs(target[1] - source[1]) ); } const timeTakenByMe = getDistance(target); let timeTakenByGhosts = Infinity...
Escape The Ghosts
Given an array nums of integers, return how many of them contain an even number of digits. &nbsp; Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits).&nbsp; 345 contains 3 digits (odd number of digits).&nbsp; 2 contains 1 digit (odd number of digits).&nbsp; ...
class Solution: def findNumbers(self, nums: List[int]) -> int: even_count = 0 for elem in nums: if(len(str(elem))%2 == 0): even_count += 1 return even_count
class Solution { public int findNumbers(int[] nums) { int count = 0; for(int val : nums) { if((val>9 && val<100) || (val>999 && val<10000) || val==100000 ) count++; } return count; } }
class Solution { public: int findNumbers(vector<int>& nums) { int count = 0; for(auto it:nums) { int amount = 0; while(it>0) { amount++; it /= 10; } if (amount % 2 == 0) { ...
var findNumbers = function(nums) { let count = 0; for(let num of nums){ if(String(num).length % 2 === 0) count++ } return count; };
Find Numbers with Even Number of Digits
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. Given an array nums of even length n, pair up the elements of nums into n / 2 ...
class Solution: def minPairSum(self, nums: List[int]) -> int: pair_sum = [] nums.sort() for i in range(len(nums)//2): pair_sum.append(nums[i]+nums[len(nums)-i-1]) return max(pair_sum)
class Solution { public int minPairSum(int[] nums) { Arrays.sort(nums); int output = Integer.MIN_VALUE; //This is greedy, so n/2 pairs must be from start and end and move inwards for(int i=0, j=nums.length - 1; i<nums.length/2; i++, j--) { output = Math.max(outp...
class Solution { public: int minPairSum(vector<int>& nums){ //sort the array sort(nums.begin(),nums.end()); int start=0,end=nums.size()-1,min_max_pair_sum=0; //Observe the pattern of taking the first and last element, second and second last element... and soo onn.. //would help you to mini...
/** * @param {number[]} nums * @return {number} */ var minPairSum = function(nums) { nums.sort((a,b) => a-b); let max = 0; for(let i=0; i<nums.length/2; i++){ max = Math.max(max , nums[i] + nums[nums.length-1-i]); } return max; };
Minimize Maximum Pair Sum in Array
You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts. For example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30....
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: hs, ms = (int(x) for x in startTime.split(":")) ts = 60 * hs + ms hf, mf = (int(x) for x in finishTime.split(":")) tf = 60 * hf + mf if 0 <= tf - ts < 15: return 0 # edge case return tf...
class Solution { public int numberOfRounds(String loginTime, String logoutTime) { String[] arr1 = loginTime.split(":"); String[] arr2 = logoutTime.split(":"); int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]); int time2 = Integer.parseInt(arr2[0])*60 + Integer.par...
class Solution { public: int solve(string s) { int hour=stoi(s.substr(0,2)); int min=stoi(s.substr(3,5)); return hour*60+min; } int numberOfRounds(string loginTime, string logoutTime) { int st=solve(loginTime); int et=solve(logoutTime); int ans=0; ...
var numberOfRounds = function(loginTime, logoutTime) { const start = toMins(loginTime); const end = toMins(logoutTime); let roundStart = Math.ceil(start / 15); let roundEnd = Math.floor(end / 15); if (start < end) { return Math.max(0, roundEnd - roundStart); } else { roundE...
The Number of Full Rounds You Have Played
Given a 2D&nbsp;grid consists of 0s (land)&nbsp;and 1s (water).&nbsp; An island is a maximal 4-directionally connected group of 0s and a closed island&nbsp;is an island totally&nbsp;(all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. &nbsp; Example 1: Input: grid = [[1,1,1,1,1,1,1...
class Solution: '''主函数:计算封闭岛屿的数量''' def closedIsland(self, grid: List[List[int]]) -> int: result = 0 m, n = len(grid), len(grid[0]) self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]] # 遍历 grid,处理边缘陆地 for j in range(n): self.dfs(grid, 0, j) ...
class Solution { boolean isClosed = true; public int closedIsland(int[][] grid) { int m = grid.length; int n = grid[0].length; int count = 0; for(int i=1; i<m-1; i++){ for(int j=1; j<n-1; j++){ isClosed = true; if(grid[i][j] == 0){ ...
class Solution { public: bool isValid(int i,int j,vector<vector<int>>&grid) { if(i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 0) { return true; } return false; } void DFS(int i,int j,vector<vector<int>>&grid) { grid[i][j] = 1; ...
/** * @param {number[][]} grid * @return {number} */ var closedIsland = function(grid) { let rows = grid.length; let cols = grid[0].length; let islandCount = 0; // Initial island count // For Quick Response if (rows <= 2 || cols <= 2) return islandCount; for (let i = 0; i <= rows - 1; i++) ...
Number of Closed Islands
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. &nbsp; Example 1: Input: left = "4", right = "1...
class Solution: def superpalindromesInRange(self, left: str, right: str) -> int: min_num, max_num = int(left), int(right) count, limit = 0, 20001 # odd pals for num in range(limit + 1): num_str = str(num) if num_str[0] != 1 or num_str[0] != 4 or num_s...
class Solution { public int superpalindromesInRange(String left, String right) { int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0; for (int dig = 1; dig < 10; dig++) { boolean isOdd = dig % 2 > 0 && dig != 1; int innerLen = (dig >> 1) - 1, ...
class Solution { public: int superpalindromesInRange(string lef, string rig) { long L = stol(lef) , R = stol(rig); int magic = 100000 , ans = 0; string s = ""; for(int k = 1 ; k < magic ; k++){ s = to_string(...
var superpalindromesInRange = function(left, right) { let ans = 9 >= left && 9 <= right ? 1 : 0 const isPal = str => { for (let i = 0, j = str.length - 1; i < j; i++, j--) if (str.charAt(i) !== str.charAt(j)) return false return true } for (let dig = 1; dig < 10; dig++) { ...
Super Palindromes
Run-length encoding is a string compression method that works by&nbsp;replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string&nbsp;"aabccc"&nbsp;we replace "a...
class Solution: def getLengthOfOptimalCompression(self, s: str, k: int) -> int: # Find min lenth of the code starting from group ind, if there are res_k characters to delete and # group ind needs to be increased by carry_over additional characters def FindMinLen(ind, res_k, carry_over=0): ...
class Solution { public int getLengthOfOptimalCompression(String s, int k) { Map<String, Integer> memo = new HashMap<>(); return recur(s, '\u0000', 0, k, 0, memo); } private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map<String, Integer> memo) { if (index...
class Solution { public: int dp[101][101]; int dfs(string &s, int left, int K) { int k = K; if(s.size() - left <= k) return 0; if(dp[left][k] >= 0) return dp[left][k]; int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1; for(int i = left + 1; i <= s.size(); ++i) { ...
var getLengthOfOptimalCompression = function(s, k) { const memo = new Map() const backtrack = (i, lastChar, lastCharCount, k) => { if (k < 0) return Number.POSITIVE_INFINITY if (i >= s.length) return 0 const memoKey = `${i}#${lastChar}#${lastCharCount}#${k}` if (mem...
String Compression II
You may recall that an array arr is a mountain array if and only if: arr.length &gt;= 3 There exists some index i (0-indexed) 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] Given an integer arr...
class Solution: def minimumMountainRemovals(self, nums: List[int]) -> int: n = len(nums) inc = [0] * n dec = [0] * n # Longest Increasing Subsequence for i in range(1,n): for j in range(0,i): if nums[i] > nums[j]: inc[i] = max...
class Solution { public int minimumMountainRemovals(int[] nums) { int n = nums.length; int[] LIS = new int[n]; int[] LDS = new int[n]; Arrays.fill(LIS, 1); Arrays.fill(LDS, 1); // calculate the longest increase subsequence (LIS) for every index i for(int i=1...
class Solution { public: int minimumMountainRemovals(vector<int>& nums) { int n = nums.size(); vector<int> dp1(n,1), dp2(n,1); // LIS from front for(int i=0; i<n; i++) { for(int j=0; j<i; j++) { if(nums[i] > nums[j] && 1 + dp1[j] > dp...
var minimumMountainRemovals = function(nums) { let n=nums.length let previous=Array.from({length:n},item=>1) let previous2=Array.from({length:n},item=>1) //calcultaing left and right side LIS in single iteration for (let i=0;i<n;i++){ for (let j=0;j<i;j++){ //reverse indexes ...
Minimum Number of Removals to Make Mountain Array
You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, b...
from collections import defaultdict from collections import deque class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: n = len(graph) G = defaultdict(list) for v in range(n): for w in range(n): if graph[v][w]: ...
class Solution { int[] parent; int[] size; public int find(int x){ if(parent[x]==x) return x; int f = find(parent[x]); parent[x] = f; return f; } void merge(int x, int y){ if(size[x]>size[y]){ parent[y] = x; size[x] += size[y];...
class Solution { public: int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { sort(initial.begin(), initial.end()); int ans = -1, mn = INT_MAX, n = graph.size(); vector<vector<int>> new_graph(n); for(int i = 0; i < n; i++) for(int j =...
var minMalwareSpread = function(graph, initial) { let n = graph.length let AdjList = new Map(); let listFromGraph = (mat) => {// convert adj matrix to adj list for(let i=0; i<n; i++){ AdjList[i] = []; for(let j=0; j<n; j++){ if(mat[i][j] === 1 && i!==j){ AdjList[i].push(j...
Minimize Malware Spread II
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface are...
class Solution: def surfaceArea(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) area = 0 for r in range(m): for c in range(n): if grid[r][c] != 0: area += 2 if...
class Solution { public int surfaceArea(int[][] grid) { int area = 0; int n = grid.length; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ // Adding the top part of grid if(i==0) area += grid[i][j]; else area += Math.abs(grid[i][j]...
class Solution { public: int surfaceArea(vector<vector<int>>& grid) { int area = 0; for(int i = 0; i < grid.size(); i++) { for(int j = 0; j < grid[0].size(); j++) { //adding 4 sides area += grid[i][j]*4; //adding two because of there will only one t...
var surfaceArea = function(grid) { let cube=0, overlap=0; for(let i=0; i<grid.length; i++){ for(let j=0; j<grid[i].length; j++){ cube+=grid[i][j]; if(i>0){overlap+=Math.min(grid[i][j], grid[i-1][j]);} // x-direction if(j>0){overlap+=Math.min(grid[i][j], grid[i][j-1]);...
Surface Area of 3D Shapes
You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the tr...
class Solution: def getLucky(self, s: str, k: int) -> int: nums = [str(ord(c) - ord('a') + 1) for c in s] for _ in range(k): nums = str(sum(int(digit) for num in nums for digit in num)) return nums
class Solution { public int getLucky(String s, int k) { StringBuilder sb=new StringBuilder(); for(int i=0;i<s.length();i++) sb.append((s.charAt(i)-'a')+1); String result=sb.toString(); if(result.length()==1) return Character.getNumericValue(result.charAt(0)); ...
class Solution { public: int getLucky(string s, int k) { long long sum=0,d; string convert; for(auto& ch: s) { convert+= to_string((ch-96)); } while(k--) { sum=0; for(auto& ch: convert) { ...
/** * @param {string} s * @param {number} k * @return {number} */ var getLucky = function(s, k) { function alphabetPosition(text) { var result = []; for (var i = 0; i < text.length; i++) { var code = text.toUpperCase().charCodeAt(i) if (code > 64 && code < 91) result.push(code - 64);...
Sum of Digits of String After Convert
Given a non-negative integer x,&nbsp;compute and return the square root of x. Since the return type&nbsp;is an integer, the decimal digits are truncated, and only the integer part of the result&nbsp;is returned. Note:&nbsp;You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or&n...
class Solution: def mySqrt(self, x: int) -> int: beg =0 end =x while beg <=end: mid = (beg+end)//2 sqr = mid*mid if sqr == x: return mid elif sqr < x: beg = mid+1 else: end = mid-1 ...
class Solution { public int mySqrt(int x) { long answer = 0; while (answer * answer <= x) { answer += 1; } return (int)answer - 1; } }
class Solution { public: int mySqrt(int x) { int s = 0 , e = x , mid; while(s<e) { mid = s + (e-s)/2 ; if(e-s == 1) break ; long double sqr = (long double)mid *mid; if(sqr <= x) s = mid ; els...
/** * @param {number} x * @return {number} */ var mySqrt = function(x) { const numx = x; let num = 0; while (num <= x) { const avg = Math.floor((num+x) / 2); if (avg * avg > numx) x = avg - 1; else num = avg + 1; } return x; };
Sqrt(x)
Given a binary tree root and a&nbsp;linked list with&nbsp;head&nbsp;as the first node.&nbsp; Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree&nbsp;otherwise return False. In this context downward path means a path that starts at so...
class Solution(object): def isSubPath(self, head, root): if not root: return False if self.issame(head, root): return True return self.isSubPath(head, root.left) or self.isSubPath(head, root.right) def issame(self, head, root): if not head: ret...
class Solution { public boolean isSubPath(ListNode head, TreeNode root) { if(root == null) return false; if(issame(head, root)) return true; return isSubPath(head, root.left) || isSubPath(head, root.right); } private boolean issame(ListNode head, TreeNode root) { if(head == n...
class Solution { public: bool func(ListNode *head,TreeNode *root){ if(!head) return true; if(!root) return false; if(head->val == root->val) return func(head->next,root->left) or func(head->next,root->right); return false; } bool isSubPath(ListNode* head, TreeNode* root) { ...
var isSubPath = function(head, root) { if(!root) return false if(issame(head, root)) return true return isSubPath(head, root.left) || isSubPath(head, root.right) }; function issame(head, root){ if(!head) return true if(!root) return false if(head.val != root.val) return false ret...
Linked List in Binary Tree
You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. &nbsp; Example 1: Input: s = "(abcd)" Output: "dcba" Example 2: Input: s = "(u(love)i)" Output...
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] ans = "" res = deque([]) s = list(s) for i in s: if i==")": while stack[-1] != "(": res.append(stack.pop()) stack.pop() whil...
class Solution { public String reverseParentheses(String s) { Stack<String> stack = new Stack<>(); int j = 0; while(j < s.length()){ /* We need to keep on adding whatever comes as long as it is not a ')'. */ if(s.charAt(j) ...
class Solution { public: string reverseParentheses(string s) { stack<int> st; for(int i=0;i<s.size();i++) { if(s[i]=='(') { st.push(i); } else if(s[i]==')') { int strt=st.top(); strt=strt+...
function reverse(s){ return s.split("").reverse().join(""); } function solve(s,index) { let ans = ""; let j = index; while(j<s.length) { if(s[j] == '(') { let store = solve(s,j+1); ans += store.ans; j = store.j; } else if...
Reverse Substrings Between Each Pair of Parentheses
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: PeekingIterator(Iterator&lt;int&gt; nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the ...
class PeekingIterator: def __init__ (self,iterator): self.arr = iterator.v self._next = 0 self.is_has_next = True def next(self): val = self.arr[self._next] self.next+=1 if self.next >= len(self.arr): self.is_has_next = False return val def hasNext(self): return ...
// Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { Queue<Integer> q; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. q= new LinkedList<>(); while(itera...
/* * Below is the interface for Iterator, which is already defined for you. * **DO NOT** modify the interface for Iterator. * * class Iterator { * struct Data; * Data* data; * public: * Iterator(const vector<int>& nums); * Iterator(const Iterator& iter); * * // Returns the next element in the iteration. * i...
var PeekingIterator = function(iterator) { this.iterator = iterator this.curr = iterator.next() }; PeekingIterator.prototype.peek = function() { return this.curr }; PeekingIterator.prototype.next = function() { let temp = this.curr this.curr = this.iterator.next() return temp }; PeekingItera...
Peeking Iterator
There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answe...
class Solution: def countHousePlacements(self, n: int) -> int: @lru_cache(None) def rec(i, k): # i is the index of the house # k is the state of last house, 1 if there was a house on the last index else 0 if i>=n: ...
class Solution { int mod = (int)1e9+7; public int countHousePlacements(int n) { if(n == 1) return 4; if(n == 2) return 9; long a = 2; long b = 3; if(n==1) return (int)(a%mod); if(n==2) return (int)(b%mod); ...
class Solution { public: typedef long long ll; ll mod = 1e9+7; int countHousePlacements(int n) { ll house=1, space=1; ll total = house+space; for(int i=2;i<=n;i++){ house = space; space = total; total = (house+space)%mod; } return (total*total)%mo...
const mod = (10 ** 9) + 7 var countHousePlacements = function(n) { let prev2 = 1 let prev1 = 1 let ways = 2 for ( let i = 2; i <= n; i++ ) { prev2 = prev1 prev1 = ways ways = ( prev1 + prev2 ) % mod } return (ways ** 2) % mod }
Count Number of Ways to Place Houses
You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: 0 represents grass, 1 represents fire, 2 represents a wall that you and fire cannot pass through. You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at th...
class Solution(object): def maximumMinutes(self, A): m, n = len(A), len(A[0]) inf = 10 ** 10 d = [[0,1],[1,0],[0,-1],[-1,0]] fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1] A = [[inf if a < 2 else -1 for a in r] for r in A] def bfs(queue, seen...
import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; class Solution { public boolean ok(int[][] grid, int[][] dist, int wait_time) { int n = grid.length; int m = grid[0].length; Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>(); Q.add(new Pair<...
class Solution { public: int maximumMinutes(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> firetime(m, vector<int>(n, INT_MAX)); queue<pair<int, int>> q; // push fire positions into queue, and set the time as 0 for(int i=...
var maximumMinutes = function(grid) { let fireSpread = getFireSpreadTime(grid); let low = 0, high = 10 ** 9; while (low < high) { let mid = Math.ceil((low + high) / 2); if (canReachSafehouse(grid, fireSpread, mid)) low = mid; else high = mid - 1; } return canReachSafehouse(grid, fireSpread, low) ?...
Escape the Spreading Fire
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular p...
class Solution(object): def pyramidTransition(self, bottom, allowed): """ :type bottom: str :type allowed: List[str] :rtype: bool """ dic = defaultdict(list) for i in allowed: dic[(i[0], i[1])].append(i[2]) res = [] ...
class Solution { HashMap<String, List<Character>> map = new HashMap<>(); HashMap<String, Boolean> dp = new HashMap<>(); public boolean pyramidTransition(String bottom, List<String> allowed) { for(String s:allowed){ String sub = s.substring(0,2); char c = s.c...
class Solution { unordered_map<string,vector<char> > m; public: bool dfs(string bot,int i,string tem){ if(bot.size()==1) return true; if(i==bot.size()-1) { string st; return dfs(tem,0,st); } for(auto v:m[bot.substr(i,2)]){ tem.push_back(v); ...
var pyramidTransition = function(bottom, allowed) { const set = new Set(allowed); const memo = new Map(); const chars = ["A", "B", "C", "D", "E", "F"]; return topDown(bottom, bottom.length - 1); function topDown(prev, row) { const key = `${prev}#${row}`; if (row ==...
Pyramid Transition Matrix
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to ...
class Solution: def lastRemaining(self, n: int) -> int: beg = 1 len = n d = 1 fromleft = True while len > 1: if(fromleft or len%2 == 1): beg += d d <<= 1 len >>= 1 fromleft = not fromleft return...
class Solution { public int lastRemaining(int n) { int head = 1; int remain = n; boolean left = true; int step =1; while(remain > 1){ if(left || remain%2==1){ head = head + step; } remain /= 2; step *= 2...
class Solution { public: int lastRemaining(int n) { bool left=true; int head=1,step=1;//step is the difference between adjacent elements. while(n>1){ if(left || (n&1)){//(n&1)->odd head=head+step; } step=step*2; n=n/2; ...
var lastRemaining = function(n) { let sum=1; let num=1; let bool=true; while(n>1){ if(bool){sum+=num; bool=false;} else{if(n%2){sum+=num;} bool=true;} num*=2; n=Math.floor(n/2); } return sum; };
Elimination Game
Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. &nbsp; Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3. Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] Ex...
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: # basically we create two pointers # move one pointer extra fast # another pointer would be slow # when fast reaches end slow would be in mid slow = fast = head while fast and fast.n...
class Solution { public ListNode middleNode(ListNode head) { ListNode temp = head; int size = 0; while(temp!=null){ size++; temp = temp.next; } int mid = size/2; temp = head; for(int i=0;i<mid;i++){ temp = temp.next...
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* middleNode(ListNode* head) { ...
var middleNode = function(head) { var runner1 = head var runner2 = head?.next while(runner1 && runner2) { runner1 = runner1?.next runner2 = (runner2?.next)?.next } return runner1 };
Middle of the Linked List
Design a food rating system that can do the following: Modify the rating of a food item listed in the system. Return the highest-rated food item for a type of cuisine in the system. Implement the FoodRatings class: FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food i...
from heapq import heapify, heappop, heappush class RatedFood: def __init__(self, rating, food): self.rating = rating self.food = food def __lt__(self, other): if other.rating == self.rating: return self.food < other.food return self.rating < other.rating cl...
class FoodRatings { HashMap<String, TreeSet<String>> cuiToFood = new HashMap(); HashMap<String, Integer> foodToRat = new HashMap(); HashMap<String, String> foodToCui = new HashMap(); public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { for(int i = 0; i < foods.length; i++){ ...
class FoodRatings { public: unordered_map<string, set<pair<int, string>>> cuisine_ratings; unordered_map<string, string> food_cuisine; unordered_map<string, int> food_rating; FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) { for (int i = 0; i < foods.size(); ++...
var FoodRatings = function(foods, cuisines, ratings) { this.heaps = {}, this.foods = {}; let n = foods.length; for (let i = 0; i < n; i++) { let food = foods[i], cuisine = cuisines[i], rating = ratings[i]; if (!this.heaps[cuisine]) this.heaps[cuisine] = new PriorityQueue((a, b) => { // [food, rating] ...
Design a Food Rating System
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.&nbsp; Each glass holds one cup&nbsp;of champagne. Then, some champagne is poured into the first glass at the top.&nbsp; When the topmost glass is full, any excess liquid poured will fall equally...
class Solution: def champagneTower(self, poured: int, r: int, c: int) -> float: quantity=defaultdict(int) quantity[(0,0)]=poured for i in range(r+1): flag=False for j in range(i+1): prev_flow=quantity[(i,j)]-1 if prev_flow<=0: ...
// Champagne Tower // Leetcode: https://leetcode.com/problems/champagne-tower/ class Solution { public double champagneTower(int poured, int query_row, int query_glass) { if (poured == 0) return 0; double[] memo = new double[101]; memo[0] = poured; for (int i=0; i<100; i++) { ...
class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { vector<double> currRow(1, poured); for(int i=0; i<=query_row; i++){ //we need to make the dp matrix only till query row. No need to do after that vector<double> nextRow(i+2, 0); //If we are at...
var champagneTower = function(poured, query_row, query_glass) { let water = [poured]; let hasOverflow = true; let row = 0; while(true){ if (! hasOverflow) return 0 // We haven't reached query_row yet, and water ran out hasOverflow = false; let rowGlass =...
Champagne Tower
Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent. &nbsp; Example 1: Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down...
class Solution: def percentageLetter(self, s: str, letter: str) -> int: return (s.count(letter)*100)//len(s)
class Solution { public int percentageLetter(String str, char letter) { int count=0; int n=str.length(); for(int i=0;i<n;i++){ if(str.charAt(i)==letter){ count ++; } } int per= (100*count)/n; return per; ...
class Solution { public: int percentageLetter(string s, char letter) { int count=0; for(int i=0;i<s.length();i++) { if(s[i]==letter) { count++; } } return (count*100)/s.length(); } };
var percentageLetter = function(s, letter) { let count = 0; for (let i of s) { // count how many letters are in s if (i == letter) count++; } return (Math.floor((count*1.0) / (s.length*1.0) * 100)) // get percentage };
Percentage of Letter in String
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni &lt; positioni+1....
class Car: def __init__(self, pos, speed, idx, prev=None, next=None): self.pos = pos self.speed = speed self.idx = idx self.prev = prev self.next = next class Solution: def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: colis_times = [-1] * len(ca...
class Solution { public double[] getCollisionTimes(int[][] cars) { int n = cars.length; double[] res = new double[n]; Arrays.fill(res, -1.0); // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that // after catching c2, we may view c1 as n...
class Solution { public: vector<double> getCollisionTimes(vector<vector<int>>& cars) { int n = cars.size(); vector<double> res(n,-1.0); stack<int> st;// for storing indices for(int i=n-1;i>=0;i--) { //traversing from back if someone has greater speed and ahead of less...
var getCollisionTimes = function(cars) { // create a stack to hold all the indicies of the cars that can be hit const possibleCarsToHit = []; const result = new Array(cars.length).fill(-1); for (let i = cars.length - 1; i >= 0; i--) { // if there are cars to hit, check if the current car will h...
Car Fleet II
Given an integer array arr, return the length of a maximum size turbulent subarray of arr. A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if: For i &l...
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: def cmp(a,b): if a == b: return 0 if a > b : return 1 return -1 n = len(arr) ans = 1 prev = 0 for i in range(1,n): c = cmp(arr[i-1],arr[i]) if c ==...
class Solution { public int maxTurbulenceSize(int[] arr) { if(arr.length == 1) { return 1; } int l = 0, r = 1; int diff = arr[l] - arr[r]; int max; if(diff == 0) { l = 1; r = 1; max = 1; } else { l =...
class Solution { public: int maxTurbulenceSize(vector<int>& arr) { vector<int> table1(arr.size(), 0); vector<int> table2(arr.size(), 0); table1[0] = 1; table2[0] = 1; int max_len = 1; for (int i=1; i<arr.size(); ++i) { table1[i] = 1; table2[i] ...
var maxTurbulenceSize = function(arr) { const len = arr.length; const dp = Array.from({ length: len + 1 }, () => { return new Array(2).fill(0); }); let ans = 0; for(let i = 1; i < len; i++) { if(arr[i-1] > arr[i]) { dp[i][0] = dp[i-1][1] + 1; } else if(arr[i-1] < ...
Longest Turbulent Subarray
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: &nbsp; Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Outpu...
class Solution: def getRow(self, rowIndex: int) -> List[int]: # base case # we know that there exist two base case one which is for zero input # One when we have to exit our recursive loop if rowIndex == 0: return [1] if rowIndex == 1: return [1,1] ...
class Solution { public List<Integer> getRow(int rowIndex) { List<List<Integer>> out = new ArrayList<>(); for(int i = 0; i<=rowIndex; i++){ List<Integer>in = new ArrayList<>(i+1); for(int j = 0 ; j<= i; j++){ if(j == 0 || j == i){ in.add(1)...
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> ans(rowIndex+1,0); ans[0]=1; for(int i=1;i<rowIndex+1;i++){ for(int j=i;j>=1;j--){ ans[j]=ans[j]+ans[j-1]; } } return ans; } };
var getRow = function(rowIndex) { const triangle = []; for (let i = 0; i <= rowIndex; i++) { const rowValue = []; for (let j = 0; j < i + 1; j++) { if (j === 0 || j === i) { rowValue[j] = 1; } else { rowValue[j] = triangle[i - 1][j - ...
Pascal's Triangle II
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). &nbsp; Example 1: Input: matrix = [[9,9,4],[6,6,8]...
class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: ROWS, COLS = len(matrix), len(matrix[0]) dp = {} def dfs(r, c, prevVal): if (r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal): ...
class Solution { public int longestIncreasingPath(int[][] matrix) { int[][] memo = new int[matrix.length][matrix[0].length]; int longestPath = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { dfs(matrix, i, j, memo); ...
class Solution { public: // declare a dp int dp[205][205]; // direction coordinates of left, right, up, down vector<int> dx = {-1, 0, 1, 0}; vector<int> dy = {0, 1, 0, -1}; // dfs function int dfs(vector<vector<int>>& matrix, int i, int j, int n, int m) ...
var longestIncreasingPath = function(matrix) { const m = matrix.length, n = matrix[0].length; const dp = new Array(m).fill(0).map(() => { return new Array(n).fill(-1); }); let ans = 0; const dir = [0, -1, 0, 1, 0]; const dfs = (x, y) => { if(dp[x][y] != -1) return dp[x][y]; ...
Longest Increasing Path in a Matrix
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: i + minJump &lt;= j &lt;= min(i + maxJump, s.length - 1), and s[j] == '0'. Return tr...
class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: # dp[i] represents whether i is reachable dp = [False for _ in s] dp[0] = True for i in range(1, len(s)): if s[i] == "1": continue # iterate through the solutions in range [i - ...
class Solution { public boolean canReach(String s, int minJump, int maxJump) { if(s.charAt(s.length() - 1) != '0') return false; Queue<Integer> queue = new LinkedList<>(); queue.add(0); // This variable tells us till which index we have processed ...
class Solution { public: bool canReach(string s, int minJump, int maxJump) { int n = s.length(); if(s[n-1]!='0') return false; int i = 0; queue<int> q; q.push(0); int curr_max = 0; while(!q.empty()){ i = q.front(); ...
var canReach = function(s, minJump, maxJump) { const validIdxs = [0]; for (let i = 0; i < s.length; i++) { // skip if character is a 1 or if all the // valid indicies are too close if (s[i] === '1' || i - validIdxs[0] < minJump) { continue; } // remo...
Jump Game VII
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candi...
class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): counter = defaultdict(int) mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i] largestVote = -1 # keep largest vote person index for i in range(len(persons))...
class TopVotedCandidate { int[] persons; int[] times; int length; Map<Integer, Integer> voteCount; Map<Integer, Integer> voteLead; public TopVotedCandidate(int[] persons, int[] times) { this.persons = persons; this.times = times; length = times.length-1; int lead...
class TopVotedCandidate { public: vector<int> pref; vector<int> glob_times; TopVotedCandidate(vector<int>& persons, vector<int>& times) { int n = times.size(); glob_times = times; pref.resize(n); vector<int> cnt; int sz = persons.size(); cnt.resize(sz+1, 0); ...
var TopVotedCandidate = function(persons, times) { this.times = times; this.len = times.length; this.votes = new Array(this.len).fill(0); let max = 0; // max votes received by any single candidate so far. let leader = -1l; this.leaders = persons.map((person, i) => { this.votes[...
Online Election
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. &nbsp; Example 1: Input: nums = [21,4,7] Output: 32 Explanation: 21 has 4 divisors: 1, 3, 7, 21 4 has 3 divisors: 1, 2, 4 7 has 2 divisors: 1, 7 T...
import math class Solution: def sumFourDivisors(self, nums: List[int]) -> int: s=0 for i in nums: r=i+1 c=2 for j in range(2, int(math.sqrt(i))+1): if i%j==0: if (i / j == j) : c+=1 ...
class Solution { public int sumFourDivisors(int[] nums) { int res = 0; for(int val : nums){ int sum = 0; int count = 0; for(int i=1;i*i <= val;i++){ if(val % i == 0){ sum += i; count++; if...
class Solution { public: int sumFourDivisors(vector<int>& nums) { int n = nums.size(); int sum = 0,cnt=0,temp=0; for(int i=0;i<n;i++){ int x = nums[i]; int sq = sqrt(x); for(int j=1;j<=sq;j++){ if(x%j==0){ ...
var sumFourDivisors = function(nums) { let check = (num) => { let divs = [num]; // init the array with the number itself let orig = num; num = num >> 1; // divide in half to avoid checking too many numbers while (num > 0) { if (orig % num === 0) divs.push(num); ...
Four Divisors
You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits. &nbsp; Example 1: Input: num = 310 Output: 103 Explana...
class Solution: def smallestNumber(self, num: int) -> int: lst=[i for i in str(num)] if num<0: return ''.join(['-'] + sorted(lst[1:],reverse=True)) lst=sorted(lst) if '0' in lst: itr=0 while itr<len(lst) and lst[itr]=='0': itr+=1 ...
class Solution { public long smallestNumber(long num) { if(num == 0){ return 0; } boolean isNegative = num < 0; num = num < 0 ? num * -1 : num; char[] c = String.valueOf(num).toCharArray(); Arrays.sort(c); String str; if(!isNegati...
class Solution { public: long long smallestNumber(long long num) { if (num < 0) { string s = to_string(-num); sort(s.rbegin(), s.rend()); return -stoll(s); } else if (num == 0) return 0; string s = to_string(num); so...
var smallestNumber = function(num) { let arr = Array.from(String(num)); if(num>0){ arr.sort((a,b)=>{ return a-b; }) } else{ arr.sort((a,b)=>{ return b-a; }) } for(let i=0;i<arr.length;i++){ if(arr[i]!=0){ [arr[0],arr[i]]=[arr[i]...
Smallest Value of the Rearranged Number
An&nbsp;integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers&nbsp;in the range [low, high]&nbsp;inclusive that have sequential digits. &nbsp; Example 1: Input: low = 100, high = 300 Output: [123,234] Example 2: Input: low =...
class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: l = len(str(low)) h = len(str(high)) ans = [] for i in range(l,h+1): for j in range(1,11-i): t = str(j) for k in range(i-1): t+=str(int(t[-1])...
class Solution { public List<Integer> sequentialDigits(int low, int high) { int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length(); List<Integer> output = new ArrayList<>(); for(int size=lowSize; size<=highSize; size++) { int seedNumber = getSeedNum...
class Solution { public: vector<int> sequentialDigits(int low, int high) { string lf = to_string(low); string rt = to_string(high); vector<int> ans; for(int i = lf.size(); i <= rt.size(); i++){ // 字符串长度 for(int st = 1; st <= 9; st++){ string base(...
var sequentialDigits = function(low, high) { const digits = '123456789'; const ans = []; const minLen = low.toString().length; const maxLen = high.toString().length; for (let windowSize = minLen; windowSize <= maxLen; ++windowSize) { for (let i = 0; i + windowSize <= digits.length;...
Sequential Digits
You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note...
class Solution: def largestWordCount(self, messages: List[str], senders: List[str]) -> str: d={} l=[] for i in range(len(messages)): if senders[i] not in d: d[senders[i]]=len(messages[i].split()) else: d[senders[i]]+=len(messages[i].spl...
class Solution { public String largestWordCount(String[] messages, String[] senders) { HashMap<String,Integer> hm=new HashMap<>(); int max=0; String name=""; for(int i=0;i<messages.length;i++){ String[] words=messages[i].split(" "); int freq=hm...
class Solution { public: string largestWordCount(vector<string>& messages, vector<string>& senders) { int n(size(messages)); map<string, int> m; for (auto i=0; i<n; i++) { stringstream ss(messages[i]); string word; int count(0); while (ss >> ...
/** * @param {string[]} messages * @param {string[]} senders * @return {string} */ var largestWordCount = function(messages, senders) { let wordCount = {} let result = '' let maxCount = -Infinity for (let i = 0; i < messages.length;i++) { let count=messages[i].split(' ').length wordC...
Sender With Largest Word Count
Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are ...
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0 for i in range(1, sz): for j in range(i): difference = nums[i] - nums[j] dp[i][difference] += 1 ...
class Solution { public int numberOfArithmeticSlices(int[] nums) { int n=nums.length; HashMap<Integer,Integer> []dp=new HashMap[n]; for(int i=0;i<n;i++){ dp[i]=new HashMap<Integer,Integer>(); } int ans=0; for(int i=1;i<n...
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { int n=nums.size(),ans=0; unordered_map<long long, unordered_map<int,int>> ma; // [diff, [index, count]] unordered_map<int,int> k; for(int i=1;i<n;i++) { for(int j=0;j<i;j++) {...
/** * @param {number[]} nums * @return {number} */ var numberOfArithmeticSlices = function(nums) { let dp = new Array(nums.length); for(let i = 0; i < nums.length; i++) { dp[i] = new Map(); } let ans = 0; for(let j = 1; j < nums.length; j++) { for(let i = 0; i < j; i++) { let commonDifference...
Arithmetic Slices II - Subsequence
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. &nbsp; Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5] Example 2:...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ lessthan = [] ...
class Solution { public ListNode partition(ListNode head, int x) { ListNode left = new ListNode(0); ListNode right = new ListNode(0); ListNode leftTail = left; ListNode rightTail = right; while(head != null){ if(head.val < x){ lef...
class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode *left = new ListNode(0); ListNode *right = new ListNode(0); ListNode *leftTail = left; ListNode *rightTail = right; while(head != NULL){ if(head->val < x){ ...
var partition = function(head, x) { if (!head) { return head; } const less = []; const greater = []; let concat; rec(head); return head; function rec(currentNode) { if (currentNode.val < x) { less.push(currentNode.val); } else { g...
Partition List
Given an m x n matrix, return&nbsp;true&nbsp;if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. &nbsp; Example 1: Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] Output: true Explanation: In the above grid, the&nbsp;diagonal...
########################################################################################### # Number of rows(M) x expected numbers(N) # Space: O(N) # We need to store the expected numbers in list ############################################################################################ class Solution: ...
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; for(int i = 0; i < m; i++){ int row = 0; int col = i; int e = matrix[row++][col++]; while(row < n &&...
class Solution { public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) if (matrix[i][j] != matrix[i - 1][j - 1]) return false; return tr...
var isToeplitzMatrix = function(matrix) { for (let i=0; i < matrix.length-1; i++) { for (let j=0; j < matrix[i].length-1; j++) { if (matrix[i][j] !== matrix[i+1][j+1]) { return false } } } return true };
Toeplitz Matrix