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
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring ...
class Solution: def maximumBinaryString(self, binary: str) -> str: zero = binary.count('0') # count number of '0' zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's) ...
class Solution { public String maximumBinaryString(String binary) { int n = binary.length(); StringBuffer ans = new StringBuffer(""); StringBuffer buffer = new StringBuffer(""); int onesAfter1stZero = 0; boolean found1stZero = false; for(int i=0;i<n;i++){ ...
class Solution { public: string maximumBinaryString(string binary) { int n = binary.size(); int z_count=0; //count the number of zeros int z_index=-1; //index of the leftmost zero that is why we start iterating from the right for(int i=n-1;i>=0;i--) { if(binary[i]=='0') { ...
/** * @param {string} binary * @return {string} */ var maximumBinaryString = function(binary) { /* 10 -> 01 allows us to move any zero to left by one position 00 -> 10 allows us to convert any consicutive 00 to 10 So we can collect all the zeros together then convert them in 1 except for the rightmos...
Maximum Binary String After Change
Given an array of non-negative integers arr, you are initially positioned at start&nbsp;index of the array. When you are at index i, you can jump&nbsp;to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. &nbsp; Example 1: Input:...
class Solution: def canReach(self, arr: List[int], start: int) -> bool: vis = [0]*len(arr) q = deque() q.append(start) while q: cur = q.popleft() print(cur) vis[cur] = 1 if arr[cur] == 0: return True if cu...
class Solution { public boolean canReach(int[] arr, int start) { int n = arr.length; boolean[] vis = new boolean[n]; Queue<Integer> q = new LinkedList<>(); q.add(start); while(!q.isEmpty()){ int size = q.size(); while(size-- > 0){ int c...
class Solution { public: bool dfs(int curr, vector<int>& arr, vector<bool>& visited, int size) { // edge cases - we can't go outside the array size and if the curr index is alredy visited it will repeat same recursion all over again so we can return false in that case too. if(curr < 0 || curr >= size || v...
/** * @param {number[]} arr * @param {number} start * @return {boolean} */ var canReach = function(arr, start) { let queue = [start]; while(queue.length) { let index = queue.shift(); if(index >= 0 && index < arr.length && arr[index] >=0 ){ if(arr[index] === 0)...
Jump Game III
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. &nbsp; Example 1: Input: root = [1,2,...
# 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 traverse(self,node,par): if node: self.parent[node.val] = par self.trave...
class Solution { HashMap<Integer, List<TreeNode>> parent_val_child_nodes_map; HashMap<Integer, TreeNode> child_val_parent_node_map; public List<TreeNode> delNodes(TreeNode root, int[] to_delete) { // initialize map parent_val_child_nodes_map = new HashMap<> (); child_val_parent_no...
class Solution { void solve(TreeNode* root,TreeNode* prev,unordered_map<int,int>& mp,int left,vector<TreeNode*>& ans){ if(root==NULL) return; int f=0; solve(root->left,root,mp,1,ans); solve(root->right,root,mp,0,ans); if(mp.find(root->val)!=mp.end()){ ...
var delNodes = function(root, to_delete) { if(!root) return []; to_delete = new Set(to_delete); // know how to delete // while deleting add new nodes to same algo const ans = []; const traverse = (r = root, p = null, d = 0) => { if(!r) return null; if(to_delete.has(r.val)) { ...
Delete Nodes And Return Forest
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an ev...
class Solution: def countGoodNumbers(self, n: int) -> int: ans = 1 rem = n % 2 n -= rem ans = pow(20, n//2, 10**9 + 7) if rem == 1: ans *= 5 return ans % (10**9 + 7)
class Solution { int mod=(int)1e9+7; public int countGoodNumbers(long n) { long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd long second=n/2;//second power would be n/2 only irrespective of even or odd long mul1=power(5,first)%mod;//5 power n/2 ...
// Approach :-> This is question of combination // if n as large no.... // 0 1 2 3 4 5 6 7 8 9 10 11 . . . . . n // 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 . . . . . n/4 times of 4 and n/4 times of 5; //so calculate 5*4 = 20 -------> 20 * 20 * 20 * . . . . .. n/2 times //so calcultae pow(20,n/2) // if n is even r...
class Math1 { // https://en.wikipedia.org/wiki/Modular_exponentiation static modular_pow(base, exponent, modulus) { if (modulus === 1n) return 0n let result = 1n base = base % modulus while (exponent > 0n) { if (exponent % 2n == 1n) result...
Count Good Numbers
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can re...
from collections import defaultdict from functools import lru_cache class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: N = len(req_skills) skills = {skill: i for i, skill in enumerate(req_skills)} people_mask = defaultdict(int) ...
class Solution { public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { int N = 1 << req_skills.length, INF = (int)1e9; int[] parent = new int[N]; int[] who = new int[N]; int[] dp = new int[N]; Arrays.fill(dp, INF); dp[0] = 0; fo...
class Solution { public: vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) { vector<int> mask(people.size(), 0); for(int i=0; i<people.size(); i++){ for(int j=0; j<req_skills.size(); j++){ for(int z=0; z<people[i].size(); z++){...
/** * @param {string[]} req_skills * @param {string[][]} people * @return {number[]} */ var smallestSufficientTeam = function(req_skills, people) { const skillIndexMap = new Map(); req_skills.forEach((skill, index) => skillIndexMap.set(skill,index) ); const skillTeamMap = new Map([[0, []]...
Smallest Sufficient Team
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array ...
"" from collections import Counter class Solution: def findLHS(self, nums: List[int]) -> int: counter=Counter(nums) # values=set(nums) res=0 # if len(values)==1:return 0 for num in nums: if num+1 in counter or num-1 in counter: res=max(res,counter[num]+counter.get(num+1,0)) res=max(res,counter[num...
class Solution { public static int firstOccurence(int[] arr,int target) { int res=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=start + (end-start)/2; if(arr[mid]==target) { res=mid; ...
class Solution { public: int findLHS(vector<int>& nums) { map<int,int> m; for(int i=0;i<nums.size();i++) { m[nums[i]]++; } int ans=0; int x=-1,y=0; for(auto i=m.begin();i!=m.end();i++) { if(i->first-x==1) { ...
var findLHS = function(nums) { let countNumber = {}; let result = []; for (let i=0; i<nums.length; i++) { if (!countNumber[nums[i]]) { countNumber[nums[i]] = 1; } else { countNumber[nums[i]]++; } } for (let value of Object.keys(countNumber)) { ...
Longest Harmonious Subsequence
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of ...
class Solution: def maximumXOR(self, nums: List[int]) -> int: res=0 for i in nums: res |= i return res
class Solution { public int maximumXOR(int[] nums) { int res = 0; for (int i=0; i<nums.length; i++){ res |= nums[i]; } return res; } }
class Solution { public: int maximumXOR(vector<int>& nums) { int res = 0; for (int i=0; i<nums.size() ; i++){ res |= nums[i]; } return res; } };
/** * @param {number[]} nums * @return {number} */ var maximumXOR = function(nums) { return nums.reduce((acc, cur) => acc |= cur, 0); };
Maximum XOR After Operations
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 &lt;= i &lt; j &lt; dominoes.length, and dominoes[i] i...
import math class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: d=dict() for i in dominoes: i.sort() #Just to make everything equal and comparable if(tuple(i) in d.keys()): #In python, lists are unhashable so converted the list into t...
class Solution { /** Algorithm 1. Brute force cannot be used because of the set size. 2. Traverse the dominos and group & count them by min-max value. As pieces can be from 1 to 9, means their groups will be from 11 to 99. eg: [1,2] will be the same as [2,1]. Their value is 10...
class Solution { public: int numEquivDominoPairs(vector<vector<int>>& dominoes) { map<pair<int,int>,int> m; int ans=0; for(auto &d:dominoes) { int a=min(d[0],d[1]),b=max(d[0],d[1]); m[{a,b}]++; } for(auto &p:m) { int n=p...
var numEquivDominoPairs = function(dominoes) { let map = {}; let count = 0; for (let [a, b] of dominoes) { if (b > a) { [a, b] = [b, a]; } let key = `${a}-${b}`; if (map.hasOwnProperty(key)) { map[key]++; count += map[key]; } else {...
Number of Equivalent Domino Pairs
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after d...
class Solution: def divide(self, dividend: int, divisor: int) -> int: # Solution 1 - bitwise operator << """ positive = (dividend < 0) is (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) if divisor == 1: quotient = dividend else: quotient...
class Solution { public int divide(int dividend, int divisor) { if(dividend == 1<<31 && divisor == -1){ return Integer.MAX_VALUE; } boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false; dividend = Math.abs(dividend); divisor = Math.abs(divisor)...
class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) { return INT_MAX; } long dvd = labs(dividend), dvs = labs(divisor), ans = 0; int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; while (dvd >= dvs) { ...
var divide = function(dividend, divisor) { if (dividend == -2147483648 && divisor == -1) return 2147483647; let subdividend = Math.abs(dividend) let subdivisor = Math.abs(divisor) let string_dividend = subdividend.toString() let i = 0 let ans=0 let remainder = 0 while(i<string_dividend.l...
Divide Two Integers
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. &nbsp; Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. ...
class Solution: def trap(self, a: List[int]) -> int: l=0 r=len(a)-1 maxl=0 maxr=0 res=0 while (l<=r): if a[l]<=a[r]: if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >= else: res+=maxl-a[l] #adding captured water when maxl>...
class Solution { public int trap(int[] height) { int left = 0; int right = height.length - 1; int l_max = height[left]; int r_max = height[right]; int res = 0; while(left < right) { if(l_max < r_max) { left+=1; ...
class Solution { public: int trap(vector<int>& height) { int left=0,right=height.size()-1; int maxleft=0,maxright=0; int res=0; while(left<=right){ if(height[left]<=height[right]){ if(height[left]>=maxleft)maxleft=height[left]; else res += ...
var trap = function(height) { let left = 0, right = height.length - 1; let hiLevel = 0, water = 0; while(left <= right) { let loLevel = height[height[left] < height[right] ? left++ : right--]; hiLevel = Math.max(hiLevel, loLevel); water += hiLevel - loLevel ; } return water; ...
Trapping Rain Water
You are given a string s consisting of digits and an integer k. A round can be completed if the length of s is greater than k. In one round, do the following: Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on....
class Solution: def digitSum(self, s: str, k: int) -> str: while len(s) > k: set_3 = [s[i:i+k] for i in range(0, len(s), k)] s = '' for e in set_3: val = 0 for n in e: val += int(n) s += str(val) ...
class Solution { public String digitSum(String s, int k) { while(s.length() > k) s = gen(s,k); return s; } public String gen(String s,int k){ String res = ""; for(int i=0;i < s.length();){ int count = 0,num=0; while(i < s.length() && count++ < k) num +...
class Solution { public: string digitSum(string s, int k) { if(s.length()<=k) return s; string ans=""; int sum=0,temp=k; int len = s.length(); for(int i=0;i<len;i++){ sum += (s[i] -'0'); temp--; if(temp==0){ ...
var digitSum = function(s, k) { while (s.length > k) { let newString = ""; for (let i = 0; i < s.length; i += k) newString += s.substring(i, i + k).split("").reduce((acc, val) => acc + (+val), 0); s = newString; } return s; };
Calculate Digit Sum of a String
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum prof...
class Solution: def maxProfit(self, prices: List[int]) -> int: n=len(prices) ans=0 want="valley" for i in range(n-1): if want=="valley" and prices[i]<prices[i+1]: ans-=prices[i] want="hill" elif want=="hill" and prices[i]>prices...
class Solution { public int maxProfit(int[] prices) { int n = prices.length,profit = 0; for(int i=0;i<n-1;i++){ if(prices[i+1]>prices[i]){ profit += prices[i+1]-prices[i]; } } return profit; } }
class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); int ans=0,currMin=prices[0]; for(int i=1;i<n;i++){ while(i<n && prices[i]>prices[i-1]){ i++; } ans+=(prices[i-1]-currMin); currMin=prices[i]; ...
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { let lowestNum = prices[0]; let highestNum = prices[0]; let profit = highestNum - lowestNum; for(var indexI=1; indexI<prices.length; indexI++) { if(prices[indexI] < prices[indexI - 1]) { lowestNum ...
Best Time to Buy and Sell Stock II
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each&nbsp;of the two arrays. &nbsp; Example 1: Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"] Output: 2 Explanation: - "leetcode" appears exactly once in each of the two arr...
class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: count = Counter(words1 + words2) return len([word for word in count if count[word] == 2 and word in words1 and word in words2])
class Solution { public int countWords(String[] words1, String[] words2) { HashMap<String, Integer> map1 = new HashMap<>(); HashMap<String, Integer> map2 = new HashMap<>(); for(String word : words1) map1.put(word,map1.getOrDefault(word,0)+1); for(String word : word...
class Solution { public: int countWords(vector<string>& words1, vector<string>& words2) { unordered_map<string, int> freq1, freq2; for (auto& s : words1) ++freq1[s]; for (auto& s : words2) ++freq2[s]; int ans = 0; for (auto& [s, v] : freq1) if (v == 1 && freq2[s] ...
var countWords = function(words1, words2) { const map1 = new Map(); const map2 = new Map(); let count = 0; for (const word of words1) { map1.set(word, map1.get(word) + 1 || 1); } for (const word of words2) { map2.set(word, map2.get(word) + 1 || 1); } for (const word of w...
Count Common Words With One Occurrence
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a &lt; b b - a equals to the minimum absolute difference of any two elements in...
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() diff=float(inf) for i in range(0,len(arr)-1): if arr[i+1]-arr[i]<diff: diff=arr[i+1]-arr[i] lst=[] for i in range(0,len(arr)-1): if arr[i+1]-a...
class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { List<List<Integer>> ans=new ArrayList<>(); Arrays.sort(arr); int min=Integer.MAX_VALUE; for(int i=0;i<arr.length-1;i++){ int diff=Math.abs(arr[i]-arr[i+1]); if(diff<min) ...
class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { sort(arr.begin(),arr.end()); int diff=INT_MAX; for(int i=1;i<arr.size();i++){ diff=min(diff,abs(arr[i]-arr[i-1])); } vector<vector<int>>v; for(int i=1;i<arr.size();i++){ ...
var minimumAbsDifference = function(arr) { arr.sort((a, b) => a - b) let minDif = Infinity let res = [] for (let i = 0; i < arr.length - 1; i++) { let currDif = Math.abs(arr[i + 1] - arr[i]) if (currDif < minDif) minDif = currDif } for (let i = 0; i < arr.length - 1; i++) { ...
Minimum Absolute Difference
We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all ...
class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: parent = list(range(n+1)) def find(i): if parent[i] != i: parent[i] = find(parent[i]) return parent[i] def union(i,j): parent[find(i)] =...
//Solving the problem using Disjoint Set Union Find approach class Solution { public int find(int x){ if(parent[x] == x) return x; //Optimising by placing the same parent for all the elements to reduce reduntant calls return parent[x] = find(parent[x]); } public void...
// DSU Class Template class DSU { vector<int> parent, size; public: DSU(int n) { for(int i=0; i<=n; i++) { parent.push_back(i); size.push_back(1); } } int findParent(int num) { if(parent[num] == num) return num; return parent[num] = findParent(pa...
var areConnected = function(n, threshold, queries) { // if(gcd(a,b)>threshold), a and b are connected // 2 is connected with : 2, 4,6,8,10,12,14,16, (gcd(2,y)=2) // 3 is connected with : 3,6,9,12,... (gcd(3,y)=3) // 4 is connected with : 4,8,12,16,20,24,28, (gcd(4,y)=4) // 6 is connected with : 6,...
Graph Connectivity With Threshold
Given an integer n, return an array ans of length n + 1 such that for each i (0 &lt;= i &lt;= n), ans[i] is the number of 1's in the binary representation of i. &nbsp; Example 1: Input: n = 2 Output: [0,1,1] Explanation: 0 --&gt; 0 1 --&gt; 1 2 --&gt; 10 Example 2: Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0...
class Solution: def countBits(self, n: int) -> List[int]: # We know that all exponential values of two have 1 bit turned on, the rest are turned off. # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed # into smaller numbers where we already hav...
class Solution { public void count(int n, int[] a, int k) { int i; for(i=k ; i<k*2 && i<=n; i++) a[i]=a[i-k]+1; if(i==n+1) return; count(n,a,k*2); } public int[] countBits(int n) { int a[] = new int[n+1]; a[0]=0; count(n,a,...
class Solution { private: int countones( int n ){ int count = 0; while(n){ count ++; n = n & ( n-1 ); } return count; } public: vector<int> countBits(int n) { vector<int> ans; for( int i = 0; i <= n; i++ ){ int x = countones...
var countBits = function(n) { if (n === 0) return [0]; const ans = new Array(n + 1).fill(0); let currRoot = 0; for (let idx = 1; idx <= n; idx++) { if ((idx & (idx - 1)) === 0) { ans[idx] = 1; currRoot = idx; continue; } ans[idx] = 1 + ans[i...
Counting Bits
You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible su...
class Solution(object): def minimumIncompatibility(self, nums, k): nums.sort(reverse = True) upperbound = len(nums) // k arr = [[] for _ in range(k)] self.res = float('inf') def assign(i): if i == len(nums): self.res = min(self.res, sum(arr[i][0]-a...
class Solution { public int minimumIncompatibility(int[] nums, int k) { Arrays.sort(nums); k=nums.length/k; int n = nums.length,INF=100; int[][] dp = new int[1<<n][n]; for (int[] d : dp){ Arrays.fill(d, INF); } for (int i=0;i<n;i++){ dp...
const int INF = 1e9; class Solution { public: int minimumIncompatibility(vector<int>& nums, int k) { int i, n = nums.size(), subset_size = n / k; sort(nums.begin(), nums.end()); // Pre-calculate the range (max - min) for each subset of nums // Note that there are (1 << n) subsets (...
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// var minimumIncompatibility = function(n...
Minimum Incompatibility
Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0. A grandparent of a node is the parent of its parent if it exists. &nbsp; Example 1: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 18...
class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: def dfs(root, p, gp): if not root: return 0 if gp and gp.val%2==0: return root.val + dfs(root.left,root,p)+dfs(root.right,root,p) return 0 + dfs(root.left,root,p)+dfs(root.right,root,p) return dfs(root,None,None)
class Solution { int sum=0; public int sumEvenGrandparent(TreeNode root) { dfs(root,null,null); return sum; } void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) { if (current == null) return; // base case if (grandParent != null && grandParent.val % 2 == 0) {...
class Solution { public: void sumGparent(TreeNode* child, int& sum, TreeNode* parent, TreeNode* Gparent){ if(!child) return; if(Gparent) if(Gparent->val % 2 ==0) sum += child->val; sumGparent(child->left, sum, child, parent); sumGparent(child->right, sum, child, parent); } i...
const dfs = function(node, evenParent) { if (!node) return 0; const isEvenNode = node.val % 2 === 0; const left = dfs(node.left, isEvenNode); const right = dfs(node.right, isEvenNode); if (!evenParent) return left + right; return left + right + (node.left ? node.left.val : 0) + (n...
Sum of Nodes with Even-Valued Grandparent
Given a 2D matrix matrix, handle multiple queries of the following type: Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] matrix) Initializes the object with the in...
class NumMatrix: def __init__(self, matrix: List[List[int]]): m, n = len(matrix), len(matrix[0]) # Understand why we need to create a new matrix with extra one row/column self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)] for r in range(1, m + 1): for c ...
class NumMatrix { int mat[][]; public NumMatrix(int[][] matrix) { mat = matrix; int rows = mat.length; int cols = mat[0].length; for(int i = 0; i< rows; i++) { for(int j = 0; j < cols; j++) { if(i > 0) mat[i][j] += mat[i-...
//Using row prefix sum O(m) class NumMatrix { vector<vector<int>> prefix; public: NumMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for(int i = 0;i<m;i++){ vector<int> row(n); row[0] = matrix[i][0]; for(int j = 1;j<n;j++){ ...
/** * @param {number[][]} matrix */ var NumMatrix = function(matrix) { const n = matrix.length, m = matrix[0].length; // n * m filled with 0 this.prefix = Array.from({ length: n}, (_, i) => { return new Array(m).fill(0); }); const prefix = this.prefix; // precompute for(let i = 0; ...
Range Sum Query 2D - Immutable
You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-...
class Solution: def getAverages(self, nums: list[int], k: int) -> list[int]: n, diam = len(nums), 2*k+1 if n < diam: return [-1]*n ans = [-1]*k arr = list(accumulate(nums, initial = 0)) for i in range(n-diam+1): ans.append((arr[i+diam]-arr[i])//diam) ...
class Solution { public int[] getAverages(int[] nums, int k) { if(k == 0) return nums; int N = nums.length; long[] sum = new long[N]; sum[0] = nums[0]; for(int i = 1; i < N; i++) sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i] ...
class Solution { public: vector<int> getAverages(vector<int>& nums, int k) { int n = nums.size(); vector<int> ans(n , -1); if(2 * k + 1 > n) return ans; // Simple Sliding Window long long int sum = 0; // Take a window of size 2 * k + 1 for(int i =0 ; i < ...
var getAverages = function(nums, k) { const twoK = 2 * k; const windowSize = twoK + 1; const result = [...nums].fill(-1); let sum = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (i >= twoK) { result[i - k] = Math.floor(sum / windowSize) sum -=...
K Radius Subarray Averages
Given a positive integer num, write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt. &nbsp; Example 1: Input: num = 16 Output: true Example 2: Input: num = 14 Output: false &nbsp; Constraints: 1 &lt;= num &lt;= 2^31 - 1
class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True lo = 2 hi = num // 2 while lo <= hi: mid = lo + (hi - lo) //2 print(mid) if mid * mid == num: return True if mid * mid > n...
class Solution { public boolean isPerfectSquare(int num) { long start = 1; long end = num; while(start<=end){ long mid = start +(end - start)/2; if(mid*mid==num){ return true; } else if(mid*mid<num){ start = mi...
class Solution { public: bool isPerfectSquare(int num) { if (num == 1)return true; long long l = 1, h = num / 2; while (l <= h) { long long mid = l + (h - l) / 2; long long midSqr = mid * mid; if (midSqr == num) return true; if (num < midSq...
var isPerfectSquare = function(num) { let low = 1; let high = 100000; while(low <= high){ let mid = (low + high) >> 1; let sqrt = mid * mid if( sqrt == num) { return true; }else if(num > sqrt ){ low = mid + 1 }else { high =...
Valid Perfect Square
Given an integer array nums where&nbsp;every element appears three times except for one, which appears exactly once. Find the single element and return it. You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space. &nbsp; Example 1: Input: nums = [2,2,3,2] Output:...
import math class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int [0,-1,1,0] [2,2,3,2] [2,2,3,2] [2,2,3,2] 10 10 11 10 """ total = sum(nums) uniqueTotals = set() ...
class Solution { public int singleNumber(int[] nums) { int[] bitCount = new int[32]; // 32 bit number // Count occurrence of each bits in each num for (int i = 0; i < bitCount.length; i++) { for (int num : nums) { if ((num & 1 << i) != 0) // If ith bit in "num" ...
class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int,int> mp; int ans= 0; for(auto i: nums){ mp[i]++; } for(auto j: mp){ if(j.second == 1){ ans = j.first; break; } } ...
/** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { if(nums.length === 1) return nums[0]; const objNums = {}; for(var indexI=0; indexI<nums.length; indexI++){ if(objNums[nums[indexI]] === 2) delete objNums[nums[indexI]]; else objNums[nums[indexI]] = (obj...
Single Number II
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 &lt;= i &lt; nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). &nbsp; Example 1: Input: nums = [0,2,1,5,3,4] Ou...
class Solution: #As maximum value of the array element is 1000, this solution would work def buildArray(self, nums: List[int]) -> List[int]: for i in range(len(nums)): if nums[nums[i]] <= len(nums): nums[i] = nums[nums[i]] * 1000 + nums[i] else: ...
class Solution { public int[] buildArray(int[] nums) { int n=nums.length; for(int i=0;i<n;i++) nums[i] = nums[i] + n*(nums[nums[i]]%n); for(int i=0;i<n;i++) nums[i] = nums[i]/n; return nums; } }
class Solution { public: vector<int> buildArray(vector<int>& nums) { int n=nums.size(); vector<int> ans(n); for(int i=0;i<n;i++){ ans[i]=nums[nums[i]]; } return ans; } };
var buildArray = function(nums) { return nums.map(a=>nums[a]); };
Build Array from Permutation
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it i...
from collections import defaultdict import re class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: reachable = defaultdict(set) for a, b in mappings: reachable[a].add(b) for c in sub: reachable[c].add(c) regex = "" ...
class Solution { public boolean matchReplacement(String s, String sub, char[][] mappings) { HashMap<Character, HashSet<Character>> m = new HashMap<>(); for(char[] carr: mappings) { if (!m.containsKey(carr[0])){ m.put(carr[0], new HashSet<Character>()); } ...
class Solution { public: bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) { int m(size(s)), n(size(sub)); unordered_map<char, unordered_set<char>> mp; auto doit = [&](int ind) { for (int i=ind, j=0; i<ind+n; i++, j++) { if (s[i] == su...
var matchReplacement = function(s, sub, mappings) { let n= s.length; let m = sub.length; let map = new Array(36).fill().map(_=>new Array(36).fill(0)); for(let i=0;i<mappings.length;i++) { let [o,ne] = mappings[i]; if(isNaN(o)) { o = (o.toUpperCase()).charCodeAt(0)-55; ...
Match Substring After Replacement
Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name. If you add periods '.' between some characters in...
class Solution: def numUniqueEmails(self, emails: List[str]) -> int: def ets(email): s, domain = email[:email.index('@')], email[email.index('@'):] s = s.replace(".", "") s = s[:s.index('+')] if '+' in s else s return s+domain dict = {} for i i...
class Solution { public int numUniqueEmails(String[] emails) { Set<String> finalEmails = new HashSet<>(); for(String email: emails){ StringBuilder name = new StringBuilder(); boolean ignore = false; for(int i=0;i<email.length();i++){ char c = emai...
class Solution { public: int numUniqueEmails(vector<string>& emails) { unordered_set<string> st; for(auto &e:emails) { string clean_email=""; for(auto &ch:e) { if(ch=='+'||ch=='@') break; if(ch=='.') ...
var numUniqueEmails = function(emails) { let set = new Set(); for (let email of emails) { let curr = email.split('@'); let currEmail = ''; for (let char of curr[0]) { if (char === '.') continue; if (char === '+') break; currEmail += char;...
Unique Email Addresses
A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any n...
class Solution: def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: i=0 while True: if i==len(triplets): break for j in range(3): if triplets[i][j]>target[j]: triplets.pop(i) i...
class Solution { public boolean mergeTriplets(int[][] triplets, int[] target) { boolean xFound = false, yFound = false, zFound = false; for(int[] triplet : triplets){ //Current Triplet is target if(triplet[0] == target[0] && triplet[1] == target[1] && tri...
class Solution { public: bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) { int first = 0, second = 0, third = 0; for (auto tr : triplets) { if (tr[0] == target[0] && tr[1] <= target[1] && tr[2] <= target[2]) first = 1; if (tr[0] <= target[0] && tr[1] ==...
var mergeTriplets = function(triplets, target) { let fst = false, snd = false, thrd = false; const [t1, t2, t3] = target; for(let i = 0; i < triplets.length; i++) { const [a, b, c] = triplets[i]; if(a === t1 && b <= t2 && c <= t3) fst = true; if(b === t2 && a <= t1 && c <= t3) ...
Merge Triplets to Form Target Triplet
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queu...
class MyStack: def __init__(self): self.stack = [] def push(self, x): self.stack.append(x) def top(self): return self.stack[-1] def pop(self): return self.stack.pop() def size(self): return len(self.stack) def isEmpty(self): return len(self.st...
class MyQueue { private final Deque<Integer> stack = new ArrayDeque<>(); private final Deque<Integer> temp = new ArrayDeque<>(); /** * Initialize your data structure here. */ public MyQueue() {} /** * Pushes element x to the back of the queue. */ public void push(int x) { ...
class MyQueue { public: stack<int>s1; stack<int>s2; MyQueue() { } void push(int x) { s1.push(x); } int pop() { if(s1.empty() && s2.empty()) return -1; while(s2.empty()){ while(!s1.empty()){ s2.push(s1.top()); s1.pop(...
var MyQueue = function() { this.queue = []; }; /** * @param {number} x * @return {void} */ MyQueue.prototype.push = function(x) { this.queue.push(x); }; /** * @return {number} */ MyQueue.prototype.pop = function() { return this.queue.splice(0, 1); }; /** * @return {number} */ MyQueue.prototype.pe...
Implement Queue using Stacks
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 &lt;= i, j &lt; arr1.length. &nbsp; Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr...
class Solution(object): def maxAbsValExpr(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf') min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),fl...
class Solution { public int maxAbsValExpr(int[] arr1, int[] arr2) { //1. remove the modulas - //i & j are interchangable because they are inside the modulas // A[i] - A[j] + B[i] -B[j] + i-j // A[i] + B[i] + i - B[j] - A[j] - j // (A[i] + B[i] + i) ->X // (B[j] - A[j...
class Solution { public: int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) { int res=0; int n = arr1.size(); vector<int>v1; vector<int>v2; vector<int>v3; vector<int>v4; for(int i=0;i<n;i++) { v1.push_back(i+arr1[i]+arr2[i]); ...
var maxAbsValExpr = function(arr1, arr2) { const l1 = [], l2 = [], l3 = [], l4 = [], res = []; for (let i = 0; i < arr1.length; i++) { l1.push(arr1[i] + arr2[i] + i) l2.push(arr1[i] - arr2[i] + i) l3.push(-arr1[i] + arr2[i] + i) l4.push(-arr1[i] - arr2[i] + i) } ...
Maximum of Absolute Value Expression
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the m...
# 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 distributeCoins(self, root: Optional[TreeNode]) -> int: def dfs(root): if n...
class Solution { int count = 0; public int helper(TreeNode root) { if(root == null) return 0; int left = helper(root.left); int right = helper(root.right); count+= Math.abs(left)+Math.abs(right); return (left+right+root.val-...
class Solution { public: int ans = 0; int recr(TreeNode *root) { if(!root) return 0; int left = recr(root->left); int right = recr(root->right); int curr = root->val + left + right; ans += abs(curr-1); return curr-1; } int distributeCoins(TreeNode* roo...
var distributeCoins = function(root) { var moves = 0; postorder(root); return moves; function postorder(node){ if(!node) return 0; const subTotal = postorder(node.left) + postorder(node.right); const result = node.val - 1 + subTotal; moves += Math.abs(result...
Distribute Coins in Binary Tree
You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is special, otherwise, return -1. It can be proven ...
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() for i in range(max(nums)+1): y=len(nums)-bisect.bisect_left(nums,i) if y==i: return i return -1
class Solution { public int specialArray(int[] nums) { int x = nums.length; int[] counts = new int[x+1]; for(int elem : nums) if(elem >= x) counts[x]++; else counts[elem]++; int res = 0; for(int i = counts.length-1; i ...
class Solution { public: int specialArray(vector<int>& nums) { int v[102]; memset(v, 0, sizeof v); for (const auto &n : nums) { ++v[n > 100 ? 100 : n]; } for (int i = 100; i > 0; --i) { v[i] = v[i + 1] + v[i]; if (v[i] == i) ...
var specialArray = function(nums) { const freq = new Array(1001).fill(0); for(let n of nums) freq[n]++; for(let i=1000, cnt=0; i>=0; i--){ cnt += freq[i]; if(i==cnt) return i; } return -1; };
Special Array With X Elements Greater Than or Equal X
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 3 * x + 1 For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --&gt; 10 --&gt; 5 --&gt; 16 --&gt; 8 --&gt; 4 --&gt; 2 --&gt; ...
import heapq class Solution: def power(self,n): if n in self.dic: return self.dic[n] if n % 2: self.dic[n] = self.power(3 * n + 1) + 1 else: self.dic[n] = self.power(n // 2) + 1 return self.dic[n] def getKth(self, lo: int, hi: int, k: int) ...
class Solution { public int getKth(int lo, int hi, int k) { int p = 0; int[][] powerArr = new int[hi - lo + 1][2]; Map<Integer, Integer> memo = new HashMap<>(); for (int i = lo; i <= hi; i++) powerArr[p++] = new int[]{i, getPower(i, memo)}; Arrays.sort(powerArr...
class Solution { public: int getPower(int num) { if (num == 1) return 0; int res = 0; if (num %2 == 0) res += getPower(num/2); else res += getPower(3*num + 1); res++; return res; } int getKth(int lo, int hi, int k) { ...
var getKth = function(lo, hi, k) { const dp = new Map(); dp.set(1, 0); const powerVals = []; for(let num = lo; num <= hi; ++num) { powerVals.push([num, findPowerVal(num, dp)]); } const heap = new MinHeap(); heap.build(powerVals); let top; while(k--) { // O(klogn) t...
Sort Integers by The Power Value
You are given the root of a full binary tree with the following properties: Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. The evaluation of a node is as follo...
class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: def recur(node): if not node.left and not node.right: #leaf node return True if node.val == 1 else False left = recur(node.left) right = recur(node.right) if node.val == ...
class Solution { public boolean evaluateTree(TreeNode root) { if(root.val == 1) return true; if(root.val == 0) return false; if(root.val == 2) return evaluateTree(root.left) || evaluateTree(root.right); return evaluateTree(root.left) && evaluateTre...
class Solution { public: bool evaluateTree(TreeNode* root) { if (!root->left and !root->right) return root->val; int l = evaluateTree(root->left); int r = evaluateTree(root->right); return (root->val == 2) ? l or r : l and r; } };
/** * @param {TreeNode} root * @return {boolean} */ var evaluateTree = function(root) { return root.val === 3 ? evaluateTree(root.left) && evaluateTree(root.right) : root.val === 2 ? evaluateTree(root.left) || evaluateTree(root.right) : root.val; };
Evaluate Boolean Binary Tree
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, in...
from collections import defaultdict class Set(object): def __init__(self): self._dict = {} self._list = [] self._len = 0 def add(self, v): if v in self._dict: pass else: self._list.append(v) self._dict[v] = self._len sel...
//Intuitions get from the top answer by @AaronLin1992 class AllOne { //Thoughts //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)? //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min ...
class AllOne { public: map<int,unordered_set<string>> minmax; unordered_map<string,int> count; AllOne() { } void inc(string key) { int was = count[key]++; if(was>0) { minmax[was].erase(key); if(minmax[was].size()==0) minmax.erase(was); ...
var AllOne = function() { this.map = new Map(); this.pre = ''; }; /** * @param {set} map * @param {function} handler * @return {map} */ AllOne.prototype.sort = function(map, handler) { return new Map([...map].sort(handler)); }; /** * @param {string} key * @return {void} */ AllOne.prototype.inc = functi...
All O`one Data Structure
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equa...
class Solution(): def atMostNGivenDigitSet(self, digits, n): cache = {} target = str(n) def helper(idx, isBoundary, isZero): if idx == len(target): return 1 if (idx, isBoundary, isZero) in cache: return cache[(idx, isBoundary, isZero)] res = ...
class Solution { // DIGIT DP IS LOVE Integer[][][] digitdp; public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) { if (pos == num.length()) { return 1; } int maxDigit = -1; if(digitdp[pos][(bound==true)?1:0][(lead=...
class Solution { public: using ll = long long; int countLen(int n) { int cnt = 0; while(n) { cnt++; n /= 10; } return cnt; } vector<int>getDigits(int n) { vector<int>digits; while(n) { digits.push_back(n % 10); ...
var atMostNGivenDigitSet = function(digits, n) { const asString = ""+ n; let smaller = 0; let prev = 1; for (let i = asString.length - 1; i >= 0; --i) { const L = asString.length - 1 - i; const num = +asString[i]; let equal = 0; let less = 0; for (let digit of dig...
Numbers At Most N Given Digit Set
You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped...
class Solution: def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool: def find(a1, a2, aCenter): if a1 <= aCenter and aCenter <= a2: return 0 elif a1 > aCenter: return a1 - aCenter ...
class Solution { public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2) + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius; } }
class Solution { public: bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { //nearest_x = x1 when xCenter<x1<x2 (OR) x2 when x1<x2<xCenter (OR) xCenter when x1<xCenter<x2 int nearest_x = (xCenter < x1) ? x1 : (xCenter > x2) ? x2 : xCenter; //same logic ...
var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) { const closestX = clamp(xCenter, x1, x2); const closestY = clamp(yCenter, y1, y2); const dist = (xCenter - closestX)**2 + (yCenter - closestY)**2; return dist <= radius * radius ? true : false; function clamp(...
Circle and Rectangle Overlapping
An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: 0, 1, and 8 rotate to themselves, 2 and 5 ro...
class Solution: def rotatedDigits(self, n: int) -> int: d={ 0:0, 1:1, 2:5, 3:None, 4: None, 5:2, 6:9, 7:None, 8:8, 9:6 } res=0 for i in range(n+1): t=i ...
class Solution { public int rotatedDigits(int n) { int ans=0; for(int i=1; i<=n; i++){ int k = i; boolean bool1=true; boolean bool2=false; while(k>0){ int m=k%10; if(m==3 || m==4 || m==7){ bool1=false; break; } else ...
class Solution { public: bool isValid(int n) { bool check = false; while (n > 0) { int k = n % 10; if (k == 2 || k == 5 || k == 6 || k == 9) check = true; if (k == 3 || k == 4 || k == 7) return false; n /= 10...
/** * @param {number} n * @return {number} */ var rotatedDigits = function(n) { let count=0; for(let i=1;i<=n;i++){ let str=i.toString().split(""); let f=str.filter(s=> s!=1 && s!=0 && s!=8); if(f.length===0) continue; let g=f.filter(s=> s!=5 && s!=2 && s!=6 && s!=9); ...
Rotated Digits
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos a...
class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: arr = [0 for _ in range(2*k+1)] for pos, numOfFruit in fruits: if pos < startPos-k or pos > startPos+k: continue arr[pos-(startPos-k)] += numOfFruit left,...
class Solution { public int maxTotalFruits(int[][] fruits, int startPos, int k) { int n = fruits.length; int posOfLastFruit = fruits[n-1][0]; int prefixArr[] = new int[posOfLastFruit + 1]; int start = Math.max(startPos - k, 0); int end = Math.min(startPos + k, prefixArr.lengt...
class Solution { public: int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) { vector<int> arr; for (int i=0; i<2*k+1; ++i) { arr.push_back(0); } for (int i=0; i<fruits.size(); ++i) { if ((fruits[i][0] < startPos-k) || (fruits[i][0] > startPo...
/** * @param {number[][]} fruits * @param {number} startPos * @param {number} k * @return {number} */ var maxTotalFruits = function(fruits, startPos, k) { let n = Math.max(fruits[fruits.length-1][0], startPos)+1; let numFruits = new Array(n).fill(0); let sums = new Array(n).fill(0); for(let ob...
Maximum Fruits Harvested After at Most K Steps
Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally&nbsp;surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. &nbsp; Example 1: Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] Output: [[...
# The question is an awesome example of multi-source bfs. # The intuition is to add the boundary to a heap if it is 'O'. # Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start # convertin all these 'O's to 'E's. # The la...
class Solution { boolean isClosed = true; public void solve(char[][] board) { int m = board.length; int n = board[0].length; // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value for(int i=0; i<m; i++){ for(int j=0; j<n; j+...
class Solution { public: int n,m; int visited[201][201] = {0}; // Breadth First Search // Flood Fill Algorithm void bfs(vector<vector<char>>& board, int x, int y){ queue<int> q; q.push(m*x+y); visited[x][y] = 1; int curr,i,j; while(!q.empty()){ curr = q.front(...
// time O(n * m) | space O(1) // We essentially invert this question // Instead of looking whether an 'O' node is surrounded, // we check if an 'O' node is on the edge (outer layer can't be surrounded) // and check if that is connected with any other nodes 'O' nodes (top, down, left, right). // We do no care if it is ...
Surrounded Regions
Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1. &nbsp; Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: The only lucky number in the array is 2 because fr...
class Solution: def findLucky(self, arr: List[int]) -> int: dc = {} for i in range(len(arr)): if arr[i] not in dc: dc[arr[i]] = 1 else: dc[arr[i]] = dc[arr[i]] + 1 mx = -1 for key,value in dc.items(): if key...
class Solution { public int findLucky(int[] arr) { HashMap<Integer,Integer> map = new HashMap<>(); for(int i : arr){ map.put(i, map.getOrDefault(i,0)+1); } System.out.print(map); int max = 0; for (Map.Entry<Integer, Integer> e : map.entrySet()){ ...
class Solution { public: int findLucky(vector<int>& arr) { // sort(arr.begin(),arr.end()); map<int,int>mp; vector<int>v; for(int i=0;i<arr.size();i++) { mp[arr[i]]++; } for(auto x:mp) { if(x.first == x.second) { ...
/** * @param {number[]} arr * @return {number} */ var findLucky = function(arr) { let obj = {}; arr.map((num) => { obj[num] = obj[num] + 1 || 1; }); let answer = -1; for (let key in obj) { if (Number(key) === obj[key]) answer = Math.max(answer, Number(key)); } return answer; };
Find Lucky Integer in an Array
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success. A spell and potion pair is considered successful if the product of thei...
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: result = self.function(spells,potions,success) return result def function(self,arr1,arr2,success): n2 = len(arr2) arr2.sort() #Sorting Enables Us To Do Binary Search ...
class Solution { public int[] successfulPairs(int[] spells, int[] potions, long success) { int n = spells.length; int m = potions.length; int[] pairs = new int[n]; Arrays.sort(potions); for (int i = 0; i < n; i++) { int spell = spells[i]; int left = 0;...
class Solution { public: vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) { vector<int> res; int n(size(potions)); sort(begin(potions), end(potions)); for (auto& spell : spells) { int start(0), end(n); ...
/** * @param {number[]} spells * @param {number[]} potions * @param {number} success * @return {number[]} */ var successfulPairs = function(spells, potions, success) { let res = []; potions.sort((a, b) => b-a); let map = new Map(); for(let i=0; i<spells.length; i++){ if(!map.has(spell...
Successful Pairs of Spells and Potions
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside...
class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: m=len(grid) n=len(grid[0]) visited=set() steps=0 q=deque([]) keyCt=0 for i in range(m): for j in range(n): if grid[i][j]=="@": ...
class Solution { private static final int[][] DIRS = new int[][]{ {1,0}, {-1,0}, {0,1}, {0,-1} }; public int shortestPathAllKeys(String[] grid) { int m = grid.length, n = grid[0].length(); int numKeys = 0, startRow = -1, startCol = -1; for(int i=0; i<m; i+...
class Solution { int dirx[4] = {-1,1,0,0}; int diry[4] = {0,0,1,-1}; public: int shortestPathAllKeys(vector<string>& grid) { int n = grid.size(); int m = grid[0].size(); vector<vector<int>> matrix(n, vector<int>(m)); vector<int> lock(7,0); int sx, sy; int lk =...
var shortestPathAllKeys = function(grid) { const n = grid.length; const m = grid[0].length; function isKey(letter) { return ( letter.charCodeAt(0) >= 'a'.charCodeAt(0) && letter.charCodeAt(0) <= 'z'.charCodeAt(0) ); } function isLock(letter) { return ( ...
Shortest Path to Get All Keys
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null...
class Solution: def isValidSerialization(self, preorder: str) -> bool: nodes = preorder.split(',') counter=1 for i, node in enumerate(nodes): if node != '#': counter+=1 else: if counter <= 1 and i != len(nodes) - 1: ...
class Solution { public boolean isValidSerialization(String preorder) { String[] strs = preorder.split(","); //In starting we have one vacany for root int vacancy = 1; for(String str : strs){ if(--vacancy < 0 ) return false; ...
class Solution { public: bool isValidSerialization(string preorder) { stringstream s(preorder); string str; int slots=1; while(getline(s, str, ',')) { if(slots==0) return 0; if(str=="#") slots--; else slots++; } return slots==0; ...
/** * @param {string} preorder * @return {boolean} */ var isValidSerialization = function(preorder) { let balance = 1 for(const node of preorder.split(',')) if (balance > 0) if (node === '#') --balance else ++balance else return false return balance < 1 }
Verify Preorder Serialization of a Binary Tree
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. &nbsp; Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: nu...
class Solution: def canPartition(self, nums: List[int]) -> bool: total = sum(nums) if total % 2: return False total //= 2 leng = len(nums) dp = [[False] * (total + 1) for _ in range(leng + 1)] for i in range(leng + 1): dp[i][0] = True for i in range(1...
class Solution { public boolean canPartition(int[] nums) { int sum = 0; for(int i=0; i<nums.length; i++){ sum = sum+nums[i]; } if(sum%2 !=0){ return false; } int[][] dp = new int[nums.length+1][sum]; for(int i=0; i<dp.length; i+...
class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; int n = nums.size(); for(int i = 0;i<n;i++) sum = sum + nums[i]; cout<<sum; if(sum % 2 == 0){ int s = sum/2; int t[n+1][s+1]; for(int i = 0; ...
var canPartition = function(nums) { let sum = nums.reduce((prevVal, currValue) => prevVal + currValue, 0); // sum of each values if (sum % 2 !== 0) return false; // return false if odd sum let target = sum / 2; // ex.[1,5,11,5] target is half which is 11 let dp = new Set(); // add unique values ...
Partition Equal Subset Sum
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same le...
class Solution: def balancedString(self, s): count = collections.Counter(s) res = n = len(s) if all(n/4==count[char] for char in 'QWER'): return 0 left = 0 for right, char in enumerate(s): # replace char whose index==right to check if it is balanced ...
class Solution { public int balancedString(String s) { int n = s.length(), ans = n, excess = 0; int[] cnt = new int[128]; cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4; for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be remove...
class Solution { public: int balancedString(string s) { int n=s.length(); unordered_map<char,int>umap; for(auto x:s) { umap[x]++; } umap['Q']=umap['Q']-n/4>0?umap['Q']-n/4:0; umap['W']=umap['W']-n/4>0?umap['W']-n/4:0; umap['E']=umap['E']-n/4>0?umap['...
var balancedString = function(s) { let output = Infinity; let map = {"Q":0, "W":0, "E":0, "R":0}; for(let letter of s){ map[letter]++; } let valueGoal = s.length / 4 let remainder = 0; let count = 4; for(let [key, val] of Object.entries(map)...
Replace the Substring for Balanced String
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results:...
class Solution: def guessNumber(self, n: int) -> int: l=1 h=n while l<=h: mid=(l+h)//2 x =guess(mid) if(x==0): return mid elif(x==1): l = mid+1 else: h = mid-1
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n...
class Solution { public: int guessNumber(int n) { int s = 1, e = n; int mid = s + (e - s)/2; while (s <= e){ if (guess(mid) == 0){ return mid; } else if (guess(mid) == -1){ e = mid - 1; }...
/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * var guess = function(num) {} */ /** * @param {number} n * @return {number} */ var gues...
Guess Number Higher or Lower
A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: 1, 3, 5, 7, 9 7...
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: out=[] for i, j in zip(l, r): out.append(self.canMakeArithmeticProgression(nums[i:j+1])) return out def canMakeArithmeticProgression(self, arr: List[int]) -...
class Solution { public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { List<Boolean> result = new ArrayList<>(); int L = nums.length, ll = l.length,ind=0; for(int i=0;i<ll;i++){ int[] arr = new int[r[i]-l[i]+1]; ind=0; for(int k=l[i...
class Solution { public: vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) { vector<bool> ans(l.size(),false); for(int i=0;i<l.size();i++) { //if the sub array size is equal to 2 if(r[i]-l[i]+1==2) ans[i]...
/** * @param {number[]} nums * @param {number[]} l * @param {number[]} r * @return {boolean[]} */ var checkArithmeticSubarrays = function(nums, l, r) { let result = []; for(let i=0;i<l.length;i++) { let subNums = [...nums].slice(l[i], r[i]+1); subNums = subNums.sort((a,b) => a-b); ...
Arithmetic Subarrays
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to f...
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: keys, ans = {}, [] for piece in pieces: keys[piece[0]] = piece for a in arr: if a in keys: ans.extend(keys[a]) return ''.join(map(str, arr)) == ''.join(map...
class Solution { public boolean canFormArray(int[] arr, int[][] pieces) { HashMap<Integer,int[]> hm = new HashMap(); for(int[] list:pieces) hm.put(list[0],list); int index = 0; while(index<arr.length){ if(!hm.containsKey(arr[index])) r...
class Solution { public: bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) { map<int,vector<int>> mp; // map the 1st element in pieces[i] to pieces[i] for(auto p:pieces) mp[p[0]] = p; vector<int> result; for(auto a:arr) { if(mp.find(a)...
var canFormArray = function(arr, pieces) { let total = ""; arr=arr.join(""); for (let i = 0; i < pieces.length; i++) { pieces[i] = pieces[i].join(""); total += pieces[i]; if (arr.indexOf(pieces[i]) == -1) return false; } return total.length == arr.length; };
Check Array Formation Through Concatenation
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. &nbsp; Example 1: Input: n = 27 Output: true Example 2: Input: n = 0 Output: false Example 3: Input: n = 9 Output: true &nbsp; Constraints: ...
class Solution: def isPowerOfThree(self, n: int) -> bool: return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False
class Solution { public boolean isPowerOfThree(int n) { if(n==1){ return true; } if(n<=0){ return false; } if(n%3 !=0 && n>1){ return false; } else{ return isPowerOfThree(n/3); // recurssion } } }
class Solution { public: bool isPowerOfThree(int n) { if(n<=0){return false;} if(n>pow(2, 31)-1 || n<pow(2, 31)*(-1)){return false;} return 1162261467%n==0; } };
var isPowerOfThree = function(n) { if(n === 1){return true;} if(n === 0){return false;} n/=3; if(n%3 != 0 && n != 1){ return false; }else{ let x = isPowerOfThree(n); return x; } };
Power of Three
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landi...
class Solution: def possible(self, i, n, stones, pos, allowedJumps): if i == n - 1: return True key = tuple([i] + allowedJumps) if key in self.cache: return self.cache[key] for jump in allowedJumps: if jump > 0 and stones[i] + jump in pos: ...
class Solution { static boolean flag = false; // If flag is true no more operations in recursion, directly return statement public boolean canCross(int[] stones) { int i = 0; // starting stone int k = 1; // starting jump flag = false; return canBeCrossed(stones, k, i); } ...
class Solution { public: bool canCross(vector<int>& stones) { unordered_map<int,bool>mp; //to see the position where stone is present for(int i=0;i<stones.size();i++) { mp[stones[i]]=true; } int stone=1; //current stone int jump=1; //jump made int last_sto...
var canCross = function(stones) { let hash = {}; function dfs(idx = 0, jumpUnits = 0) { let key = `${idx}-${jumpUnits}`; if (key in hash) return hash[key]; if (idx === stones.length - 1) return true; if (idx >= stones.length) return false; let minJump = jumpUnits - ...
Frog Jump
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection tha...
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: dic = collections.defaultdict(list) for c in connections: u, v = c dic[u].append(v) dic[v].append(u) timer = 0 ...
class Solution { // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from th...
class Solution { int timer = 1; public: void dfs(vector<int>adj[] , int node , int parent , vector<int>&tin , vector<int>&low , vector<int>&vis , vector<vector<int>>&ans) { vis[node] = 1; tin[node] = low[node] = timer; timer++; for(auto it:adj[node]) { if(it == parent) continue; ...
var criticalConnections = function(n, connections) { // Graph Formation const graph = new Map(); connections.forEach(([a, b]) => { const aconn = graph.get(a) || []; const bconn = graph.get(b) || []; aconn.push(b), bconn.push(a); graph.set(a, aconn); graph.set(b, bcon...
Critical Connections in a Network
You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend. You can only attend one...
import bisect from functools import lru_cache class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: if k == 1: # optimization for TLE test case 57/67 return max([event[2] for event in events]) events.sort() event_starts = [event[0] for event in eve...
class Solution { public int maxValue(int[][] events, int k) { Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0])); return maxValue(events, 0, k, 0, new int[k+1][events.length]); } private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEnd...
class Solution { public: int ans; unordered_map<int,unordered_map<int,unordered_map<int,int>>> dp; int Solve(vector<vector<int>>& events, int start, int n, int k, int endtime){ if(k == 0 || start == n){ return 0; } if(dp.find(start) != dp.end() && ...
/** * @param {number[][]} events * @param {number} k * @return {number} */ var maxValue = function(events, k) { events = events.sort((a, b) => a[1] - b[1]); const n = events.length; var ans = 0; var dp = Array.from(Array(k+1), () => new Array(n).fill(0)); for(let i = 0; i < n; i++) { ...
Maximum Number of Events That Can Be Attended II
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position...
class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.rad = radius self.xc = x_center self.yc = y_center def randPoint(self) -> List[float]: while True: xg=self.xc+random.uniform(-1, 1)*self.rad*2 yg=self.yc+random.uni...
class Solution { double radius; double x_center; double y_center; Random r=new Random(); public Solution(double radius, double x_center, double y_center) { this.radius=radius; this.x_center=x_center; this.y_center=y_center; } public double[] randPoint() { ...
class Solution { public: double r,x,y; Solution(double radius, double x_center, double y_center) { r = radius; x = x_center; y = y_center; } vector<double> randPoint() { double x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r); double y_r = ((double)rand()/RAND...
/** * @param {number} radius * @param {number} x_center * @param {number} y_center */ var Solution = function(radius, x_center, y_center) { this.radius = radius; this.x_center = x_center; this.y_center = y_center; }; /** * @return {number[]} */ Solution.prototype.randPoint = function() { const randomX = ...
Generate Random Point in a Circle
You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters. &nbsp; Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated ...
class Solution: def maxRepOpt1(self, text: str) -> int: char_groups = [] for char, group in groupby(text): group_len = len(list(group)) char_groups.append((char, group_len)) char_count = Counter(text) longest_substr_len = 1 # Each ch...
class Solution { public int maxRepOpt1(String s) { int[] count = new int[26]; int[] left = new int[s.length()]; int[] right = new int[s.length()]; int max =0; // Left Array Containing Length Of Subarray Having Equal Characters Till That Index for(int i=0;i<s.length();i++){ count[s.charAt(i...
class Solution { public: int maxRepOpt1(string text) { vector<pair<int, int>> intervals[26]; // a: [st, ed], ..... for(int i = 0; i < text.size();){ int st = i, ed = i; while(i < text.size() && text[i] == text[st]){ ed = i; i++; ...
/** * @param {string} text * @return {number} */ const getLast = (ar)=> ar[ar.length-1]; var maxRepOpt1 = function(text) { let freq = {}; // compute frequency map for(let i=0;i<text.length;i++){ let e=text[i]; !freq[e] && (freq[e]=0); freq[e]++; } let segments = []; ...
Swap For Longest Repeated Character Substring
You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 &lt;= i &lt; n and set the value of arr at index i to x. You may repeat this procedure as many ...
class Solution: def isPossible(self, target: List[int]) -> bool: if len(target) == 1: return target == [1] res = sum(target) heap = [-elem for elem in target] heapify(heap) while heap[0]<-1: maximum = -heappop(heap) res -= maximum ...
class Solution { public boolean isPossible(int[] target) { if(target.length==1) return target[0]==1; PriorityQueue<Integer> que = new PriorityQueue<Integer>(Collections.reverseOrder()); int totsum = 0; for(int i=0;i<target.length;i++){ que.add(target[i]); to...
class Solution { public: bool isPossible(vector<int>& target) { //Priority queue for storing all the nums in taget in decreasing order. priority_queue<int> pq; long long sum = 0; //for storing total sum for(auto num : target){ //adding the nums in pq and sum pq....
var isPossible = function(target) { let max=0 let index=-1 for(let i=target.length-1;i>=0;i--){ if(target[i]>max){ max=target[i] index=i } } if(max===1)return true // if max itself is 1 return true let total=0 for(let i=0;i<target.length;i++){ ...
Construct Target Array With Multiple Sums
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. &nbsp; Example 1: Input: n = 12...
class Solution: def __init__(self): self.perSq = [] def numSquares(self, n): # finding perfect squares up to n i = 1 while i*i <= n: self.perSq.append(i*i) i += 1 return self.lengths(n) # algorithm to find sum from perfect squares def o...
class Solution { public int numSquares(int n) { ArrayList<Integer> perfect_squares = new ArrayList<>(); int i=1; while(i*i <= n){ perfect_squares.add(i*i); i++; } Integer[][] dp = new Integer[n+1][perfect_squares.size()+1]; int answer ...
class Solution { public: int numSquares(int n) { vector<int> perfectSq; for(int i = 1; i*i <= n; ++i){ perfectSq.push_back(i*i); } int m = perfectSq.size(); vector<vector<int>> dp( m+1, vector<int>(n+1, 0)); dp[0][0] = 0...
var numSquares = function(n) { let dp = new Array(n+1).fill(Infinity); dp[0] = 0; for(let i=1; i <= n; i++){ for(let k=1; k*k <= i; k++){ dp[i] = Math.min(dp[i],dp[i - (k*k)] + 1); } } return dp[n]; };
Perfect Squares
Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different i...
class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: def dfs(i,val): if maxBit == val : return 1<<(len(nums)-i) if i == len(nums): return 0 return dfs(i+1,val|nums[i]) + dfs(i+1,val) maxBit = 0 for i in nums: maxBit |= i re...
class Solution { public int countMaxOrSubsets(int[] nums) { subsets(nums, 0, 0); return count; } int count = 0; int maxOR = 0; private void subsets(int[] arr, int vidx, int OR){ if(vidx == arr.length){ if(OR == maxOR){ ...
class Solution { public: int countMaxOrSubsets(vector<int>& nums) { int i,j,max_possible_or=0,n=nums.size(),ans=0; //maximum possible or=or of all number in array for(i=0;i<n;i++) { max_possible_or=nums[i]|max_possible_or; } //ch...
/** * @param {number[]} nums * @return {number} */ var countMaxOrSubsets = function(nums) { let n = nums.length; let len = Math.pow(2, n); let ans = 0; let hash = {}; for (let i = 0; i < len; i++) { let tmp = 0; for (let j = 0; j < n; j++) { if(i & (1 << j)) { ...
Count Number of Maximum Bitwise-OR Subsets
Given an integer array nums, find three numbers whose product is maximum and return the maximum product. &nbsp; Example 1: Input: nums = [1,2,3] Output: 6 Example 2: Input: nums = [1,2,3,4] Output: 24 Example 3: Input: nums = [-1,-2,-3] Output: -6 &nbsp; Constraints: 3 &lt;= nums.length &lt;=&nbsp;104 -1000 &lt;=...
class Solution: def maximumProduct(self, nums: List[int]) -> int: # TC = O(NlogN) because sorting the array # SC = O(1); no extra space needed; sorting was done in place. # sorting the array in descending order nums.sort(reverse = True) # maximum product ca...
class Solution { public int maximumProduct(int[] nums) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE; for (int n: nums) { if (n <= min1) { min2 = min1; min...
class Solution { public: int maximumProduct(vector<int>& nums) { int min1 = INT_MAX , min2 = INT_MAX; // Both have the maximum value that is +infinte int max1 = INT_MIN, max2 = INT_MIN , max3 = INT_MIN; //All these have the minimum value that is -infinte //now finding all these value above...
var maximumProduct = function(nums) { nums.sort((a, b) => a-b) var lastNumber = nums.length - 1 var midNumber = nums.length - 2 var firstNumber = nums.length - 3 var total = nums[lastNumber] * nums[midNumber] * nums[firstNumber] return total };
Maximum Product of Three Numbers
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent ele...
class FreqStack: def __init__(self): self.cnt = {} self.maxcount = 0 self.stack = {} def push(self, val: int) -> None: count = self.cnt.get(val,0)+1 self.cnt[val] = count if count>self.maxcount: self.maxcount = count self.stack[count] = [...
class Node{ int data, freq, time; Node(int data, int freq, int time){ this.data=data; this.freq=freq; this.time=time; } } class CompareNode implements Comparator<Node>{ @Override public int compare(Node a, Node b){ if(a.freq-b.freq==0){ return b.time-a.ti...
class FreqStack { public: unordered_map<int,int> ump; unordered_map<int,stack<int>> ump_st; int cap=1; FreqStack() { ump.clear(); ump_st.clear(); } void push(int val) { //increasing the count if(ump.find(val)!=ump.end()) { ump[val]++...
var FreqStack = function() { //hashMap to keep track of the values being repeated this.frequencyMap = {}; //List map to keep track of the sequence of the value being entered this.listMap = {}; //Max Frequency variable to keep track of the max frequency this.maxValueFrequency = 0; }; /** * @p...
Maximum Frequency Stack
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip ...
class Solution: def minBitFlips(self, s: int, g: int) -> int: count = 0 while s or g: if s%2 != g%2: count+=1 s, g = s//2, g//2 return count
class Solution { public static int minBitFlips(int a1, int a2) { int n = (a1 ^ a2); int res = 0; while (n != 0) { res++; n &= (n - 1); } return res; } }
class Solution { public: int minBitFlips(int start, int goal) { return __builtin_popcount(start^goal); } };
var minBitFlips = function(start, goal) { return (start^goal).toString(2).split("0").join("").length; };
Minimum Bit Flips to Convert Number
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given ...
class Solution: def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: in_degree=defaultdict(int) graph=defaultdict(list) latest=[0]*(n+1) for u,v in relations: graph[u].append(v) in_degree[v]+=1 q=[] for i in range(...
class Solution { public int minimumTime(int n, int[][] relations, int[] time) { List<Integer> adj[] = new ArrayList[n]; int indegree[] = new int[n]; int completionTime[] = new int[n]; for(int i=0; i<n; i++) adj[i] = new ArrayList<>(); for(int relation[]: relations){ ...
class Solution { public: int minimumTime(int n, vector<vector<int>>& relations, vector<int>& time) { vector<vector<int>> adjList(n); vector<int> inDegree(n),cTime(n,0); for(auto &r:relations) { // Create adjacency list and in degree count vectors. adjList[r[0]-1].push_back(r[1]-...
/** * @param {number} n * @param {number[][]} relations * @param {number[]} time * @return {number} */ var minimumTime = function(n, relations, time) { /* Approach: We can create reverse edges for relation. &nbsp; &nbsp; Then longest path(by weightage of time for each node) from the node will be the minimu...
Parallel Courses III
Given an array of integers arr. We want to select three indices i, j and k where (0 &lt;= i &lt; j &lt;= k &lt; arr.length). Let's define a and b as follows: a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k] Note that ^ denotes the bitwise-xor operation. Return the number of tri...
class Solution: def countTriplets(self, arr: List[int]) -> int: s = [0] n = len(arr) if n <= 1: return 0 for i in range(n): s.append(s[-1]^arr[i]) # a = s[i] ^ s[j], b = s[j] ^ s[k+1] count = defaultdict(int) # a = b <-> a ^ b == 0 <...
class Solution { public int countTriplets(int[] arr) { int count=0; for(int i=0;i<arr.length;i++){ int val=0; val=val^arr[i]; for(int k=i+1;k<arr.length;k++){ val=val ^ arr[k]; if(val==0) count+=k-i; } } ...
class TrieNode { public: int numOfIndex; int sumOfIndex; TrieNode* child[2]; TrieNode() : numOfIndex(0), sumOfIndex(0) { child[0] = NULL; child[1] = NULL; } }; class Solution { public: void addNumber(TrieNode* root, int num, int idx){ for( int i = 31; i >= 0; i--){ ...
/** * @param {number[]} arr * @return {number} */ var countTriplets = function(arr) { let count = 0 for(let i=0;i<arr.length;i++){ let xor = arr[i] for(let j=i+1;j<arr.length;j++){ xor ^= arr[j] if(xor == 0){ count += (j-i) } } }...
Count Triplets That Can Form Two Arrays of Equal XOR
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the...
class Solution: def calPoints(self, ops: List[str]) -> int: temp = [] for i in ops: if i!="C" and i!="D" and i!="+": temp.append(int(i)) elif i=="C": temp.remove(temp[len(temp)-1]) elif i=="D": temp.append(2*temp[len...
class Solution { public int calPoints(String[] ops) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < ops.length; i++){ switch(ops[i]){ case "C": list.remove(list.size() - 1); break; case "...
class Solution { public: int calPoints(vector<string>& ops) { stack<int>st; int n = ops.size(); for(int i=0;i<n;i++){ if(ops[i] == "C"){ st.pop(); } else if (ops[i] =="D"){ st.push(st....
//Plus sign in the below algo confirms that the data type we are getting is integer. So, instead of adding it as a string, the data type will be added as integer var calPoints = function(ops) { let stack = []; for(let i = 0; i < ops.length; i++){ if(ops[i] === "C") stack.pop(); else...
Baseball Game
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. &nbsp; Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330" &...
from functools import cmp_to_key class Solution: def largestNumber(self, nums: List[int]) -> str: nums = list(map(str, nums)) nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0)))) res = "".join(nums) return res...
class Solution { public String largestNumber(int[] nums) { String[] arr=new String[nums.length]; for(int i=0;i<nums.length;i++){ arr[i]=Integer.toString(nums[i]); } Arrays.sort(arr,(a,b)->(b+a).compareTo(a+b)); if(arr[0].equals("0")) return "0"; StringBuil...
class Solution { public: string largestNumber(vector<int>& nums) { sort(nums.begin(),nums.end(),[&](int a,int b){ string order1 = to_string(a)+to_string(b); string order2 = to_string(b)+to_string(a); return order1>order2; }); string ans = ""; ...
var largestNumber = function(nums) { var arr=[] nums.forEach((item)=>{ arr.push(item.toString()); }) arr.sort((a,b)=>(b+a).localeCompare(a+b)); var ret="" if(arr[0]=="0") return "0"; arr.forEach((item)=>{ ret+=item; }) return ret; };
Largest Number
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. Note that the same word in the dictionary may be reused multiple times in the segmentation. &nbsp; Example 1: Input: s = "catsand...
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ dic = defaultdict(list) for w in wordDict: dic[w[0]].append(w) result = [] def recursion(idx , ans): ...
class Solution { List<String> res = new ArrayList<>(); String s; int index = 0; Set<String> set = new HashSet<>(); public List<String> wordBreak(String s, List<String> wordDict) { this.s = s; for (String word: wordDict) set.add(word); backtrack(""); return res; } public void backtrack(String ...
class Solution { public: void helper(string s, unordered_set<string>& dict,int start, int index,string current,vector<string>& ans){ if(start==s.size()){ ans.push_back(current); return; } if(index==s.size()) return; string sub=s.substr(start,index-start+1); ...
var wordBreak = function(s, wordDict) { const n = s.length; const result = []; const findValidSentences = (currentString = '', remainingString = s, currentIndex = 0) => { if(currentIndex === remainingString.length) { if(wordDict.includes(remainingString)) { result.push(`...
Word Break II
You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 &lt;= i &lt; n - 1. Retur...
class Solution: def waysToSplitArray(self, nums: List[int]) -> int: prefix_sum = [nums[0]] n = len(nums) for i in range(1, n): prefix_sum.append(nums[i] + prefix_sum[-1]) count = 0 for i in range(n-1): if prefix_sum[i] >= prefix_sum[n-1] - pr...
class Solution { public int waysToSplitArray(int[] nums) { long sum = 0; for(int i : nums){ sum+=i; } int sol = 0; long localSum = 0; for(int i=0; i<nums.length-1;i++){ localSum += nums[i]; if(localSum >= sum-localSum){ ...
class Solution { public: int waysToSplitArray(vector<int>& nums) { long long sumFromBack(0), sumFromFront(0); for (auto& i : nums) sumFromBack += i; int n(size(nums)), res(0); for (auto i=0; i<n-1; i++) { sumFromFront += nums[i]; // sum of the first i + 1 elements ...
/** * @param {number[]} nums * @return {number} */ var waysToSplitArray = function(nums) { let result = 0; let letsum = 0; let rightsum = nums.reduce((a,b)=> a+b); let end = nums.length-1; for (let i = 0;i<end;i++) { letsum+=nums[i]; rightsum-=nums[i]; if (letsum>=rightsum...
Number of Ways to Split Array
You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is cov...
class Solution: def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: t=[0]*(60) for i in ranges: t[i[0]]+=1 t[i[1]+1]-=1 for i in range(1,len(t)): t[i] += t[i-1] ...
class Solution { public boolean isCovered(int[][] ranges, int left, int right) { boolean flag = false; for (int i=left; i<=right; i++) { for (int[] arr: ranges) { if (i >= arr[0] && i <= arr[1]) { flag = true; break; ...
class Solution { public: bool isCovered(vector<vector<int>>& ranges, int left, int right) { int n = ranges.size(); sort(ranges.begin(), ranges.end()); if(left < ranges[0][0]) //BASE CASE return false; bool ans = false; ...
var isCovered = function(ranges, left, right) { var map=new Map() for(let i=left;i<=right;i++){ map.set(i,0) } for(let range of ranges){ for(let i=range[0];i<=range[1];i++){ map.set(i,1) } } // console.log(map) for(let key of map.keys()){ if(map.get(key)===0) return fal...
Check if All the Integers in a Range Are Covered
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). &nbsp; Example 1: Input: x = 123 Output: 321 Exa...
import bisect class Solution: def reverse(self, x: int) -> int: flag = 0 if x<0: x = abs(x) flag = 1 l = [i for i in str(x)] l.reverse() ret = ''.join(l) ret = int(ret) if flag == 1: ret = ret...
class Solution { public int reverse(int x) { long reverse = 0; while (x != 0) { int digit = x % 10; reverse = reverse * 10 + digit; x = x / 10; } if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0; return (int) reverse...
class Solution { public: int reverse(int x) { long res = 0; while (abs(x) > 0) { res = (res + x % 10) * 10; x /= 10; } x < 0 ? res = res / 10 * -1 : res = res / 10; if (res < INT32_MIN || res > INT32_MAX) { res = 0; } return...
var reverse = function(x) { let val = Math.abs(x) let res = 0 while(val !=0){ res = (res*10) + val %10 val = Math.floor(val/10) } if(x < 0)res = 0 - res return (res > ((2**31)-1) || res < (-2)**31) ? 0 : res };
Reverse Integer
Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cos...
class Solution: def minCost(self, n: int, cuts: List[int]) -> int: cuts = [0] + sorted(cuts) + [n] k = len(cuts) dp = [[float('inf')] * k for _ in range(k)] for l in range(1, k + 1): for beg in range(k - l): end = beg + l if l == 1: ...
class Solution { public int minCost(int n, int[] cuts) { int len = cuts.length; Arrays.sort(cuts); int[] arr = new int[len+2]; for(int i = 1 ; i <= len ; i++) arr[i] = cuts[i-1]; arr[0] = 0; arr[len+1] = n; int[]...
class Solution { public: long cutMin(int i, int j, vector<int>&c, vector<vector<int>>&dp) { if(i>j) return 0; if(dp[i][j]!=-1) return dp[i][j]; long mini = INT_MAX; for(int ind=i;ind<=j;ind++) { long cost = c[j+1]-c[i-1]+cutMin(i,ind-1,c,dp)+cutMin(ind+1,j,c,d...
var minCost = function(n, cuts) { cuts = cuts.sort((a, b) => a - b); let map = new Map(); // Use cutIdx to track the idx of the cut position in the cuts array function dfs(start, end, cutIdx) { let key = `${start}-${end}`; if (map.has(key)) return map.get(key); let min = Infinity...
Minimum Cost to Cut a Stick
Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. &...
class Solution: """ Top Down recursion approach: it is sub optimal """ def __init__(self): self.max_diameter = 0 def diameter(self, root): if root is None: return 0 return self.max_depth(root.left) + self.max_depth(root.right) def max_depth(self, root): ...
class Solution { // Declare Global Variable ans to 0 int ans = 0; // Depth First Search Function public int dfs(TreeNode root) { if(root == null) return 0; // recursive call for left height int lh = dfs(root.left); // recursive call for right height int rh = dfs(r...
class Solution { public: int diameterOfBinaryTree(TreeNode* root) { int diameter = 0; height(root, diameter); return diameter; } private: int height(TreeNode* node, int& diameter) { if (!node) { return 0; } int lh = height(node->left, diameter); ...
function fastDiameter(node) { if(node == null) { let pair = new Array(2).fill(0) pair[0] = 0 pair[1] = 0 return pair } let leftPair = fastDiameter(node.left) let rightPair = fastDiameter(node.right) let leftDiameter = leftPair[0] let rightDiameter = righ...
Diameter of Binary Tree
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. &nbsp; Example 1: Input: s = "tree" Output: "eert" Explanation: 'e' appear...
class Solution: def frequencySort(self, s: str) -> str: di = Counter(s) #it wont strike immediately that this is a heap kind of question. heap = [] heapq.heapify(heap) for key,val in di.items(): heapq.heappush(heap,(-1*val,key)) # n = len(s) res = ...
class Solution { public String frequencySort(String s) { HashMap<Character,Integer> hm1=new HashMap<>(); TreeMap<Integer,ArrayList<Character>> hm2=new TreeMap<>(Collections.reverseOrder()); for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(hm1.containsKey(c))...
class Solution { public: string frequencySort(string s) { unordered_map<char,int>mp; for(int i=0;i<s.length();i++) //get the frequency of every char of the string { mp[s[i]]++; } priority_queue<pair<int,char>>pq; //store the freq and char pair in max heap ...
var frequencySort = function(s) { let obj = {} for(const i of s){ obj[i] = (obj[i] || 0) +1 } let sorted = Object.entries(obj).sort((a,b)=> b[1]-a[1]) return sorted.map((e)=> e[0].repeat(e[1])).join('') };
Sort Characters By Frequency
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character &nbsp; Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: h...
from functools import cache class Solution: def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) @cache def dp(i, j): if i == 0: return j if j == 0: return i l1, l2 = wo...
class Solution { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int dp[][] = new int[m][n]; for(int i=0 ; i<m ; i++){ for(int j=0 ; j<n ; j++){ dp[i][j] = -1; } } return...
class Solution { public: int minDistance(string word1, string word2) { int m = word1.size(), n = word2.size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 1; i <= m; i++) { dp[i][0] = i; } for (int j = 1; j <= n; j++) { dp[0][j] ...
var minDistance = function(word1, word2) { const m = word1.length; const n = word2.length; const memo = new Array(m).fill().map(() => new Array(n)); const dfs = (i = m - 1, j = n - 1) => { if(i < 0 && j < 0) return 0; if(i < 0 && j >= 0) return j + 1; if(i >= 0 && j < 0) return ...
Edit Distance
Given a&nbsp;square&nbsp;matrix&nbsp;mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. &nbsp; Example 1: Input: mat = [[1,2,3], &nbsp; [4,5,6], &nbsp; ...
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: n = len(mat) mid = n // 2 summation = 0 for i in range(n): # primary diagonal summation += mat[i][i] # secondary diago...
class Solution { public int diagonalSum(int[][] mat) { int sum1 = 0; int sum2 = 0; int n = mat.length; for(int i = 0 ; i < n ; i++) { sum1 += mat[i][i]; sum2 += mat[i][n-i-1]; } int res = sum1 + sum2; if(n%2 != 0) { ...
class Solution { public: int diagonalSum(vector<vector<int>>& mat) { int n = mat.size() ; int ans = 0 ; for(int i = 0 ; i < n ; i++){ ans = ans + mat[i][i] + mat[i][n - i - 1] ; } ans = (n & 1) ? ans - mat[n/2][n/2] : ans ;//if n is odd then we have to subtract mat[n/2][n/2] from...
var diagonalSum = function(mat) { return mat.reduce((acc, matrix, i)=>{ const matrixlength = matrix.length-1; return acc += (i !== matrixlength-i) ? matrix[i]+ matrix[matrixlength-i] : matrix[i]; },0) }; /* */
Matrix Diagonal Sum
A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always cons...
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ nums = [-2**32]+nums+[-2**32] l,r = 0,len(nums)-1 while l <=r: m = (l+r)//2 # we find the target: if nums[m] > nums[m-1] and nums[m] >...
class Solution { public int findPeakElement(int[] nums) { int start = 0; int end = nums.length - 1; while(start < end){ int mid = start + (end - start) / 2; if(nums[mid] > nums[mid + 1]){ //It means that we are in decreasing part of the array ...
class Solution { public: int findPeakElement(vector<int>& nums) { int peak = 0; for(int i=1; i<nums.size(); i++) { if(nums[i]>nums[i-1]) peak = i; } return peak; } };
/** * @param {number[]} nums * @return {number} */ var findPeakElement = function(nums) { if(nums.length === 1) return 0; const recursion = (startIndex, endIndex) => { const midIndex = Math.floor((startIndex + endIndex)/2); if (startIndex === endIndex) return startIndex; if (startIndex + 1 === e...
Find Peak Element
You are given a string s. A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same. Return the number of good splits you can make in s. &nbsp; Example 1: ...
class Solution: def numSplits(self, s: str) -> int: one = set() two = set() dic = {} for i in s: dic[i] = dic.get(i, 0) + 1 two.add(i) tot = 0 for i in s: one.add(i) dic[i] -= 1 if dic[i] ==...
class Solution { public int numSplits(String s) { int a[] = new int[26]; int b[] = new int[26]; int ds1=0,ds2=0; int count=0; for(int i=0;i<s.length();i++) { b[s.charAt(i)-97]++; if(b[s.charAt(i)-97] == 1) ds2++; } ...
class Solution { public: int numSplits(string s) { int n=s.size(); vector<int>left(26,0); vector<int>right(26,0); int left_count=0,right_count=0; int splits=0; for(auto &it:s){ right[it-'a']++; if(right[it-'a']==1)right_count++; } ...
var numSplits = function(s) { let n = s.length; let preFix = new Array(n) , suFix = new Array(n); let preSet = new Set(); let suSet = new Set(); for(let i=0; i<n ; i++){ preSet.add(s[i]); suSet.add(s[n-1-i]); preFix[i]= preSet.size; ...
Number of Good Ways to Split a String
Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 &lt;= i &lt; j &lt; nums.length and low &lt;= (nums[i] XOR nums[j]) &lt;= high. &nbsp; Example 1: Input: nums = [1,4,2,7], low = 2, high = 6 Output: 6 Explanation: All nice pair...
from collections import defaultdict class TrieNode: def __init__(self): self.nodes = defaultdict(TrieNode) self.cnt = 0 class Trie: def __init__(self): self.root = TrieNode() def insert(self, val): cur = self.root for i in reversed(range(15)): bit = va...
class Solution { public int countPairs(int[] nums, int low, int high) { Trie trie=new Trie(); int cnt=0; for(int i=nums.length-1;i>=0;i--){ // count all the element whose xor is less the low int cnt1=trie.maxXor(nums[i],low); // count all the element whose...
struct Node { Node* arr[2]; int count = 0; bool contains(int bitNo) { return arr[bitNo] != NULL; } void put(int bitNo, Node* newNode) { arr[bitNo] = newNode; } Node* getNext(int bitNo) { return arr[bitNo]; } int getCount(int bitNo) { return arr[bit...
var countPairs = function(nums, low, high) { function insert(num){ var node = root; for(i = 14; i>=0; i--) { var bit = (num >> i) & 1; if(!node.children[bit]) { node.children[bit] = new TrieNode(); } node.children[bi...
Count Pairs With XOR in a Range
A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val. Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine...
class Solution: """ approach: given a, we can get the inorder traversal of it, then append val to it and then construct the tree back """ def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: inorder_list = [] def inorder(root): if not...
class Solution { public TreeNode insertIntoMaxTree(TreeNode root, int val) { if (root==null) return new TreeNode(val); if (val > root.val) { TreeNode newRoot = new TreeNode(val); newRoot.left = root; return newRoot; } root.right = insertIntoMaxTree...
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) ...
/** * @param {TreeNode} root * @param {number} val * @return {TreeNode} */ var insertIntoMaxTree = function(root, val) { // get new node var node = new TreeNode(val); // no root if(!root) { return node; } // upward derivation if val larger then root if(val > root.val) { ...
Maximum Binary Tree II
Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i &gt; 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For...
class Solution: def findKthBit(self, n: int, k: int) -> str: i, s, hash_map = 1, '0', {'1': '0', '0': '1'} for i in range(1, n): s = s + '1' + ''.join((hash_map[i] for i in s))[::-1] return s[k-1]
class Solution { private String invert(String s){ char [] array=s.toCharArray(); for(int i=0;i<s.length();i++){ if(array[i]=='1'){ array[i]='0'; } else{ array[i]='1'; } } return new String(array); } ...
class Solution { public: string Reverse(string s){ for(int i=0;i<s.length()/2;i++){ swap(s[i],s[s.length()-1-i]); } return s; } string invert(string s){ for(int i=0;i<s.length();i++){ if(s[i]=='1') s[i]='0'; else s[i]='1'; } ...
var findKthBit = function(n, k) { return recursivelyGenerate(n-1)[k-1]; } function recursivelyGenerate(bitLength, memo=new Array(bitLength+1)){ if(bitLength===0) return "0"; if(memo[bitLength]) return memo[bitLength]; const save = recursivelyGenerate(bitLength-1); memo[bitLength] = save + '1' + rev...
Find Kth Bit in Nth Binary String
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. You can move according to these rules: In 1 second, you can either: move vertically by one&nbsp;unit, move horizontally by one unit, or m...
class Solution: def minTimeToVisitAllPoints(self, points): res = 0 n = len(points) for i in range(n-1): dx = abs(points[i+1][0]-points[i][0]) dy = abs(points[i+1][1]-points[i][1]) res+= max(dx,dy) return res obj = Solution() print(obj...
class Solution { public int minTimeToVisitAllPoints(int[][] points) { int max = 0, x, y; for(int i = 0; i < points.length - 1; i++){ for(int j = 0; j < points[i].length - 1; j++){ x = Math.abs(points[i][j] - points[i+1][j]); y = Math.abs(points[i][j+1] - p...
class Solution { public: int minTimeToVisitAllPoints(vector<vector<int>>& points) { vector<int>sk; int x,y,maxy=0; for(int i=0;i<points.size()-1;i++){ for(int j=0;j<points[i].size()-1;j++){ x=abs(points[i][j]-points[i+1][j]); y=abs(points[i][j+1]-p...
/** * @param {number[][]} points * @return {number} */ var minTimeToVisitAllPoints = function(points) { let sum = 0; for(let i=1; i<points.length; i++){ sum += Math.max(Math.abs(points[i][0] - points[i-1][0]) , Math.abs(points[i][1] - points[i-1][1])); } return sum; };
Minimum Time Visiting All Points
You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: The greatest common divisor of any adjacent values in the sequence is equal to 1. There is at least a gap of 2 rolls between equal va...
mod=1000000007 @cache def func(n,prev,pp): if n==0: return 1 ans=0 for i in range(1,7): if prev==-1: ans+=func(n-1,i,prev) ans=ans%mod elif pp==-1: if(math.gcd(i,prev)==1 and i!=prev): ans+=func(n-1,i,prev) ans=ans%m...
class Solution { static long[][] dp; public int distinctSequences(int n) { if(n==1) return 6; int mod = 1_000_000_007; dp =new long[][] { {0,1,1,1,1,1}, {1,0,1,0,1,0}, {1,1,0,1,1,0}, {1,0,1,0,...
class Solution { private: int mod = 1e9+7; int f(int ind,int prev1,int prev2,int n){ //Base Case if(ind == n) return 1; int ans = 0; for(int i = 1;i <= 6;i++) //Exploring all possible values if(prev1 != i && prev2 != i && (prev1 == 0 || __gcd(prev1,i) == 1)) ans = (ans + f(ind+1,i,prev1,n))%mod; r...
var distinctSequences = function(n) { // 3D DP [n + 1][7][7] => rollIdx, prev, prevPrev const dp = Array.from({ length: n + 1}, () => { return new Array(7).fill(0).map(() => new Array(7).fill(0)); }); const gcd = (a, b) => { if(a < b) [b, a] = [a, b]; while(b) { let ...
Number of Distinct Roll Sequences
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid...
class Solution: def numOfWays(self, n: int) -> int: two_c_options = 6 tot_options = 12 for i in range(n-1): temp = tot_options tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4) two_c_options = (two_c_options * 3) + ((temp - two_c_opti...
class Solution { int MOD = 1000000007; int[][] states = {{0,1,0},{1,0,1},{2,0,1}, {0,1,2},{1,0,2},{2,0,2}, {0,2,0},{1,2,0},{2,1,0}, {0,2,1},{1,2,1},{2,1,2}}; HashMap<Integer, List<Integer>> nextMap = new HashMap<>(); Long[][] memo; ...
class Solution { public: int numOfWays(int n) { int mod=1e9+7; long long c2=6,c3=6; for(int i=2;i<=n;i++){ long long temp=c3; c3=(2*c3+2*c2)%mod; c2=(2*temp+3*c2)%mod; } return (c2+c3)%mod; } };
/** * @param {number} n * @return {number} */ var numOfWays = function(n) { const mod = Math.pow(10, 9) + 7; const dp212 = [6]; const dp123 = [6]; for (let i = 1; i < n; i++) { // two sides same dp212[i] = (dp212[i - 1] * (5 - 2) + dp123[i - 1] * (6 - 2 - 1 - 1)) % mod; // three different colors ...
Number of Ways to Paint N × 3 Grid
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. R...
import heapq class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: adjlist = [[] for _ in range(n+1)] for src, dst, weight in times: adjlist[src].append((dst, weight)) visited = [-1]*(n+1) captured =[-1]*(n+1...
class Solution { HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>(); public int networkDelayTime(int[][] times, int n, int k) { for (int i = 1; i <= n; i++) { map.put(i, new HashMap<>()); } for (int i = 0; i < times.length; i++) { map.get(times[i][0...
class cmp{ public: bool operator()(pair<int,int> &a,pair<int,int> &b) { return a.second>b.second; } }; class Solution { public: int networkDelayTime(vector<vector<int>>& times, int n, int k) { vector<pair<int,int>> a[n]; for(auto it:times) { a[it[0]-1].push...
/** * @param {number[][]} times * @param {number} n * @param {number} k * @return {number} */ let visited,edges,dijkastra_arr,min_heap const MAX_VALUE=Math.pow(10,6); const dijkastra=(source)=>{ visited[source]=true; min_heap.pop(); let nei=edges[source]||[]; // if(!nei.length)return; for(let...
Network Delay Time
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. &nbsp; Example 1: Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Example 2: Input: head = [1,1,1,2,3] Output: [2,3] &nbsp; Constraints:...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: if (not head): return None result = tail = L...
class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) return head; ListNode temp = head; int last = -1; int[]array = new int[201]; // zero == index 100 // one == index 101; // -100 == index 0; while (temp != null){ ...
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* k=new ListNode(); ListNode *root=k,*cur=head; while(cur!=NULL) { ListNode *t=cur; while(t->next!=NULL && t->next->val==t->val) t=t->next; if(t==cur) ...
var deleteDuplicates = function(head) { let map = new Map() let result = new ListNode(-1) let newCurr = result let curr = head while(head){ if(map.has(head.val)){ map.set(head.val, 2) }else{ newArr.push(head.val) map.set(head.val, 1)...
Remove Duplicates from Sorted List II
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, a...
class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: n = len(graph) dist = [[inf]*n for _ in range(n)] for i, x in enumerate(graph): dist[i][i] = 0 for ii in x: dist[i][ii] = 1 # floyd-warshall for k in range...
class Solution { class Pair { int i; int path; public Pair(int i, int path) { this.i = i; this.path = path; } } public int shortestPathLength(int[][] graph) { /* For each node currentNode, steps as key, visited as value boolean[...
class Solution { public: int shortestPathLength(vector<vector<int>>& graph) { int n = graph.size(); string mask = ""; string eq = ""; for(int i=0; i<n; i++){ mask += '0'; eq += '1'; } queue<pair<int,string>>q; set<pair<int,string>>s; ...
/** * @param {number[][]} graph * @return {number} */ var shortestPathLength = function(graph) { const n = graph.length; const allVisited = (1 << n) - 1; const queue = []; const visited = new Set(); for (let i = 0; i < n; i++) { queue.push([1 << i, i, 0]); visited.add((1 << i) * ...
Shortest Path Visiting All Nodes
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. &nbsp; Example 1: Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1]. Example 2: Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Ou...
class Solution: def findLength(self, nums1: List[int], nums2: List[int]) -> int: dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)] max_len = 0 for row in range(len(nums2)): for col in range(len(nums1)): if nums2[row] == nums1[col]: dp[r...
class Solution { public int findLength(int[] nums1, int[] nums2) { int n= nums1.length , m = nums2.length; int[][] dp = new int [n+1][m+1]; // for(int [] d: dp)Arrays.fill(d,-1); int ans =0; for(int i =n-1;i>=0;i--){ for(int j = m-1 ;j>=0;j--){ ...
class Solution { public: int findLength(vector<int>& nums1, vector<int>& nums2) { int n1 = nums1.size(); int n2 = nums2.size(); //moving num2 on num1 int ptr2 = 0; int cnt = 0; int largest = INT_MIN; for(...
var findLength = function(nums1, nums2) { let dp = new Array(nums1.length+1).fill(0).map( () => new Array(nums2.length+1).fill(0) ) let max = 0; for (let i = 0; i < nums1.length; i++) { for (let j = 0; j < nums2.length; j++) { if (nums1[i] != nums2[j]) { conti...
Maximum Length of Repeated Subarray
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the firs...
class Solution(object): def stoneGameIII(self, stoneValue): """ :type stoneValue: List[int] :rtype: str """ n = len(stoneValue) suffixSum = [0 for _ in range(n+1)] dp = [0 for _ in range(n+1)] for i in range(n-1, -1, -1): suffixSum[i] = suf...
class Solution { Integer[] dp; public String stoneGameIII(int[] stoneValue) { dp = new Integer[stoneValue.length + 1]; Arrays.fill(dp, null); int ans = stoneGameIII(0, stoneValue); if (ans == 0) return "Tie"; else if (ans > 0) return "Alice"; else return "Bob"; } public int stoneGameIII...
class Solution { public: int dp[50001][2][2]; int playGame(vector<int>& stones, bool alice, bool bob, int i) { if (i >= stones.size()) return 0; int ans; int sum = 0; if (dp[i][alice][bob] != -1) return dp[i][alice][bob]; if (alice) { ans = INT_MIN; ...
var stoneGameIII = function(stoneValue) { let len = stoneValue.length-1 let bestMoves = [0,0,0] bestMoves[len%3] = stoneValue[len] for(let i = len-1; i >= 0 ; i--){ let turn = stoneValue[i] let option1 = turn - bestMoves[(i+1)%3] turn += stoneValue[i+1] ||0 let option2 = ...
Stone Game III
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: num = "52" Output: "5" Expla...
class Solution: def largestOddNumber(self, num: str) -> str: indx = -1 n = len(num) for i in range(n): if int(num[i])%2 == 1: indx = i if indx == -1: return "" return num[:indx+1]
class Solution { public String largestOddNumber(String num) { for (int i = num.length() - 1; i > -1; i--) { if (num.charAt(i) % 2 == 1) return num.substring(0,i+1); } return ""; } }
class Solution { public: string largestOddNumber(string num) { // Length of the given string int len = num.size(); // We initialize an empty string for the result string res = ""; // We start searching digits from the very right to left because we want to find the first odd d...
var largestOddNumber = function(num) { for (let i = num.length - 1; i >= 0; i--) { // +num[i] converts string into number like parseInt(num[i]) if ((+num[i]) % 2) { return num.slice(0, i + 1); } } return ''; };
Largest Odd Number in String
Given a matrix&nbsp;and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 &lt;= x &lt;= x2 and y1 &lt;= y &lt;= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate&nbsp;t...
class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: m, n = len(matrix), len(matrix[0]) matrix_sums = [[0 for _ in range(n)] for _ in range(m)] # Calculate all the submatrices sum with the transition formula we found for row in range(...
class Solution { public int numSubmatrixSumTarget(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; int[] summedArray = new int[n]; int ans = 0; for(int i = 0; i < m; i++){ //starting row Arrays.fill(summedArray, 0); for(int j = i; j < m; j++){ //ending row ...
class Solution { public: int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { int n=matrix.size(),m=matrix[0].size(),count=0; vector<vector<int>>temp(n+1,vector<int>(m)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ temp[i+1][j]=temp[i][j]+matrix[i]...
var numSubmatrixSumTarget = function(matrix, target) { let result = 0; for (let i = 0; i < matrix.length; i++) { for (let j = 1; j < matrix[0].length; j++) { matrix[i][j] = matrix[i][j] + matrix[i][j-1] } } for (let i = 0; i < matrix[0].length; i++) { for (l...
Number of Submatrices That Sum to Target
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to firs...
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: d = {i:[] for i in range(numCourses)} for crs, prereq in prerequisites: d[crs].append(prereq) visit, cycle = set(), set() output = [] def dfs(crs)...
class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { Map<Integer, Set<Integer>> graph = new HashMap<>(); int[] inDegree = new int[numCourses]; for (int i = 0; i < numCourses; i++) { graph.put(i, new HashSet<Integer>()); } for (...
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { map<int, vector<int>>adj; vector<int> indegree(numCourses,0); vector<int>res; for(int i=0;i<prerequisites.size();i++){ adj[prerequisites[i][1]].push_back(prerequisites[i][...
/** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */ var findOrder = function(numCourses, prerequisites) { let visiting = new Set(); const visited = new Set(); const adjList = new Map(); const result = []; // Generate scaffold of adjacency list // initi...
Course Schedule II
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. A closed interval [a, b] (with a &lt;= b) denotes the set...
from collections import deque class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: answer = [] if len(firstList) == 0 or len(secondList) == 0: return answer first_queue= deque(firstList) second_que...
class Solution { public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { int i = 0; int j = 0; List<int[]> ans = new ArrayList<>(); while(i<firstList.length && j<secondList.length){ int a[] = firstList[i]; int b[] = secon...
class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) { vector<vector<int>> result; int i = 0; int j = 0; while(i < firstList.size() && j < secondList.size()){ if((firstList[i][0] >= secondList[j...
var intervalIntersection = function(firstList, secondList) { //if a overlap b - a.start >= b.start && a.start <= b.end //if b overlap a - b.start >= a.start && b.start <= a.end //handle empty edge cases if(firstList.length === 0 || secondList.length === 0){ return []; } let merged = []...
Interval List Intersections
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answ...
class Solution: def maxProduct(self, root: Optional[TreeNode]) -> int: def findTotalSum(node, totalSum): if node is None: return totalSum totalSum = findTotalSum(node.left,totalSum) totalSum += node.val totalSum = findTotalSum(node.right,totalS...
class Solution { public void findMaxSum(TreeNode node,long sum[]){ if(node==null) return ; findMaxSum(node.left,sum); findMaxSum(node.right,sum); sum[0]+=node.val; } public long findProd(TreeNode node,long sum[],long []max){ if(node==null) return 0; long ...
class Solution { public: int mod = 1e9+7; unordered_map<TreeNode*,pair<long long int,long long int>> mp; long long int helper(TreeNode* root){ if(!root) return 0; long long int ls = 0,rs = 0; if(root->left) ls = helper(root->left); if(root->right) ...
var maxProduct = function(root) { const lefteRightSumMap = new Map(); function getLeftRightSumMap(node) { if (node === null) return 0; let leftSum = getLeftRightSumMap(node.left); let rightSum = getLeftRightSumMap(node.right); lefteRightSumMap.set(node,...
Maximum Product of Splitted Binary Tree
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. &nbsp; Example ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: res = 0 po = 0 stack = [] node = head while node: ...
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public int getDecimalValue(ListNode head) { head = ...
class Solution { public: int getDecimalValue(ListNode* head) { ListNode* temp = head; int count = 0; while(temp->next != NULL){ count++; temp = temp->next; } temp = head; int ans = 0; while(count != -1){ ans += temp->val * p...
var getDecimalValue = function(head) { let str = "" while(head){ str += head.val head = head.next } return parseInt(str,2) //To convert binary into Integer
Convert Binary Number in a Linked List to Integer
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. &nbsp; Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] cont...
class Solution: def longestSubarray(self, nums: List[int]) -> int: n = len(nums) pre, suf = [1]*n, [1]*n if nums[0] == 0:pre[0] = 0 if nums[-1] == 0:suf[-1] = 0 for i in range(1, n): if nums[i] == 1 and nums[i-1] == 1: pre[i] = pre[i-1] + ...
class Solution { public int longestSubarray(int[] nums) { List<Integer> groups = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) groups.add(nums[i]); if (nums[i] == 1) { int count = 0; while (i < num...
class Solution { public: int longestSubarray(vector<int>& nums) { int x=0,y=0,cnt=0; for(int i=0;i<nums.size();i++){ if(nums[i]==1){ x++; } else if(nums[i]==0){ cnt=max(cnt,x+y); y=x; x=0; ...
var longestSubarray = function(nums) { let l = 0, r = 0; let longest = 0; // Keep track of the idx where the last zero was seen let zeroIdx = null; while (r < nums.length) { // If we encounter a zero if (nums[r] === 0) { // If this is the first zero encountered, then set ...
Longest Subarray of 1's After Deleting One Element
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 &lt;= i1 &lt; i2 &lt; ... &lt; ik &lt;= nums.length - 1, and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the...
class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: dp = [[1]*1001 for i in range(len(nums))] for i in range(len(nums)): for j in range(i+1,len(nums)): d = nums[j] - nums[i] + 500 dp[j][d] = max(dp[i][d]+1,dp[j][d]) return max(...
class Solution { public int longestArithSeqLength(int[] nums) { int n = nums.length; int longest = 0; Map<Integer, Integer>[] dp = new HashMap[n]; for (int i = 0; i < n; i++) { dp[i] = new HashMap<>(); for (int j = 0; j < i...
class Solution { public: int longestArithSeqLength(vector<int>& nums) { int n=size(nums); int ans=1; vector<vector<int>> dp(n,vector<int>(1005,1)); for(int i=1;i<n;i++) for(int j=0;j<i;j++) ans=max(ans, dp[i][nums[i]-nums[j]+500]= 1+dp[...
var longestArithSeqLength = function(nums) { if (nums === null || nums.length === 0) { return 0; } let diffMap = new Array(nums.length).fill(0).map(() => new Map()); let maxLen = 1; for (let i = 0; i < nums.length; i++) { for (let j = 0; j < i; j++) { let diff = nums[i] -...
Longest Arithmetic Subsequence
An integer interval [a, b] (for integers a &lt; b) is a set of all consecutive integers from a to b, including a and b. Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two. &nbsp; Example 1: Input: intervals = [[1,3],[1,4],[2,5...
class Solution: def intersectionSizeTwo(self, intervals: List[List[int]]) -> int: ans = [] for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): if not ans or ans[-2] < x: if ans and x <= ans[-1]: ans.append(y) else: ans.extend([y-1, y]) re...
//Time Complexity O(Nlog(N)) - N is the number of intervals //Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed class Solution { public int intersectionSizeTwo(int[][] intervals) { //corner case: can intervals be null or empty? No //First, sort the intervals by ...
class Solution { public: // sort wrt. end value static bool compare(vector<int>& a, vector<int>& b) { if(a[1] == b[1]) return a[0] < b[0]; else return a[1] < b[1]; } int intersectionSizeTwo(vector<vector<int>>& intervals) { int n = intervals.size()...
/** * @param {number[][]} intervals * @return {number} */ var intersectionSizeTwo = function(intervals) { const sortedIntervals = intervals.sort(sortEndsThenStarts) let currentTail = [] let answer = 0 sortedIntervals.forEach(interval => { const start = interval[0] const end = interval...
Set Intersection Size At Least Two
Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule i...
# 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 findTilt(self, root: Optional[TreeNode]) -> int: res = [0] def tilt_helper(root,res): if not root: ...
class Solution { int max = 0; public int findTilt(TreeNode root) { loop(root); return max; } public int loop(TreeNode root){ if(root==null) return 0; int left = loop(root.left); int right = loop(root.right); max+= Math.abs(left-right); return root....
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l...
var findTilt = function(root) { function helper(node, acc) { if (node === null) { return 0; } const left = helper(node.left, acc); const right = helper(node.right, acc); acc.sum += Math.abs(left - right); return left + node.val + right; } let a...
Binary Tree Tilt
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individual...
class DSU(object): def __init__(self, N): self.par = list(range(N)) self.rnk = [0] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if x...
class Solution { public int swimInWater(int[][] grid) { int len = grid.length; Map<Integer, int[]> reverseMap = new HashMap<>(); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { reverseMap.put(grid[i][j], new int[] { i, j }); } }...
class Solution { public: int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; bool valid(int x,int y,int n) { return ((x>=0&&x<n)&&(y>=0&&y<n)); } int swimInWater(vector<vector<int>>& grid) { int n=grid.size(); int time[n][n]; bool vis[n][n]; for(int i=0;i<n;++i) ...
const moves = [[1,0],[0,1],[-1,0],[0,-1]] var swimInWater = function(grid) { let pq = new MinPriorityQueue(), N = grid.length - 1, ans = grid[0][0], i = 0, j = 0 while (i < N || j < N) { for (let [a,b] of moves) { let ia = i + a, jb = j + b if (ia < 0 || ia > N || jb < 0...
Swim in Rising Water
We define the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Given a string p, return the number of unique non-empty substrings of p are present in s. &nbsp; Example 1: Input: p = "a" Out...
def get_next(char): x = ord(char)-ord('a') x = (x+1)%26 return chr(ord('a') + x) class Solution: def findSubstringInWraproundString(self, p: str) -> int: i = 0 n = len(p) map_ = collections.defaultdict(int) while i<n: start = i prev_val = p[i] ...
// One Pass Counting Solution // 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring. // 2. counts to track the longest continuos subtring starting with current character. // Time complexity: O(N) // Space complexity: O(1) class Solution { public int findSubstringInWraproundString(String...
class Solution { public: int findSubstringInWraproundString(string p) { unordered_map<char, int> mp; // if the characters are not contiguous and also check whether after 'z' I am getting 'a'. If so, reset the streak to 1 // else streak++ int streak = 0; for (int i = 0; i ...
var findSubstringInWraproundString = function(p) { const dp = Array(26).fill(0); const origin = 'a'.charCodeAt(0); let count = 0; for (let index = 0; index < p.length; index++) { const code = p.charCodeAt(index); const preCode = p.charCodeAt(index - 1); const pos = code - origin; count = code - preCode ==...
Unique Substrings in Wraparound String
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Up...
class LRUCache { int N; list<int> pages; unordered_map<int, pair<int, list<int>::iterator>> cache; public: LRUCache(int capacity) : N(capacity) { } int get(int key) { if (cache.find(key) != cache.end()) { pages.erase(cache[key].second); pages.push_fr...
class LRUCache { // Declare Node class for Doubly Linked List class Node{ int key,value;// to store key and value Node next,prev; // Next and Previous Pointers Node(int k, int v){ key=k; value=v; } } Node head=new Node(-1,-1); // Default values ...
class LRUCache { public: int mx; class node{ public: node *prev,*next; int key,val; node(int k,int v){ key=k,val=v; } }; unordered_map<int,node*> mp; node *head=new node(-1,-1); node *tail=new node(-1,-1); LRUCache(int capacity) { ...
/** * @param {number} capacity */ var LRUCache = function(capacity) { this.capacity = capacity; this.cache = new Map(); }; /** * @param {number} key * @return {number} */ LRUCache.prototype.get = function(key) { if(!this.cache.has(key)){ return -1 } let val = this.cache.get(key);...
LRU Cache
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Return the latest 24-hour time in "HH:MM" format...
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: res = "" digit_freq = collections.Counter(arr) # first digit if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2: res += "2" arr.remove(2) else: ...
class Solution { public String largestTimeFromDigits(int[] arr) { int[] count = new int[10]; for (int num: arr) { count[num]++; } StringBuilder sb = backTrack(count, new StringBuilder()); if (sb.length() == 4) sb.insert(2, ':'); return sb.toString(); ...
class Solution { public: string largestTimeFromDigits(vector<int>& arr) { sort(arr.rbegin(), arr.rend()); used.resize(4); string ret = ""; if(!dfs(arr,0,0)) return ret; else { for(int i=0;i<2;i++) ret.push_back(ans[i] + '0'); ...
var largestTimeFromDigits = function(arr) { let max=-1; for(let A=0; A<4; A++){ for(let B=0; B<4; B++){ if(B==A){continue}; for(let C=0; C<4; C++){ if(C==A||C==B||arr[C]>=6){continue}; for(let D=0; D<4; D++){ if(D==A||D==B||D==C){continue}; let...
Largest Time for Given Digits
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. &nbsp; Example 1: Input: strs = ["eat","tea","tan","ate","nat","ba...
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: strs_table = {} for string in strs: sorted_string = ''.join(sorted(string)) if sorted_string not in strs_table: strs_table[sorted_string] = [] strs_table[sorted_string]...
class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap<String,ArrayList<String>> hm=new HashMap<>(); for(String s : strs) { char ch[]=s.toCharArray(); Arrays.sort(ch); StringBuilder sb=new StringBuilder(""); for(char ...
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { map<string,vector<int>> mp; for(int i=0;i<strs.size();i++) { string t=strs[i]; sort(t.begin(),t.end()); mp[t].push_back(i); } vector<vector<string>> ans;...
var groupAnagrams = function(strs) { let totalResults = []; let grouped = new Map(); for (let i=0; i < strs.length; i++) { let results = []; let res = strs[i]; let sortedStr = strs[i].split('').sort().join(''); let value = grouped.get(sortedStr); if (value !== unde...
Group Anagrams