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 playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available ...
class Solution: def maximumScore(self, a: int, b: int, c: int) -> int: a, b, c = sorted([a, b, c], reverse=True) ans = 0 while a > 0 and b > 0: a -= 1 b -= 1 ans += 1 a, b, c = sorted([a, b, c], reverse=True) return ans
class Solution { public int maximumScore(int a, int b, int c) { // Make sure a <= b <= c if (a>b) return maximumScore(b,a,c); if (b>c) return maximumScore(a,c,b); // if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c if (a+b<=c) retur...
class Solution { public: int maximumScore(int a, int b, int c) { return min((a + b + c) / 2, a + b + c - max({a, b, c})); } };
/** * @param {number} a * @param {number} b * @param {number} c * @return {number} */ var maximumScore = function(a, b, c) { let resultArray = []; resultArray.push(a); resultArray.push(b); resultArray.push(c); resultArray.sort((a,b)=>a-b); let counter=0; while(resultArray[0]>0||resultAr...
Maximum Score From Removing Stones
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are ...
class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: servers_available = [(w, i) for i,w in enumerate(servers)] heapify(servers_available) tasks_in_progress = [] res = [] time = 0 for j,task in enumerate(tasks): time = ...
class Solution { public int[] assignTasks(int[] servers, int[] tasks) { PriorityQueue<int[]> availableServer = new PriorityQueue<int[]>((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0]))); for(int i = 0; i < servers.length; i++){ availableServer.add(new int[]{i, servers[i]}); ...
class Solution { public: vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) { priority_queue<vector<long long>, vector<vector<long long>>, greater<vector<long long>>> free, busy; for (int i = 0; i < servers.size(); ++i) { free.push(vector<long long>{servers[i], i}); ...
var assignTasks = function(servers, tasks) { // create a heap to manage free servers. // free servers will need to be prioritized by weight and index const freeServers = new Heap((serverA, serverB) => ( serverA.weight - serverB.weight || serverA.index - serverB.index )); // create a heap t...
Process Tasks Using Servers
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) an...
class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]: perm=[i for i in range(1,m+1)] res=[] for i in queries: ind=perm.index(i) res.append(ind) perm=[perm.pop(ind)]+perm return res
class Solution { public int[] processQueries(int[] queries, int m) { int[] results = new int[queries.length]; ArrayList<Integer> permutations = new ArrayList<Integer>(); // Filling the permuations array with numbers. for (int i = 0; i < m; i++) permutations.add(i+1); ...
class Solution { public: vector<int> processQueries(vector<int>& queries, int m) { vector<int> p; for(int i=0; i<m; i++) p.push_back(m-i); for(int i=0; i<queries.size(); i++) { auto it = find(p.begin(), p.end(), queries[i]); int j = it - p.b...
var processQueries = function(queries, m) { let result = []; let permutation = []; for(let i=0; i<m; i++){ permutation.push(i+1); } for(let i=0; i<queries.length; i++){ let index = permutation.indexOf(queries[i]); result.push(index); permutation.splice(index,1); ...
Queries on a Permutation With Key
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] &lt;= nums[i + 1] holds for every i (0-based) such that (0 &lt;= i &lt;= n - 2). &nbsp; Example 1: Input: nums = [4,2,3] Output: true Explanat...
class Solution: def checkPossibility(self, nums: List[int]) -> bool: unstable=0 for i in range(1,len(nums)): if nums[i]<nums[i-1]: unstable+=1 if i<2 or nums[i-2]<=nums[i]: nums[i-1]=nums[i] else: num...
class Solution { public boolean checkPossibility(int[] nums) { int modified = 0, prev = nums[0], index = 0; for (; index < nums.length; ++index) { if (nums[index] < prev) { if (++modified > 1) return false; if (index - 2 >= 0 && nums[index - 2] > nums[inde...
class Solution { public: bool checkPossibility(vector<int>& nums) { if(nums.size()<=2) return true; //creating a diff array(size=n-1) to store differences bw 2 consecutive ele. vector<int>diff(nums.size()-1); int neg=0; for(int i=0;i<nums.size()-1;i++) { diff[i]=nums[i+1]-nu...
var checkPossibility = function(nums) { let changed = false for(let i=nums.length-1; i>0; i--) { if(nums[i-1] > nums[i]) { if(changed) return false; if(i === nums.length-1 || nums[i-1] < nums[i+1]) nums[i] = nums[i-1] else nums[i-1] = nums[i]; changed = tr...
Non-decreasing Array
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting posi...
class Solution: def minRefuelStops(self, t, F, S): S.append([t, 0]) heap, ans = [], 0 for p,f in S: while heap and p > F: F -= heapq.heappop(heap) ans += 1 if p > F: return -1 heapq.heappush(heap, -f) return ans
class Solution { public int minRefuelStops(int target, int startFuel, int[][] stations) { if(startFuel >= target) return 0; int[][] dp = new int[stations.length + 1][stations.length + 1]; for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel; for (int j = 1; j < dp.length; j++) { ...
/* The approach here used is - first cosider the stations which are possible at a particular time and then take the one with maximum fuel that can be filled this ensure that with only one fill up the vehicle will move to furthest distance. Now there might be case where if we don't fill up from multiple stations ata p...
var minRefuelStops = function(target, startFuel, stations) { let pq = new MaxPriorityQueue({compare: (a, b) => b[1] - a[1]}); let idx = 0, reachablePosition = startFuel, refuels = 0; // reachablePosition is the farthest position reachable so far while (reachablePosition < target) { // While...
Minimum Number of Refueling Stops
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer get...
class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: freq = {} for x in nums: freq[x] = 1 + freq.get(x, 0) vals = sorted(freq.values(), reverse=True) quantity.sort(reverse=True) # pruning - large values first def fn(i): ...
class Solution { public boolean canDistribute(int[] nums, int[] quantity) { // Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2} Map<Integer, Integer> freq = new HashMap<>(); for (int num : nums) freq.put(num, freq.getOrDefault(num, 0)+1); ...
class Solution { public: bool solve(vector<int>&q, map<int,int>&count, int idx){ if(idx==q.size()){ return true; } for(auto it=count.begin();it!=count.end();it++){ if(it->second>=q[idx]){ count[it->first]-=q[idx]; if(solve(q,count,idx+1...
var canDistribute = function(nums, quantity) { quantity.sort((a,b)=>b-a) let freq={},flag=false for(let num of nums) freq[num]=(freq[num]||0) +1 let set=Object.keys(freq),n=set.length,k=quantity.length let rec=(prefix)=>{ if(prefix.length==k || flag==true) return flag=t...
Distribute Repeating Integers
You are given a 0-indexed binary string s which represents the types of buildings along a street where: s[i] = '0' denotes that the ith building is an office and s[i] = '1' denotes that the ith building is a restaurant. As a city official, you would like to select 3 buildings for random inspection. However, to en...
class Solution: def numberOfWays(self, s: str) -> int: temp = [] c0 = 0 c1 = 0 for char in s : if char == "0" : c0+=1 else: c1+=1 temp.append([c0,c1]) total0 = c0 total1 = c1 ...
class Solution { public long numberOfWays(String s) { int zero = 0; // Individual zeroes count long zeroOne = 0; // Number of combinations of 01s int one = 0; // Individual ones count long oneZero = 0; // Number of combinations of 10s long tot = 0; // Final answer ...
class Solution { public: long long numberOfWays(string s) { long long a=0,b=0,ans=0; // a and b are the number of occurances of '1' and '0' after the current building respectively. for(int i=0;i<s.length();i++){ if(s[i]=='1') a++; else b...
var numberOfWays = function(s) { const len = s.length; const prefix = new Array(len).fill(0).map(() => new Array(2).fill(0)); for(let i = 0; i < len; i++) { const idx = s[i] == '1' ? 1 : 0; if(i == 0) prefix[i][idx]++; else { prefix[i] = Array.from(prefix[i-1]); ...
Number of Ways to Select Buildings
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7. &nbsp; Example 1: Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3...
class Solution: def sumSubarrayMins(self, arr: List[int]) -> int: n = len(arr) small_before = [-1]*n stack = [] for i in range(n): while stack and arr[stack[-1]] >= arr[i]: stack.pop() if stack:small_before[i] = stack[-1] stack.appe...
class Solution { public int sumSubarrayMins(int[] arr) { int n = arr.length; int ans1[] = nsl(arr); int ans2[] = nsr(arr); long sum=0; for(int i=0;i<n;i++){ sum=(sum + (long)(arr[i]*(long)(ans1[i]*ans2[i])%1000000007)%1000000007)%1000000007; } return (int)sum; } ...
class Solution { public: //Thanks to Bhalerao-2002 int sumSubarrayMins(vector<int>& A) { int n = A.size(); int MOD = 1e9 + 7; vector<int> left(n), right(n); // for every i find the Next smaller element to left and right // Left stack<int>st;...
var sumSubarrayMins = function(arr) { M = 10**9+7 stack = [-1] res = 0 arr.push(0) for(let i2 = 0; i2 < arr.length; i2++){ while(arr[i2] < arr[stack[stack.length -1]]){ i = stack.pop() i1 = stack[stack.length-1] Left = i - i1 Right = ...
Sum of Subarray Minimums
You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). &nbsp; Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 996...
class Solution: def maximum69Number(self, num): lst= list(str(num)) #! convert the number to a list for i in range(len(lst)): #! iterate through the list if lst[i]=='6': #! if the element is 6 lst[i]='9' #! replace the element with 9 break #! break the loo...
class Solution { public int maximum69Number (int num) { int i; String s=String.valueOf(num); int l=s.length(); int max=num; for(i=0;i<l;i++) { char c[]=s.toCharArray(); if(c[i]=='9') { c[i]='6'; ...
class Solution { public: int maximum69Number (int num) { string s=to_string(num); for(int i=0;i<s.size();i++){ if(s[i]=='6'){ s[i]='9'; break; } } num=stoi(s); return num; } };
var maximum69Number = function(num) { let flag=true num= num.toString().split('').map((x)=>{ if(x!=='9'&&flag){ flag=false return '9' } return x }) return parseInt(num.join('')) };
Maximum 69 Number
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra spa...
class Solution: def singleNumber(self, nums: List[int]) -> List[int]: x = Counter(nums) return([y for y in x if x[y] == 1])
class Solution { public int[] singleNumber(int[] nums) { if (nums == null || nums.length < 2 || nums.length % 2 != 0) { throw new IllegalArgumentException("Invalid Input"); } int aXORb = 0; for (int n : nums) { aXORb ^= n; } int rightSetBit =...
class Solution { public: vector<int> singleNumber(vector<int>& nums){ vector<int> ans; int xorr = 0; for(int i=0; i<nums.size(); i++){ xorr = xorr xor nums[i]; } int count = 0; while(xorr){ if(xorr & 1){ break; } ...
var singleNumber = function(nums) { let hash ={} for ( let num of nums){ if( hash[num]===undefined) hash[num] =1 else hash[num]++ } let result =[] for ( let [key, value] of Object.entries(hash)){ if(value==1) result.push(key) } retur...
Single Number III
You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 &lt; upperi for 0 &lt; i &lt; brackets.length). Tax is calculated as follows: ...
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: taxtot=0 if(brackets[0][0]<income): taxtot+=brackets[0][0]*(brackets[0][1]) income-=brackets[0][0] else: taxtot+=income*(brackets[0][1]) return taxtot/100 ...
class Solution { public double calculateTax(int[][] brackets, int income) { double ans=0; int pre=0; for(int[] arr : brackets){ int val=arr[0]; arr[0]-=pre; pre=val; ans+=(double)(Math.min(income,arr[0])*arr[1])/100; income-=arr[0]; if(income<...
class Solution { public: double calculateTax(vector<vector<int>>& brackets, int income) { double tax = 0; if(brackets[0][0]<=income) tax=(brackets[0][0]*brackets[0][1]/100.0); else return (income*brackets[0][1]/100.0); for(int i=1; i<brackets....
var calculateTax = function(brackets, income) { return brackets.reduce(([tax, prev], [upper, percent]) => { let curr = Math.min(income, upper - prev); tax += curr * (percent / 100); income -= curr; if (income <= 0) brackets.length = 0; return [tax, upper]; }, [0, 0])[0]...
Calculate Amount Paid in Taxes
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking. A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers sta...
class Node: def __init__(self, start, end, val): self.start = start self.end = end self.val = val self.left = None self.right = None def insertable(self, node): if node.end <= node.start: return True if node.end <= self.start: ...
class MyCalendarTwo { private List<int[]> bookings; private List<int[]> doubleBookings; public MyCalendarTwo() { bookings = new ArrayList<>(); doubleBookings = new ArrayList<>(); } public boolean book(int start, int end) { for(int[] b : doubleBookings) { ...
class MyCalendarTwo { public: map<int,int>mpp; MyCalendarTwo() { } bool book(int start, int end) { mpp[start]++; mpp[end]--; int sum=0; for(auto it:mpp){ sum+=it.second; if(sum>2){ mpp[start]--; mpp[end]++; ...
var MyCalendarTwo = function() { this.calendar = []; this.overlaps = []; }; /** * @param {number} start * @param {number} end * @return {boolean} */ MyCalendarTwo.prototype.book = function(start, end) { for (let date of this.overlaps) { if (start < date[1] && end > date[0]) return false; } for (le...
My Calendar II
There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit. Choose a subset s of the n elements such that: The size of the subset s is less than or equ...
from collections import defaultdict import heapq class Solution: def largestValsFromLabels( self, values: list[int], labels: list[int], numWanted: int, useLimit: int ) -> int: # Add labels and values into the heap heap = [(-value, label) for value, label in zip(values, labels)] ...
class Solution { public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) { PriorityQueue<Pair<Integer, Integer>> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey())); for(int i=0;i<values.length;i++) { maxHeap.add...
class Solution { public: int largestValsFromLabels(vector<int>& values, vector<int>& labels, int numWanted, int useLimit) { // same label item should be less than uselimit priority_queue<pair<int,int>>q; // this will give us maximum element because we need to maximise the sum for(int i=0;i...
/** * @param {number[]} values * @param {number[]} labels * @param {number} numWanted * @param {number} useLimit * @return {number} */ var largestValsFromLabels = function(values, labels, numWanted, useLimit) { // this sortValues will create an addition array that keep track of the value idx after descending ...
Largest Values From Labels
Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, retu...
from functools import lru_cache class Solution: def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int: def srange(a, b): return [chr(i) for i in range(ord(a),ord(b)+1)] def LPS(pat): lps = [0] i, target = 1, 0 while i < len(pat): ...
class Solution { Integer[][][][] dp; int mod = 1000000007; int[] lps; private int add(int a, int b) { return (a % mod + b % mod) % mod; } private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) { if(evI == evil.length) ...
class Solution { public: using ll = long long; int findGoodStrings(int n, string s1, string s2, string evil) { int M = 1e9+7; int m = evil.size(); // kmp int f[m]; f[0] = 0; for (int i = 1, j = 0; i < m; ++i) { while (j != 0 && evil[i] != evil[j]) { j = f[j-...
const mod = 10 ** 9 + 7 let cache = null /** * @param {number} n * @param {string} s1 * @param {string} s2 * @param {string} evil * @return {number} */ var findGoodStrings = function(n, s1, s2, evil) { /** * 17 bits * - 9 bit: 2 ** 9 > 500 by evil * - 6 bit: 2 ** 6 > 50 by evil * - 1 bit...
Find All Good Strings
Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer. &nbsp; Example 1: Input...
class Solution: def minDistance(self, houses: List[int], k: int) -> int: houses.sort() @lru_cache(None) def dp(left, right, k): if k == 1: # <-- 1. mid = houses[(left+right) // 2] return sum(abs(houses[i] -...
class Solution { public int minDistance(int[] houses, int k) { Arrays.sort(houses); int n = houses.length; int[] dp = new int[n]; for (int i = 1; i < n; i++){ // know optimal dist for i-1, then for i, we add houses[i] - houses[i/2] dp[i]=dp[i-1]+houses[i]-houses[i/2]; ...
class Solution { public: int dp[101][101] ; int solve(vector<int>&houses , int pos , int k){ if(k < 0) return 1e9 ; if(pos >= houses.size()) return k ? 1e9 : 0 ; if(dp[pos][k] != -1) return dp[pos][k] ; //at current position pos, spread the group from (pos upto j) and a...
/** * @param {number[]} houses * @param {number} k * @return {number} */ var minDistance = function(houses, k) { var distance=[],median,dist,cache={}; houses.sort(function(a,b){return a-b}); //distance[i][j] is the minimun distacne if we cover houses from ith index to jth index with 1 mailbox. This mail...
Allocate Mailboxes
Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it...
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: newPlate = '' # modify the licensePlate for i in licensePlate: if i.isalpha(): newPlate += i.lower() c = Counter(newPlate) l1 = [] ...
class Solution { public String shortestCompletingWord(String licensePlate, String[] words) { //Store count of letters in LicensePlate int[] licensePlateCount = new int[26]; //To store all words which meet the criteria ArrayList<String> res = new ArrayList<>(); //To f...
class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { string ans=""; vector<int> m(26,0); for(auto &lp:licensePlate) { if(isalpha(lp)) m[tolower(lp)-'a']++; } for(auto &word:words) ...
var shortestCompletingWord = function(licensePlate, words) { // Object to hold the shortest word that matches var match = {'found':false, 'word':''}; // Char array to hold the upper case characters we want to match var licensePlateChars = licensePlate.toUpperCase().replace(/[^A-Z]/g, '').split(''); ...
Shortest Completing Word
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7. Two paths are conside...
class Solution: def __init__(self): self.dp = None self.di = [0, 0, -1, 1] self.dj = [-1, 1, 0, 0] self.mod = 1000000007 def countPaths(self, grid): n = len(grid) m = len(grid[0]) self.dp = [[0] * m for _ in range(n)] ans = 0 for i in ...
class Solution { long[][] dp; int mod = 1_000_000_007; public int countPaths(int[][] grid) { dp = new long[grid.length][grid[0].length]; long sum=0L; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ sum = (sum + dfs(grid,i,j,0)) % mod; ...
class Solution { public: int mod = 1000000007; int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; int countPaths(vector<vector<int>>& grid) { vector <vector <int>> dp(grid.size(),vector<int>(grid[0].size(),-1)); long long count = 0; for(int i = 0; i<grid.size(); i++){ fo...
var countPaths = function(grid) { let mod = Math.pow(10, 9) + 7; let result = 0; let rows = grid.length, columns = grid[0].length; let dp = Array(rows).fill(null).map(_ => Array(columns).fill(0)); const dfs = (r, c, preVal)=> { if (r < 0 || r == rows || c < 0 || c == columns || grid[r][c] <= preVal) retu...
Number of Increasing Paths in a Grid
You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: nums = [3,5,6,7], target = 9 ...
class Solution: def numSubseq(self, nums: List[int], target: int) -> int: nums.sort() left, right = 0, len(nums) - 1 count = 0 mod = 10 ** 9 + 7 while left <= right: if nums[left] + nums[right] > target: right -= 1 else: ...
class Solution { public int numSubseq(int[] nums, int target) { int n = nums.length; int i =0, j = n-1; int mod = (int)1e9+7; Arrays.sort(nums); int[] pow = new int[n]; pow[0]=1; int count =0; for(int z =1;z<n;z++){ pow[z] = (pow[z-1]*2)%mo...
class Solution { private: int mod=1e9+7; int multiply(int a,int b){ if(b==0){ return 0; } else if(b%2==0){ int ans=multiply(a,b/2); return (ans%mod+ans%mod)%mod; } else { int ans=multiply(a,b-1); return (a%mod+ans%mod)%mod; ...
const MOD = 1000000007; var numSubseq = function(nums, target) { nums.sort((a, b) => a - b); const len = nums.length; const pow = new Array(len).fill(1); for(let i = 1; i < len; i++) { pow[i] = (pow[i - 1] * 2) % MOD; } let l = 0, r = len - 1, ans = 0; while(l <= r) { if(num...
Number of Subsequences That Satisfy the Given Sum Condition
A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the st...
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] for parenthese in s: if parenthese == "(": stack.append("(") else: if not stack or stack[-1] == ")": stack.append(")") if stack and st...
class Solution { public int minAddToMakeValid(String s) { int open = 0; int extra = 0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ open++; }else{ if(open==0){ extra++; }else{ ...
class Solution { public: int minAddToMakeValid(string s) { stack<char> sta; int nums = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') { sta.push(s[i]); } else { if (!sta.empty()) ...
var minAddToMakeValid = function(s) { let stack = [] let count = 0 for(let i=0;i<s.length;i++) { let ch = s[i] if(ch === '(') { stack.push(ch) } else { let top = stack.pop() if(top != '(') count++ } } count += stack.length ret...
Minimum Add to Make Parentheses Valid
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i &lt; j &lt; k and nums[i] &lt; nums[j] &lt; nums[k]. If no such indices exists, return false. &nbsp; Example 1: Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i &lt; j &lt; k is valid. Example 2...
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: first = second = float('inf') for n in nums: if n <= first: first = n elif n <= second: second = n else: return True return False
class Solution { public boolean increasingTriplet(int[] nums) { if(nums.length < 3) return false; int x = Integer.MAX_VALUE; int y = Integer.MAX_VALUE; for (int i : nums){ if(i <= x){ x = i; }else if (i <= y) ...
class Solution { public: bool increasingTriplet(vector<int>& nums) { int n = nums.size(); int smallest = INT_MAX; int second_smallest = INT_MAX; for(int i = 0;i<n;i++) { if(nums[i] <= smallest) { smallest = nums[i]; } ...
var increasingTriplet = function(nums) { const length = nums.length, arr = []; let tripletFound = false, arrLength, added = false, found = false; if(length < 3) return false; arr.push([nums[0],1]); for(let index = 1; index < length; index++) { let count = 1; added = false; fo...
Increasing Triplet Subsequence
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. &nbsp; Example 1: Input: arr = [1,0,2...
class Solution: def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ l = len(arr) i,c=0,0 while i<l: if arr[i]==0: arr.insert(i+1,0) i+=1 arr.pop() ...
class Solution { // Time Complexity = O(n) // Space Complexity = O(1) public void duplicateZeros(int[] arr) { // Loop through the array for(int i = 0; i < arr.length; i++) { // Trigger Condition if(arr[i] ==0) { int j; ...
class Solution { public: void duplicateZeros(vector<int>& arr) { for(int i=0;i<arr.size();i++) { if(arr[i]==0) { arr.pop_back(); arr.insert(arr.begin()+i,0); i++; } } } };
/** * @param {number[]} arr * @return {void} Do not return anything, modify arr in-place instead. */ var duplicateZeros = function(arr) { // Variables const originalLength = arr.length; // Iterate over all the numbers in 'arr', if the number is 0 we duplicate it and skip the next loop iteration to p...
Duplicate Zeros
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. &nbsp; Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation:&nbsp;The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example...
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: # defining dictionary occ = dict() # adding elements with their counts in dictionary for element in arr: if element not in occ: occ[element] = 0 else: occ[element...
class Solution { public boolean uniqueOccurrences(int[] arr) { Arrays.sort(arr); HashSet<Integer> set = new HashSet<>(); int c = 1; for(int i = 1; i < arr.length; i++) { if(arr[i] == arr[i-1]) c++; else { if(set.contains(c...
class Solution { public: bool uniqueOccurrences(vector<int>& arr) { unordered_map<int,int>sk; unordered_map<int,int>skk; for(int i=0;i<arr.size();i++){ sk[arr[i]]++; } for(auto j : sk) { if(skk[j.second]==1){ return false; ...
var uniqueOccurrences = function(arr) { const obj = {}; // Creating hashmap to store count of each number arr.forEach(val => obj[val] = (obj[val] || 0) + 1); // Creating an array of the count times const val = Object.values(obj).sort((a, b) => a-b); // Now, just finding the duplicates for(le...
Unique Number of Occurrences
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each ga...
class Solution: def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: g = defaultdict(list) for u,v in paths: g[u-1].append(v-1) g[v-1].append(u-1) ans = [0]*n for i in range(n): c = [1,2,3,4] for j in g[i]: if ans[j] in c: c.remove(ans[j]) ans[i] = c.pop() retur...
class Solution { public int[] gardenNoAdj(int n, int[][] paths) { boolean[][] graph = new boolean[n][n]; for(int i = 0;i<paths.length;i++){ int u = paths[i][0]-1; int v = paths[i][1]-1; graph[u][v] = true; graph[v][u] = true; } int[] co...
class Solution { public: int check(vector<int> a[],vector<int> &col,int sv,int i) { for(auto it:a[sv]) { if(col[it]==i)return 0; } return 1; } void dfs(vector<int> a[],vector<int> &col,int sv,int lc) { for(int i = 1;i<5;i++) { ...
/** * @param {number} n * @param {number[][]} paths * @return {number[]} */ var gardenNoAdj = function(n, paths) { //if n is less than or equal to four just return an array of size n from 1 to n if(n <= 4){ let arr = [] let count = 1 while(arr.length < n){ arr.push(count)...
Flower Planting With No Adjacent
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot...
class Solution: def fillCups(self, amount: List[int]) -> int: count = 0 amount = sorted(amount, reverse=True) while amount[0] > 0: amount[0] -= 1 amount[1] -= 1 count += 1 amount = sorted(amount, reverse=True) return count
class Solution { public int fillCups(int[] amount) { Arrays.sort(amount); int x=amount[0]; int y=amount[1]; int z=amount[2]; int sum=x+y+z; if(x+y>z){return sum/2 +sum%2;} if(x==0&&y==0){return z;} else{return z;} } }
class Solution { public: int fillCups(vector<int>& amount) { sort(amount.begin(),amount.end()); int x=amount[0]; int y=amount[1]; int z=amount[2]; int sum=x+y+z; if(x+y>z) return sum/2+sum%2; if(x==0 && y==0) return z; else return z; } };
var fillCups = function(amount) { var count = 0 var a = amount while (eval(a.join("+")) > 0) { var max = Math.max(...a) a.splice(a.indexOf(max), 1) var max2 = Math.max(...a) a.splice(a.indexOf(max2), 1) count++ if(max == 0) a.push(0) else a.push(max - ...
Minimum Amount of Time to Fill Cups
There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end o...
class Solution: def recursion(self,index,used): # base case if index == self.n: return 0 #check in dp if (index,used) in self.dp: return self.dp[(index,used)] #choice1 is using the secret technique choice1 = -float('inf') # we can only use se...
class Solution { public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { int start = -1; int count = 0; int max = 0; int curr = 0; for (int i = 0; i < customers.length; i++) { if (grumpy[i] == 0) { count += customers...
/* https://leetcode.com/problems/grumpy-bookstore-owner/ TC: O(N) SC: O(1) Looking at the problem, main thing to find is the window where the minutes should be used so that the owner is not grumpy and max customers in that window can be satisifed. Find the window with most no. of ...
var maxSatisfied = function(customers, grumpy, minutes) { let left=0; let maxUnsatisfied=0; let curr=0; let satisfied=0; // finding the satisfied customers for(let i=0;i<customers.length;i++){ if(grumpy[i]===0)satisfied+=customers[i]; } // finding the maximum un-satisfied ...
Grumpy Bookstore Owner
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, ...
class Solution: def hammingWeight(self, n: int) -> int: i = 0 while n > 0: if n % 2 != 0: i += 1 n = n >> 1 return i
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { return Integer.bitCount(n); } }
class Solution { public: int hammingWeight(uint32_t n) { int ans=0; while(n!=0){ n=n&(n-1); ans++; } return ans; } };
var hammingWeight = function(n) { let count = 0, i = 0; while(n > 0) { i = 0; while(n >= Math.pow(2,i)) { i++; } count++; n -= Math.pow(2,i-1); } return count; };
Number of 1 Bits
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without usin...
class Solution: def sortColors(self, nums: List[int]) -> None: red, white, blue = 0, 0, len(nums) - 1 while white <= blue: if nums[white] == 0: nums[white], nums[red] = nums[red], nums[white] red += 1 white += 1 elif nums[whit...
class Solution { public void sortColors(int[] nums) { int zeroIndex = 0, twoIndex = nums.length - 1, i = 0; while (i <= twoIndex) { if (nums[i] == 0) swap(nums, zeroIndex++, i++); else if (nums[i] == 2) swap(nums, twoIndex--, i); else i++; } } public void s...
class Solution { public: void sortColors(vector<int>& nums) { int a =0; int b=0,c=0;int i; for(i=0;i<nums.size();i++){ if(nums[i]==0){ a++; } if(nums[i]==1){ b++; } else c++; } fo...
var sortColors = function(nums) { let map = { '0': 0, '1': 0, '2': 0 }; for(let char of nums) { map[char] = map[char] + 1; } let values = Object.values(map); let curr = 0; for(let k=0; k<values.length; k++) { for(let i=curr; i<curr+values[k]; i++) { ...
Sort Colors
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts ...
class Solution: def reversePrefix(self, word: str, ch: str) -> str: idx=word.find(ch) if idx: return word[:idx+1][::-1]+ word[idx+1:] return word
class Solution { public String reversePrefix(String word, char ch) { char[] c = word.toCharArray(); int locate = 0; for (int i = 0; i < word.length(); i++) { //first occurrence of ch if (ch == c[i]) { locate = i; break; } } ...
class Solution { public: string reversePrefix(string word, char ch) { string ans = ""; int tr = true; for(auto w : word){ ans.push_back(w); if(tr && w == ch){ tr=false; reverse(ans.begin(), ans.end()); } } re...
var reversePrefix = function(word, ch) { return word.indexOf(ch) !== -1 ? word.split("").slice(0, word.indexOf(ch) + 1).reverse().join("") + word.slice(word.indexOf(ch) + 1) : word; };
Reverse Prefix of Word
You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of it...
class Solution: def minScoreTriangulation(self, values: List[int]) -> int: n = len(values) c = [[0 for _ in range(n)] for _ in range(n)] for L in range(2, n): for i in range(1, n-L+1): j = i + L - 1 ...
class Solution { int solve(int[] v, int i, int j){ if(i+1==j) return 0; int ans= Integer.MAX_VALUE; for(int k=i+1;k<j;k++){ ans= Math.min(ans, (v[i]*v[j]*v[k] + solve(v,i,k) + solve(v,k,j) ) ); } return ans; } int solveMem(int[] v, int i, int ...
class Solution { public: int f(int i,int j,vector<int>& values,vector<vector<int>> &dp){ if(i == j || i+1 == j) return 0; if(dp[i][j] != -1) return dp[i][j]; int res = INT_MAX; for(int k = i+1;k < j;k++) { int temp = values[i]*values[j]*values[k] + f(k,j,values,dp) + f(i,k,values,dp); res = m...
var minScoreTriangulation = function(values) { let dp = Array(values.length).fill().map((i) => Array(values.length).fill(0)); function dfs(i, j) { if (dp[i][j]) return dp[i][j]; if (j - i < 2) return 0; let min = Infinity; // k forms a triangle with i and j, thus bisecting the ar...
Minimum Score Triangulation of Polygon
Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1. Return the length of n. If there is no such n, return -1. Note: n may not fit in a 64-bit signed integer. &nbsp; Example 1: Input: k = 1 Output: 1 Explanation: T...
class Solution: def smallestRepunitDivByK(self, k: int) -> int: if k % 2 == 0: return -1 n = 1 leng = 1 mapp = {} while True: rem = n % k if rem == 0: return leng if rem in mapp : return -1 mapp[rem] = True n = n*10 ...
class Solution { public int smallestRepunitDivByK(int k) { // if (k % 2 == 0 || k % 5 == 0) return -1; // this trick may save a little time boolean[] hit = new boolean[k]; int n = 0, ans = 0; while (true) { // at most k times, because 0 <= remainder < k ++ ans; ...
class Solution { public: int smallestRepunitDivByK(int k) { if(k&1==0)return -1; long long val=0; for(int i=1; i<=k;i++) { // val=((val*10)+1); if((val=(val*10+1)%k)==0)return i; } return -1; } };
/** * @param {number} k * @return {number} */ var smallestRepunitDivByK = function(k) { if( 1 > k > 1e6 ) return -1; let val = 0; for (let i = 1; i < 1e6; i++) { val = (val * 10 + 1) % k; if (val === 0) return i; } return -1; };
Smallest Integer Divisible by K
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. &nbsp; Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3 &nbsp; Constraints: The number of no...
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int: n=0 stack=[] # to store the elements cur=root # ...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * ...
class Solution { public: void findInorder(TreeNode* root, vector<int> &ans) { if(root == NULL) return; findInorder(root->left, ans); ans.push_back(root->val); findInorder(root->right, ans); } int kthSmallest(TreeNode* root, int k) { vector<int> ans; ...
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} k * @return {number} */ var kthSmall...
Kth Smallest Element in a BST
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of the division is rounded to the nearest intege...
class Solution: def helper(self,nums,m): Sum = 0 for n in nums: Sum += math.ceil(n/m) return Sum def smallestDivisor(self, nums: List[int], threshold: int) -> int: l,r = 1, max(nums) while l < r: mid = (l+r)//2 Sum = self.helper(nu...
class Solution { public int smallestDivisor(int[] a, int h) { int l = 1, r = a[0]; for (int x : a) if (x > r) r = x; while (l < r) { int m = l + (r-l)/2; if (valid(a, m, h)) r = m; else l = m + 1; } return l; } private boolean va...
class Solution { public: int smallestDivisor(vector<int>& nums, int threshold) { int l=1,r=0; for(int n:nums)r=max(r,n); int mid,s=0; while(l<r){ s=0; mid = l+(r-l)/2; for(int n:nums){ s+= n/mid + (n%mid !=0); } ...
var smallestDivisor = function(nums, threshold) { let left = 1; let right = nums.reduce((r, x) => Math.max(r, x), 0); while (left <= right) { const div = Math.floor((left + right) / 2); const sum = nums.reduce((r, x) => r + Math.ceil(x / div), 0); if (sum <= threshold) ...
Find the Smallest Divisor Given a Threshold
A valid encoding of an array of words is any reference string s and array of indices indices such that: words.length == indices.length The reference string s ends with the '#' character. For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is e...
class Solution: def minimumLengthEncoding(self, words): # root of suffix trie trie_root = dict() # helper function to judge leaf node isLeafNode = lambda node: len(node) == 0 # collection of tail nodes tail_nodes = [] ...
class Node { private boolean flag; private Node[] children; public Node () { flag = false; children = new Node[26]; Arrays.fill (children, null); } public boolean getFlag () { return flag; } public Node getChild (int index) { return children[index];...
class TrieNode{ public: bool isEnd; vector<TrieNode*> children; TrieNode(){ isEnd = false; children = vector<TrieNode*>(26, NULL); } }; class Trie{ public: TrieNode* root; Trie(){ root = new TrieNode(); } void insert(string& word, bool& isSuffix){ au...
/** * @param {string[]} words * @return {number} */ class Trie { constructor(letter) { this.letter = letter; this.children = new Map(); this.isWord = false; } } var minimumLengthEncoding = function(words) { let minEncodingLength = 0; const sortedWords = words.sort((a, b) => a...
Short Encoding of Words
Consider all the leaves of a binary tree, from&nbsp;left to right order, the values of those&nbsp;leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar&nbsp;if their leaf value sequence is the same. Return t...
# class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: tree=[] def inorder(root): nonlo...
class Solution { public boolean leafSimilar(TreeNode root1, TreeNode root2) { List<Integer> list1 = new ArrayList<>(); checkLeaf(root1, list1); List<Integer> list2 = new ArrayList<>(); checkLeaf(root2, list2); if(list1.size() != list2.size()) return false; int i = 0...
/** * 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...
/* * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root1 * @param {TreeNode} root2 * @return {boolea...
Leaf-Similar Trees
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. &nbsp; Example 1: Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,nul...
class Solution(object): def increasingBST(self, root): def sortBST(node): if not node: return [] # return the in order BST nodes in list return sortBST(node.left) + [node.val] + sortBST(node.right) # the in order sorted l...
class Solution { TreeNode inRoot = new TreeNode(); TreeNode temp = inRoot; public TreeNode increasingBST(TreeNode root) { inorder(root); return inRoot.right; } public void inorder(TreeNode root) { if(root==null) return; inorder(root.left); temp.rig...
/** * 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 increasingBST = function(root) { let newRoot = new TreeNode(-1); const newTree = newRoot; const dfs = (node) => { if (!node) return null; if (node.left) dfs(node.left); const newNode = new TreeNode(node.val); newRoot.right = newNode; newRoot.left = null; ...
Increasing Order Search Tree
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1: The test cases are generated such that there are no cycles anywhere...
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: m = 0 n = 0 temp = headA while temp != None: m+=1 temp = temp.next temp = headB while temp != None: n+=1 temp = temp....
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode tempA = headA, tempB = headB; int lenA = 0, lenB = 0; while (tempA != null) { lenA++; tempA = tempA.next; } while (tempB != null) { lenB+...
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: //function to get length of linked list int getLength(ListNode *head) { //initial length 0 int l = 0; while(he...
var getIntersectionNode = function(headA, headB) { let node1 = headA; let node2 = headB; const set = new Set() while(node1 !== undefined || node2!== undefined){ if(node1 && set.has(node1)){ return node1 } if(node2 && set.has(node2)){ return node2 }...
Intersection of Two Linked Lists
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. &nbsp; Example 1: Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] Output: true Explanation: In this case, n = 3, and e...
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: lst = [0]*len(matrix) for i in matrix: if len(set(i)) != len(matrix): return False for j in range(len(i)): lst[j] += i[j] return len(set(lst)) == 1
class Solution { public boolean checkValid(int[][] matrix) { int n = matrix.length; int num = (n*(n+1))/2; // SUM of n number 1 to n; for(int i=0; i<n; i++) { HashSet<Integer> hs = new HashSet<Integer>(); HashSet<Integer> hs1 = new HashSet<Integer>(); ...
class Solution { public: bool checkValid(vector<vector<int>>& matrix) { int n=matrix.size(); unordered_set<int> s1, s2; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(s1.find(matrix[i][j])!=s1.end()) return false; ...
var checkValid = function(matrix) { for(let i =0; i<matrix.length;i++){ const cols = new Set(), rows = new Set(matrix[i]); for(let j =0; j<matrix.length;j++){ if(matrix[j][i] > matrix.length) return false; cols.add(matrix[j][i]) } if(cols.size < matr...
Check if Every Row and Column Contains All Numbers
You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i]. Return the length of the shortest sequence of rolls that cannot be taken from rolls. A sequence of rolls of length len is the result of rolling a k si...
class Solution: def shortestSequence(self, rolls: List[int], k: int) -> int: ans = 1 data = set() for roll in rolls: data.add(roll) if len(data) == k: ans += 1 data.clear() return ans
class Solution { public int shortestSequence(int[] rolls, int k) { int len = 0; Set<Integer> set = new HashSet<>(); for(int i:rolls) { set.add(i); if(set.size()==k) { set = new HashSet<>(); len++; } ...
class Solution { public: int shortestSequence(vector<int>& rolls, int k) { int len = 1; set<int> data ; for (int i = 0; i < rolls.size(); i++) { data.insert(rolls[i]); if (data.size() == k) { len++; data = set<int>...
var shortestSequence = function(rolls, k) { let ans=1; let sett=new Set(); for(let i of rolls) { sett.add(i); if(sett.size===k) { ans++; sett=new Set(); } } return ans; };
Shortest Impossible Sequence of Rolls
Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) &nbsp; Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3] Example 2: Input: head = [] Output: [] Example 3:...
class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return head dummy = ListNode(None, head) prev, curr_1, curr_2 = dummy, head, head.next while curr_1 and curr_2: # 1. define temp nodes, temp nodes are comprised o...
class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0) , prev = dummy , curr = head; dummy.next = head; while(curr != null && curr.next != null){ prev.next = curr.next; curr.next = curr.next.next ; prev.next.next = cur...
class Solution { public: ListNode* swapPairs(ListNode* head) { // if head is NULL OR just having a single node, then no need to change anything if(head == NULL || head -> next == NULL) { return head; } ListNode* temp; // temporary pointer to store head -> next ...
var swapPairs = function(head) { if(!head || !head.next) return head; // using an array to store all the pairs of the list let ptrArr = []; let ptr = head; while(ptr) { ptrArr.push(ptr); let nptr = ptr.next ? ptr.next.next : null; if(nptr) ptr.next.next = nul...
Swap Nodes in Pairs
There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit. Given the array answers, return the minimum number of rabbits that could be in the forest. &nbs...
class Solution: def numRabbits(self, answers: List[int]) -> int: counts = {} count = 0 for answer in answers: if answer == 0: # This must be the only rabbit of its color. count += 1 elif answer not in counts or counts[answer] == 0: ...
class Solution { public int numRabbits(int[] answers) { HashMap<Integer, Integer> map = new HashMap<>(); int count = 0; for(int ele : answers) { if(!map.containsKey(ele+1)) { map.put(ele+1, 1); count += ele+1; } ...
class Solution { public: int numRabbits(vector<int>& answers) { sort(answers.begin(),answers.end()); int ans = 0; for(int i=0;i<answers.size();i++){ ans += answers[i]+1; int num = answers[i]; while(answers[i]==answers[i+1] && num>0 && i+1<answers.size()){ ...
/** * @param {number[]} answers * @return {number} */ var numRabbits = function(answers) { var totalRabbits = 0; var sumOfLikeAnswers = new Array(1000).fill(0); for (let i = 0; i < answers.length; i++) { sumOfLikeAnswers[answers[i]] += 1; } for (let i = 0; i < sumOfLikeAnsw...
Rabbits in Forest
You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times: Choose two elements x and y from nums. Choose a bit in x and swap it with its co...
class Solution: def minNonZeroProduct(self, p: int) -> int: mod = 10**9+7 return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod
class Solution { public int mod = 1_000_000_007; public int minNonZeroProduct(int p) { if (p == 1) return 1; long mx = (long)(Math.pow(2, p)) - 1; long sm = mx - 1; long n = sm/2; long sum = rec(sm, n); return (int)(sum * (mx % mod) % mod); ...
class Solution { public: long long myPow(long long base, long long exponent, long long mod) { if (exponent == 0) return 1; if (exponent == 1) return base % mod; long long tmp = myPow(base, exponent/2, mod); if (exponent % 2 == 0) { // (base ^ exponent/2) * (base ^ e...
var minNonZeroProduct = function(p) { p = BigInt(p); const MOD = BigInt(1e9 + 7); const first = ((1n << p) - 1n); const half = first / 2n; const second = powMOD(first - 1n, half); return (first * second) % MOD; function powMOD(num, exp) { if (exp === 0n) retu...
Minimum Non-Zero Product of the Array Elements
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose d...
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: matrix = [[float('inf')] * n for _ in range(n)] # initializing the matrix for u, v, w in edges: matrix[u][v] = w matrix[v][u] = w for u in range(n)...
class Solution { public int findTheCity(int n, int[][] edges, int distanceThreshold) { int[][] graph = new int[n][n]; for(int[] row: graph) Arrays.fill(row, Integer.MAX_VALUE); for(int i = 0; i < n; i++) graph[i][i] = 0; for(int[] edge: edges...
class Solution { public: unordered_map<int,int>m; int findTheCity(int n, vector<vector<int>>& edges, int threshold) { vector<vector<pair<int,int>>>adj(n); for(auto x:edges) { adj[x[0]].push_back({x[1],x[2]}); adj[x[1]].push_back({x[0],x[2]}); } int ind...
var findTheCity = function(n, edges, distanceThreshold) { const dp = Array.from({length: n}, (_, i) => { return Array.from({length: n}, (_, j) => i == j ? 0 : Infinity) }); for(let edge of edges) { const [a, b, w] = edge; dp[a][b] = dp[b][a] = w; } // k is intermediate node...
Find the City With the Smallest Number of Neighbors at a Threshold Distance
Given an array of integers arr, and three integers&nbsp;a,&nbsp;b&nbsp;and&nbsp;c. You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k])&nbsp;is good if the following conditions are true: 0 &lt;= i &lt; j &lt; k &lt;&nbsp;arr.length |arr[i] - arr[j]| &lt;= a |arr[j] - arr[k]| &lt;= b |...
class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: count = 0 for i in range(len(arr)): for j in range(i+1,len(arr)): for k in range(j+1,len(arr)): if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k...
class Solution { public int countGoodTriplets(int[] arr, int a, int b, int c) { int total = 0; for (int i = 0; i < arr.length - 2; i++){ for (int j = i+1; j < arr.length - 1; j++){ for (int k = j+1; k < arr.length; k++){ if (helper(arr[i], arr[j]) <= a...
class Solution { public: int countGoodTriplets(vector<int>& arr, int a, int b, int c) { int ct = 0; for(int i = 0; i<arr.size()-2; i++) { for(int j = i+1; j<arr.size()-1; j++) { if(abs(arr[i]-arr[j])<=a) for(int k = j+1; k<arr.size(...
var countGoodTriplets = function(arr, a, b, c) { let triplets = 0; for (let i = 0; i < arr.length - 2; i++) { for (let j = i + 1; j < arr.length - 1; j++) { if (Math.abs(arr[i] - arr[j]) > a) continue; for (let k = j + 1; k < arr.length; k++) { if (Math.abs(arr[j] - arr[k]) > b || Math.abs(...
Count Good Triplets
A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any f...
class Solution: def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int: fb = set(fb) q = deque([[0,0,True]]) while(q): n,l,isf = q.popleft() if(n<0 or n in fb or n>2000+2*b): continue fb.add(n) if(n==x): ...
class Solution { public int minimumJumps(int[] forbidden, int a, int b, int x) { // Visited Set Set<Integer> visited = new HashSet<Integer>(); // Add forbidden coordinates to visited for (int i = 0; i < forbidden.length; i++) { visited.add(forbidden[i]);...
class Solution { public: typedef pair<int, bool> pi; int minimumJumps(vector<int> &forbidden, int a, int b, int x) { set<int> st(forbidden.begin(), forbidden.end()); vector<vector<int>> vis(2, vector<int>(10000, 0)); vis[0][0] = 1; vis[1][0] = 1; queue<pi> q; ...
var minimumJumps = function(forbidden, a, b, x) { let f = new Set(forbidden); let m = 2000 + 2 * b; let memo = {}; let visited = new Set(); let res = dfs(0, true); return res === Infinity ? -1 : res; function dfs(i,canJumpBack) { if (i === x) return 0; let key = `${i},${...
Minimum Jumps to Reach Home
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges...
class Solution: def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: p_c = [0] * (n+1) # point counter e_c = defaultdict(int) # edge counter for a,b in edges: p_c[a] += 1 p_c[b] += 1 if a<b: e_c[(a...
class Solution { public int[] countPairs(int n, int[][] edges, int[] queries) { Map<Integer, Map<Integer, Integer>> dupMap = new HashMap<>(); Map<Integer, Set<Integer>> map = new HashMap<>(); int[] ans = new int[queries.length]; int[] count = new int[n]; for (int[] e : edges)...
class Solution { vector<int> st; public: void update(int tind,int tl,int tr,int ind,int val){ if(tl>tr) return; if(tl==tr){ st[tind]+=val; return; } int tm=tl+((tr-tl)>>1),left=tind<<1; if(ind<=tm) update(left,tl,tm,ind,val)...
var countPairs = function(n, edges, queries) { const degree = Array(n+1).fill(0) const edgesMap = new Map() const countMemo = new Map() const answer = [] for(let [u, v] of edges) { degree[u]++ degree[v]++ const key = `${Math.min(u, v)}-${Math.max(u, v)}`; edgesMa...
Count Pairs Of Nodes
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. For example, if chairs 0, 1, and 5 are occupied when a frie...
class Solution: def smallestChair(self, times: List[List[int]], targetFriend: int) -> int: arrivals = [] departures = [] for ind, (x, y) in enumerate(times): heappush(arrivals, (x, ind)) heappush(departures, (y, ind)) d = {} occupied = [0] * len(times)...
class Solution { public int smallestChair(int[][] times, int targetFriend) { int targetStart = times[targetFriend][0]; Arrays.sort(times, (a, b) -> a[0] - b[0]); PriorityQueue<Integer> available = new PriorityQueue<>(); for (int i = 0; i < times.length; ++ i) { available...
class Solution { public: int smallestChair(vector<vector<int>>& times, int targetFriend) { int n = times.size(); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > busy; //departure time as first , index as second priority_queue<int, vector<int>, greate...
/** * @param {number[][]} times * @param {number} targetFriend * @return {number} */ var smallestChair = function(times, targetFriend) { const [targetArrival] = times[targetFriend]; // we need only arrival time const arrivalQueue = times; const leavingQueue = [...times]; arrivalQueue.sort((a, b) => ...
The Number of the Smallest Unoccupied Chair
You are given two strings current and correct representing two 24-hour times. 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. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. ...
class Solution: def HHMMToMinutes(self, s: str) -> int: return int(s[0:2])*60 + int(s[3:5]) def convertTime(self, current: str, correct: str) -> int: diff = self.HHMMToMinutes(correct) - self.HHMMToMinutes(current) order = [60,15,5,1] ops = 0 for i in range(0,4): ...
class Solution { public int HHMMToMinutes(String s){ return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ; } public int convertTime(String current, String correct) { int diff = HHMMToMinutes(correct) - HHMMToMinutes(current); int[] order = {60,15,5,1}; ...
class Solution { public: int HHMMToMinutes(string s){ return stoi(s.substr(0,2))*60 + stoi(s.substr(3,2)); } int convertTime(string current, string correct) { int diff = - HHMMToMinutes(current) + HHMMToMinutes(correct); vector<int> order = {60,15,5,1}; int i = 0; in...
var getTime = function(time){ var [hrs,mins] = time.split(":"); return parseInt(hrs)*60 + parseInt(mins); } var convertTime = function(current, correct) { var diff = getTime(correct) - getTime(current); var order = [60,15,5,1]; var ops = 0; order.forEach(val =>{ ops+=Math.floor((diff/v...
Minimum Number of Operations to Convert Time
Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minim...
class Solution: def minimumOneBitOperations(self, n: int) -> int: if n <= 1: return n def leftmostbit(x): x |= x >> 1 x |= x >> 2 x |= x >> 4 x |= x >> 8 x |= x >> 16 x += 1 x >>= 1 return x ...
class Solution { public int minimumOneBitOperations(int n) { int inv = 0; // xor until n becomes zero for ( ; n != 0 ; n = n >> 1){ inv ^= n; System.out.println(inv+" "+n); } return inv; } }
class Solution { public: int minimumOneBitOperations(int n) { int output = 0; while( n> 0) { output ^= n; n = n >> 1; } return output; } };
/** * @param {number} n * @return {number} */ var minimumOneBitOperations = function(n) { let answer = 0; let op = 1; let bits = 30; while(bits >= 0) { if(n & (1 << bits)) { let tmp = (1 << (bits + 1)) - 1; answer += tmp * op; op *= -1; } bits--; } return answer; }
Minimum One Bit Operations to Make Integers Zero
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. &nbsp; Example 1: Inp...
seen=set() def dfs(i,j,m,n,grid): global seen if (i<0 or i>=m or j<0 or j>=n):return if (i,j) in seen:return seen.add((i,j)) if grid[i][j]=="1": dfs(i,j+1,m,n,grid) dfs(i,j-1,m,n,grid) dfs(i+1,j,m,n,grid) dfs(i-1,j,m,n,grid) class Solution: def numIslands(self, g...
class Solution { public int numIslands(char[][] grid) { int count = 0; int r = grid.length; int c = grid[0].length; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(grid[i][j]=='1'){ dfs(grid,i,j); count++; ...
class Solution { public: void calculate(vector<vector<char>>& grid, int i, int j) { if(i>=grid.size() || j>=grid[i].size() || i<0 || j<0) return; if(grid[i][j]=='0') return; grid[i][j] = '0'; calculate(grid,i,j-1); calculate(grid,i-1,j); ...
/** * @param {character[][]} grid * @return {number} */ var numIslands = function(grid) { const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]] let islandCount = 0 for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) { for (let colIndex = 0; colIndex < grid[0].length; colIndex++) { ...
Number of Islands
Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1. Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc". ...
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: res="" count=0 while len(res)<len(b)+len(a): count+=1 res=a*count if b in res: return count return -1
class Solution { public int repeatedStringMatch(String a, String b) { String copyA = a; int count =1; int repeat = b.length()/a.length(); for(int i=0;i<repeat+2;i++){ if(a.contains(b)){ return count; } else{ a+=copyA...
class Solution { public: int repeatedStringMatch(string a, string b) { int m=a.size(); int n=b.size(); vector<int>d; int mod=n%m; int h=n/m; if(mod==0) {d.push_back(h); d.push_back(h+1); } else { d.push_back(h+1); d.push_back(h+2); } string s=""; string t="";...
var repeatedStringMatch = function(a, b) { const initRepeatTimes = Math.ceil(b.length / a.length); const isMatch = (times) => a.repeat(times).includes(b); if (isMatch(initRepeatTimes)) return initRepeatTimes; if (isMatch(initRepeatTimes + 1)) return initRepeatTimes + 1; return -1; };
Repeated String Match
A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. &nbsp; Example 1: Input: root = [1,1,1,1,1,null,1] Output: true Example 2: Input: root = [2,2,2,5,2] Output: false &nbsp; Constraints: Th...
# 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 isUnivalTree(self, root: Optional[TreeNode]) -> bool: val1 = root.val self.tracker = Fal...
class Solution { boolean ans=true; int firstVal=0; public boolean isUnivalTree(TreeNode root) { if(root==null) return ans; firstVal=root.val; traversal(root); return ans; } private void traversal(TreeNode root) { if(root==null) return; if(root.v...
class Solution { public: bool recur(TreeNode* root, int value){ if(root==NULL) return true; if(root->val!=value){ return false; } return recur(root->left,value) &&recur(root->right,value); } bool isUnivalTree(TreeNode* root) { if(root==NULL) ...
var isUnivalTree = function(root) { if (!root) { return false; } const prev = root.val; const nodes = [root]; for (const node of nodes) { if (node.val !== prev) { return false; } if (node.left) { nodes.push(node.left); } if ...
Univalued Binary Tree
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product bef...
import heapq class Solution: def maximumProduct(self, nums, k: int) -> int: # creating a heap heap = [] for i in nums: heapq.heappush (heap,i) # basic idea here is keep on incrementing smallest number, then only multiplication of that n...
class Solution { public int maximumProduct(int[] nums, int k) { Queue<Integer> pq = new PriorityQueue<>(); for (int num : nums) pq.add(num); while (k-->0) { int top = pq.poll() + 1 ; pq.add(top); } long res = 1; while (!pq...
class Solution { public: int maximumProduct(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end()); while(k--) { int mini = pq.top(); pq.pop(); pq.push(mini + 1); } long long ans = 1, mod = 1e9+7;...
var maximumProduct = function(nums, k) { let MOD = Math.pow(10, 9) + 7; // build a new minimum priority queue // LeetCode loads MinPriorityQueue by default, no need to implement again let queue = new MinPriorityQueue(); for (let i = 0; i < nums.length; i++) { queue.enqueue(nums[i], nums[i]); } // To...
Maximum Product After K Increments
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maxim...
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: total = count_a = count_b = 0 for c in text: if c == pattern[1]: total += count_a count_b += 1 if c == pattern[0]: count_a += 1 ...
class Solution { public long maximumSubsequenceCount(String text, String pattern) { //when pattern[0] == pattern[1] if (pattern.charAt(0) == pattern.charAt(1)) { long freq = 1; //O(N) for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == ...
class Solution { public: long long maximumSubsequenceCount(string text, string pattern) { // support variables int len = text.size(); long long res = 0, aCount = 0, bCount = 0; char a = pattern[0], b = pattern[1]; // getting the frequencies for (char c: text) { ...
/** * @param {string} text * @param {string} pattern * @return {number} */ var maximumSubsequenceCount = function(text, pattern) { const arrText = text.split("") const lengthP0 = arrText.filter(x => x === pattern[0]).length const lengthP1 = arrText.filter(x => x === pattern[1]).length const [c1, c2,...
Maximize Number of Subsequences in a String
You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. &nbsp; Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10],...
def compute(num): if num < 10: return num newVal = 0 while num > 0: last = num % 10 newVal += last num /= 10 return newVal class Solution(object): def countLargestGroup(self, n): """ :type n: int :rtype: int """ myMap = {} for i in range(1, n + 1): val = compute(i) if val in myMap.k...
class Solution { public int countLargestGroup(int n) { Map<Integer,Integer> map=new HashMap<>(); for(int i=1;i<=n;i++){ int x=sum(i); map.put(x,map.getOrDefault(x,0)+1); } int max=Collections.max(map.values()); int c=0; for(int i:map.values()){...
class Solution { public: int cal(int n){ int sum = 0; while(n > 0){ sum += n%10; n /= 10; } return sum; } int countLargestGroup(int n) { int a[40]; for(int i=0; i<40; i++) a[i] = 0; for(int i=1; i<=n; i++){ a[cal(i...
var countLargestGroup = function(n) { const hash = {}; for (let i = 1; i <= n; i++) { const sum = i.toString().split('').reduce((r, x) => r + parseInt(x), 0); if (!hash[sum]) { hash[sum] = 0; } hash[sum]++; } return Object.keys(hash) .sort((a, b) =...
Count Largest Group
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr, do the following: Choose a ...
class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: # creating a borad map to loop-up the square value board_map = {} i = 1 b_rev = board[::-1] for d, r in enumerate(b_rev): # reverse for even rows - here d is taken as direction ...
class Solution { //what if we have changed the dice number, or changing the starting index or changing the ending index //so i have covered all possible ways in which this question can be asked //bfs tip:- for better bfs, we can use marking first and then inserting it in the queue which works faster then remov...
class Solution { public: int snakesAndLadders(vector<vector<int>>& board) { unordered_map<int, int> mp; int n = board.size(); for(int i = n-1; i >= 0; i--) { for(int j = 0; j < n; j++) { if(board[i][j] != -1) { int val; if((...
var snakesAndLadders = function(board) { let n = board.length; let seen = new Set(); let queue = [[1, 0]]; while (queue.length) { let [label, step] = queue.shift(); //console.log(label, step); let [r, c] = labelToPosition(label, n); //console.log(r, c, n); if (board[r][c] !== -1) { ...
Snakes and Ladders
Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. &nbsp; Example 1: Input: n = 5 Output: 5 Explanation: Here are the non-negative integers &lt;= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 ...
class Solution: def findIntegers(self, n: int) -> int: b=(bin(n).replace("0b","")) dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)] def fun(i,last,tight,leading_zeros): if i==len(str(b)): return 1 if dp[i][tight][l...
class Solution { public int findIntegers(int n) { int val=0,res=0,cn=n,digi=0,prevdig=0,i;//digi means bin digi while(cn>0){ cn=cn>>1; digi++; } int dp[]=new int[digi+1]; dp[0]=1;dp[1]=2; for(i=2;i<=digi;i++) dp[i]=dp[i-1]+dp[i-2]; ...
class Solution { public: int dp[31][2]; vector<int> f(){ vector<int> res(31, 1); dp[1][0]=0; dp[1][1]=1; for(int i=2; i<31; i++){ dp[i][0]=dp[i-1][0]+dp[i-1][1]; dp[i][1]=dp[i-1][0]; } for(int i=1; i<31; i++){ ...
var findIntegers = function(n) { let dp = len=>{ if (len<0) return 0; if (!len) return 1; let _0x = 1; // number of accepted combination when '1' is first let _1x = 1; // number of accepted combination when '0' is first while (--len) [_0x, ...
Non-negative Integers without Consecutive Ones
There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. A path from node start to node...
class Solution: def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: dct_nd = {} dist_to_n = {} queue = deque() # from n-node to 1-node visited = set() # 1 step: create dictionary with nodes and nodes' distances to n # cre...
class Solution { int dp[]; //We use memoization public int countRestrictedPaths(int n, int[][] edges) { int[] dist = new int[n+1]; dp = new int[n+1]; Arrays.fill(dp,-1); Map<Integer, Map<Integer, Integer>> graph = new HashMap<>(); //Create the graph from input edges ...
typedef pair<int, int> pii; class Solution { public: int countRestrictedPaths(int n, vector<vector<int>>& edges) { unordered_map<int, vector<pair<int, int>>> gp; for (auto& edge : edges) { gp[edge[0]].push_back({edge[1], edge[2]}); gp[edge[1]].push_back({edge[0], edge[2]}); ...
var countRestrictedPaths = function(n, edges) { // create an adjacency list to store the neighbors with weight for each node const adjList = new Array(n + 1).fill(null).map(() => new Array(0)); for (const [node1, node2, weight] of edges) { adjList[node1].push([node2, weight]); adjList[node2]...
Number of Restricted Paths From First to Last Node
The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations. &n...
class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: nums.sort() sums, i, ans = 0, 0, 0 for j in range(len(nums)): sums += nums[j] while nums[j]*(j-i+1) > sums+k: sums -= nums[i] i = i+1 ans = max(ans, j-i...
class Solution { public int maxFrequency(int[] nums, int k) { //Step-1: Sorting-> Arrays.sort(nums); //Step-2: Two-Pointers-> int L=0,R=0; long totalSum=0; int res=1; //Iterating over the array: while(R<nums.length) { totalSum+=nums...
#define ll long long class Solution { public: int maxFrequency(vector<int>& nums, int k) { // sorting so that can easily find the optimal window sort(nums.begin(), nums.end()); // left - left pointer of window // right - right pointer of window int left = 0, right = 0, ans ...
var maxFrequency = function(nums, k) { // We sorted because as we are allowed only to increment the value & we try to increase the smaller el to some larger el nums.sort((a,b)=>a-b); let left=0; let max=Math.max(); // without any args, Math.max() is -Infinity let curr=0; // I have used 'for loop' ...
Frequency of the Most Frequent Element
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order. &nbsp; Example 1: Input: s = "()())()" Output: ["(())()","()()()"] Example 2: Input: s = "(a)())()" Outp...
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: ## RC ## ## APPROACH : BACK-TRACKING ## ## Similar to Leetcode 32. Longest Valid Parentheses ## ## LOGIC ## # 1. use stack to find invalid left and right braces. # 2. if its close brace at in...
class Solution { public List<String> removeInvalidParentheses(String s) { List<String> ans=new ArrayList<>(); HashSet<String> set=new HashSet<String>(); int minBracket=removeBracket(s); getAns(s, minBracket,set,ans); return ans; } public void ge...
class Solution { public: void back_tracking(vector<string>& res, string cus, int lp, int rp, int idx) { if (!lp && !rp) { int invalid = 0; bool flag = true; for (int i = 0; i < cus.size(); i++) { if (cus[i] == '(') invalid++; ...
var removeInvalidParentheses = function(s) { const isValid = (s) => { const stack = []; for(let c of s) { if(c == '(') stack.push(c); else if(c == ')') { if(stack.length && stack.at(-1) == '(') stack.pop(); else return false...
Remove Invalid Parentheses
Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. &nbsp; Example 1: Input: word1 = ["ab", "c"], word2 = ["a", "bc"] Output: true Explanation: word1 re...
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return True if "".join(word1) == "".join(word2) else False
class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { return(String.join("", word1).equals(String.join("", word2))); } }
class Solution { public: bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) { int wordIdx1 = 0, wordIdx2 = 0, chIdx1 = 0, chIdx2 = 0; while(true) { char ch1 = word1[wordIdx1][chIdx1]; char ch2 = word2[wordIdx2][chIdx2]; if (ch1 !=...
var arrayStringsAreEqual = function(word1, word2) { return word1.join('') === word2.join('') };
Check If Two String Arrays are Equivalent
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, "wrr" is a subset of "warrior" but is not a subset of "world". A string a from words1 is universal if for every string b in words2, b is a subset of a. Retur...
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: freq = [0]*26 for w in B: temp = [0]*26 for c in w: temp[ord(c)-97] += 1 for i in range(26): freq[i] = max(freq[i], temp[i]) ans = [] for w ...
class Solution { public List<String> wordSubsets(String[] words1, String[] words2) { List<String> list=new ArrayList<>(); int[] bmax=count(""); for(String w2:words2) { int[] b=count(w2); for(int i=0;i<26;i++) { bmax[i]=Math.max(bmax...
class Solution { public: // calculate the frequency of string s vector<int> giveMeFreq(string s) { vector<int> freq(26,0); for(int i = 0; i < s.length(); i++) { freq[s[i] - 'a']++; } return freq; } vector<string> wordSubsets(vector<string>& wo...
var wordSubsets = function(words1, words2) { this.count = Array(26).fill(0); let tmp = Array(26).fill(0); for(let b of words2){ tmp = counter(b); for(let i=0; i<26; i++) count[i] = Math.max(count[i], tmp[i]); } let list = [] for(let a of words1) if(isSub(count...
Word Subsets
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. &nbsp; Example 1: Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2: Input: barcodes = [1...
import heapq class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: barcodes_counter = Counter(barcodes) if len(barcodes_counter) == len(barcodes): return barcodes barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ] heapq.heapify(b...
class Solution { public int[] rearrangeBarcodes(int[] barcodes) { if(barcodes.length <= 2){ return barcodes ; //Problem says solution always exist. } Map<Integer, Integer> count = new HashMap<>(); Integer maxKey = null; // Character having max frequency ...
class Solution { public: struct comp{ bool operator()(pair<int,int>&a, pair<int,int>&b){ return a.first < b.first; } }; vector<int> rearrangeBarcodes(vector<int>& barcodes) { unordered_map<int,int> hmap; int n = barcodes.size(); if(n==1)return barcode...
var rearrangeBarcodes = function(barcodes) { var result = []; var map = new Map(); barcodes.forEach(n => map.set(n, map.get(n) + 1 || 1)); let list = [...map.entries()].sort((a,b) => {return b[1]-a[1]}) let i = 0; //list[i][0]=>number list[i][1]=>count of this number while(result.length!==barcod...
Distant Barcodes
Given a 2D grid of size m x n&nbsp;and an integer k. You need to shift the grid&nbsp;k times. In one shift operation: Element at grid[i][j] moves to grid[i][j + 1]. Element at grid[i][n - 1] moves to grid[i + 1][0]. Element at grid[m&nbsp;- 1][n - 1] moves to grid[0][0]. Return the 2D grid after applying shift ...
class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) cache = [] for i in range(m): for j in range(n): cache.append(grid[i][j]) k %= len(cache) new_vals = cache[-k:] + cache[:...
class Solution { public List<List<Integer>> shiftGrid(int[][] grid, int k) { // just bruteforce??? O(i*j*k) // instead we calculate the final position at once! int m = grid.length; // row int n = grid[0].length; // column int[][] arr = new int[m][n]; ...
class Solution { public: vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) { deque<int>dq; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[i].size();j++){ dq.push_back(grid[i][j]); } } int last = dq.s...
/** * @param {number[][]} grid * @param {number} k * @return {number[][]} */ var shiftGrid = function(grid, k) { let m = grid.length let n = grid[0].length for (let r = 0; r < k; r++) { const newGrid = Array(m).fill("X").map(() => Array(n).fill("X")) for (let i = 0; i < m; i++) { ...
Shift 2D Grid
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: s = "abbcccaa" Output:...
class Solution: def countHomogenous(self, s: str) -> int: res, count, n = 0, 1, len(s) for i in range(1,n): if s[i]==s[i-1]: count+=1 else: if count>1: res+=(count*(count-1)//2) count=1 if count>1...
class Solution { public int countHomogenous(String s) { int res = 1; int carry = 1; int mod = 1000000007; for(int i =1;i<s.length();i++){ if(s.charAt(i) == s.charAt(i-1)) carry++; else carry = 1; res = (res + carry) % mod; } return...
class Solution { public: int countHomogenous(string s) { int mod=1e9+7,size=s.size(),i=0,j=0,count=0; while(j<size){ if(s[j]!=s[j+1]){ long n=j-i+1; count = count + (n*(n+1)/2)%mod; i=j+1; } j++; } re...
var countHomogenous = function(s) { let mod = 1e9 + 7 let n = s.length let j=0, res = 0 for(let i=0; i<n; i++){ if(i>0 && s[i-1] != s[i]){ let x = i-j res += x*(x+1) / 2 j = i } } let x = n-j res += x*(x+1) / 2 return res%mod...
Count Number of Homogenous Substrings
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: The area of the rectangular web page you designed must equal to the given target area. ...
class Solution: def constructRectangle(self, area: int): y = Solution.mySqrt(area) for i in range(y, 0, -1): if not area%i: return [int(area/i), i] def mySqrt(x): if x == 0: return 0 n = x count = 0 while True: ...
class Solution { public int[] constructRectangle(int area) { int minDiff = Integer.MAX_VALUE; int[] result = new int[2]; for (int w = 1; w*w <= area; w++) { if (area % w == 0) { int l = area / w; int diff = l - w; if (diff ...
class Solution { public: vector<int> constructRectangle(int area) { int sq = sqrt(area); while (sq > 1) { if (area % sq == 0) break; sq--; } return {area / sq, sq}; } };
/** * @param {number} area * @return {number[]} */ var constructRectangle = function(area) { let w = Math.floor(Math.sqrt(area)) while(area % w != 0) w-- return [area/w, w] };
Construct the Rectangle
A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a string of the c...
class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: i1=num1.index('+') i2=num2.index('+') a=int(num1[0:i1]) x=int(num2[0:i2]) b=int(num1[i1+1:len(num1)-1]) y=int(num2[i2+1:len(num2)-1]) ans1=a*x+(-1)*b*y ans2=a*y+b*x r...
class Solution { public String complexNumberMultiply(String num1, String num2) { int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+'))); int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1)); int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+'...
class Solution { public: pair<int,int> seprateRealAndImg(string &s){ int i = 0; string real,img; while(s[i] != '+') real += s[i++]; while(s[++i] != 'i') img += s[i]; return {stoi(real),stoi(img)}; } string complexNumberMultiply(string num1, string num2) { ...
var complexNumberMultiply = function(num1, num2) { let [realA, imaginaryA] = num1.split('+'); let [realB, imaginaryB] = num2.split('+'); imaginaryA = parseInt(imaginaryA); imaginaryB = parseInt(imaginaryB); const real = realA * realB - imaginaryA * imaginaryB; const imaginary = realA * imaginaryB + imaginaryA * r...
Complex Number Multiplication
You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. Return the minimal number of characters that you need to change ...
class Solution: def palindromePartition(self, s: str, t: int) -> int: n=len(s) @lru_cache(None) def is_palin(s): #This function returns min no of chars to change to make s as a palindrome cnt=0 for c1,c2 in zip(s,s[::-1]): if c1!=c2: cnt...
class Solution { public int mismatchCount(String s) { int n = s.length()-1; int count = 0; for(int i=0,j=n;i<j;i++,j--) { if(s.charAt(i) != s.charAt(j)) count++; } return count; } public int helper(String s, int n, int i, int j, int k, Inte...
class Solution { public: int dp[105][105]; /// Count Number of changes to be done /// to make substring of s from i to j /// to palindrome int changes(int i , int j , string& s){ int cnt = 0; while(i < j){ cnt += (s[i++] != s[j--]); } return cnt; } int recur(int idx, int k, string &s){ /// If Re...
var palindromePartition = function(s, k) { const len = s.length; const cost = (i = 0, j = 0) => { let c = 0; while(i <= j) { if(s[i] != s[j]) c++; i++, j--; } return c; } const dp = Array.from({ length: len }, () => { return new Array(k +...
Palindrome Partitioning III
Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) &nbsp; Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [5,6,3,2,4,1] Examp...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def postorder(self, root: 'Node') -> List[int]: ans=[] def post(root): nonlocal ans if not root: ...
class Solution { List<Integer> result = new ArrayList<>(); public List<Integer> postorder(Node root) { addNodes(root); return result; } void addNodes(Node root) { if (root == null) return; for (Node child : root.children) addNodes(child); result.add(root.val)...
class Solution { public: void solve(Node*root,vector<int>&ans){ if(root==NULL)return; for(int i=0;i<root->children.size();i++){ solve(root->children[i],ans); } ans.push_back(root->val); } vector<int> postorder(Node* root) { vector<int>ans; solve(r...
var postorder = function(root) { const res = []; function post(node) { if (!node) return; for (let child of node.children) { post(child); } res.push(node.val); } post(root); return res; };
N-ary Tree Postorder Traversal
You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k. You are allowed to choose exactly one element from each row to form an array. Return the kth smallest array sum among all possible arrays. &nbsp; Example 1: Input: mat = [[1,3,11],[2,4,6]], k = 5 Output: 7 Explanati...
class Solution: def kthSmallest(self, mat: List[List[int]], k: int) -> int: def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: h = [(nums1[0]+nums2[0],0,0)] visited = set() res = [] while h and k > 0: e, i, j = h...
class Solution { public int kthSmallest(int[][] mat, int k) { int[] row = mat[0]; for(int i=1; i<mat.length; i++) { row = findKthSmallest(row, mat[i], k); } return row[k-1]; } private int[] findKthSmallest(int[] num1, int[] num2, int k) { ...
class Solution { public: vector<int> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { auto cmp = [&nums1,&nums2](pair<int,int> a, pair<int,int>b){ return nums1[a.first]+nums2[a.second] > nums1[b.first]+nums2[b.second]; }; int n = nums1.size(); i...
/** * @param {number[][]} mat * @param {number} k * @return {number} */ var kthSmallest = function(mat, k) { var m = mat.length; var n = m ? mat[0].length : 0; if (!m || !n) return -1; var sums = [0]; for (var idx = 0; idx < m; idx++) { var newSums = [] for (var sum of sums) { ...
Find the Kth Smallest Sum of a Matrix With Sorted Rows
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: You...
class Solution: def totalFruit(self, fruits: List[int]) -> int: ans=0 fruitdict=defaultdict() stack=[] i,j=0,0 while j<len(fruits): if fruits[j] not in fruitdict and len(fruitdict)<2: stack.append(fruits[j]) fruitdict[fruits[j]]=j ...
class Solution { public int totalFruit(int[] fruits) { if (fruits == null || fruits.length == 0) { return 0; } int start = 0, end = 0, res = 0; HashMap<Integer, Integer> map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit ...
class Solution { public: int totalFruit(vector<int>& fruits) { int i=0, j=0, ans = 1; unordered_map<int, int>mp; while(j<fruits.size()){ mp[fruits[j]]++; if(mp.size()<2){ ans = max(ans, j-i+1); j++; } ...
var totalFruit = function(fruits) { let myFruits = {}; let n = fruits.length; let windowStart = 0; let ans = -Number.MAX_VALUE; for(let windowEnd = 0; windowEnd < n; windowEnd++) { let fruit = fruits[windowEnd]; if(fruit in myFruits) { myFruits[fruit]++; ...
Fruit Into Baskets
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the construc...
class Solution: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []
class Solution { public int[][] construct2DArray(int[] original, int m, int n) { if (original.length != m * n) return new int[0][]; int[][] ans = new int[m][n]; int currRow = 0, currCol = 0; for (int num : original) { ans[currRow][currCol++] = nu...
class Solution { public: vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) { if (m * n != original.size()) return {}; vector<vector<int>> res; for (int i = 0; i < m*n; i+=n) res.push_back(vector<int>(original.begin()+i, original.begin()+i+n)); re...
var construct2DArray = function(original, m, n) { if (original.length !== (m*n)) return [] let result = [] let arr = [] for (let i = 0; i < original.length; i++){ arr.push(original[i]) if (arr.length === n){ result.push(arr) arr = [] } } return res...
Convert 1D Array Into 2D Array
Given a positive integer n,&nbsp;you can apply one of the following&nbsp;operations: If n is even, replace n with n / 2. If n is odd, replace n with either n + 1 or n - 1. Return the minimum number of operations needed for n to become 1. &nbsp; Example 1: Input: n = 8 Output: 3 Explanation: 8 -&gt; 4 -&gt; 2 -&...
class Solution: def integerReplacement(self, n: int) -> int: dp = {} def dfs(num): if num == 1: return 0 if num in dp: return dp[num] # if num is even, we have only one option -> n / 2 even = odd = 0 if num...
class Solution { public int integerReplacement(int n) { return (int)calc(n,0); } public long calc(long n,int i){ if(n==1) return i; if(n<1) return 0; long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE; if(n%2==0) ...
class Solution { public: int integerReplacement(int n) { return helper(n); } int helper(long n) { if(n == 1) return 0; if(n % 2) return 1 + min(helper(n - 1), helper(n + 1)); return 1 + helper(n / 2); } };
var integerReplacement = function(n) { let count=0; while(n>1){ if(n%2===0){n/=2;} else{ if(n!==3 && (n+1)%4===0){n++;} else{n--;} } count++; } return count; };
Integer Replacement
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise. &nbsp; Example 1: Input: root = [10,4,6] Output: true Explanation: The values of the...
class Solution: def checkTree(self, root: Optional[TreeNode]) -> bool: return root.val == (root.left.val + root.right.val)
class Solution { public boolean checkTree(TreeNode root) { return root.val == root.left.val + root.right.val; // O(1) } }
class Solution { public: bool checkTree(TreeNode* root) { if(root->left->val+root->right->val==root->val){ return true; } return false; } };
var checkTree = function(root) { return root.val === root.left.val + root.right.val; };
Root Equals Sum of Children
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. &nbsp; Example 1: Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","...
class Solution: def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: set_words = set(words) def check(word, seen): if word == '': return True for i in range(len(word) if seen else len(word) - 1): if word[:...
class Solution { Set<String> set = new HashSet<>(); Set<String> res = new HashSet<>(); int index = 0; public List<String> findAllConcatenatedWordsInADict(String[] words) { for (String word: words) set.add(word); for (String word: words) { int len = word.length(); index = 0; b...
class Solution { public: int checkForConcatenation( unordered_set<string>& st, string w, int i, vector<int>& dp){ if(i == w.size()) return 1; if(dp[i] != -1) return dp[i]; for(int j = i; j < w.size(); ++j ){ string t = w.substr(i, j-i+1); if(t.size() != w.size() && st...
class Node { val; children; isWord = false; constructor(val) { this.val = val; } } class Trie { nodes = Array(26); addWord(w) { let idx = this.getIdx(w[0]); let node = this.nodes[idx] || new Node(w[0]); this.nodes[idx] = node; for (let i=1; i < w.leng...
Concatenated Words
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. &nbsp; Example 1: Input: s1 = "ab", s2 = "ba" Output: 1 ...
class Solution: def kSimilarity(self, s1: str, s2: str) -> int: n = len(s1) def helper(i, curr, dp): if curr == s2: return 0 if curr not in dp[i]: if curr[i] == s2[i]: dp[i][curr] = helper(i+1, curr, dp...
class Solution { public int kSimilarity(String s1, String s2) { HashSet<String> vis = new HashSet<>(); ArrayDeque<String> queue = new ArrayDeque<>(); int level = 0; queue.add(s1); while(queue.size() > 0){ int size = queue.size(); for(...
class Solution { public: unordered_map<string,int>m; int solve(string &s1,string &s2,int i) { if(i==s1.length()) return 0; if(m.find(s1)!=m.end())return m[s1]; if(s1[i]==s2[i]) return m[s1]=solve(s1,s2,i+1); int ans=1e5; for(int j=i+1;j<s1.leng...
var kSimilarity = function(s1, s2) { // abc --> bca // swap from 0: a !== b, find next b, swap(0,1) --> bac // swap from 1: a !== c, find next c, swap(1,2) --> bca return bfs(s1, s2); }; const bfs = (a,b)=>{ if(a===b) return 0; const visited = new Set(); const queue = []; qu...
K-Similar Strings
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure. void set(String key, String value, int timestamp) Stores th...
class TimeMap: def __init__(self): self.dict = {} def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.dict: self.dict[key] = ([], []) self.dict[key][0].append(value) self.dict[key][1].append(timestamp) else: ...
class TimeMap { private Map<String, List<Entry>> map; private final String NOT_FOUND = ""; public TimeMap() { map = new HashMap<>(); } public void set(String key, String value, int timestamp) { List<Entry> entries = map.getOrDefault(key, new ArrayList<>()); entries.add(n...
class TimeMap { public: map<string,vector<pair<int,string>>> mp; string Max; TimeMap() { Max = ""; } void set(string key, string value, int timestamp) { mp[key].push_back(make_pair(timestamp,value)); Max = max(Max,value); } string get(string key, int timesta...
var TimeMap = function() { this.data = new Map(); }; /** * @param {string} key * @param {string} value * @param {number} timestamp * @return {void} */ TimeMap.prototype.set = function(key, value, timestamp) { if(!this.data.has(key)){ this.data.set(key, [{timestamp: timestamp, value: value}]...
Time Based Key-Value Store
Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime la...
class Solution(object): def busyStudent(self, startTime, endTime, queryTime): res = 0 for i in range(len(startTime)): if startTime[i] <= queryTime <= endTime[i]: res += 1 else: pass return res
class Solution { public int busyStudent(int[] startTime, int[] endTime, int queryTime) { int count = 0; for (int i = 0; i < startTime.length; ++i) { if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count; } return count; } }
class Solution { public: int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) { int ans = 0 ; for(int i = 0 ; i < size(startTime); ++i ) if(queryTime >= startTime[i] and queryTime <= endTime[i]) ++ans ; return ans ; } };
var busyStudent = function(startTime, endTime, queryTime) { let res = 0; for (let i = 0; i < startTime.length; i++) { if (startTime[i] <= queryTime && endTime[i] >= queryTime) res++; } return res; };
Number of Students Doing Homework at a Given Time
A bus&nbsp;has n stops numbered from 0 to n - 1 that form&nbsp;a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number&nbsp;i and (i + 1) % n. The bus goes along both directions&nbsp;i.e. clockwise and counterclockwise. Return the shortest dista...
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: # switch start and destination if destination is before start if start>destination: start,destination=destination,start #find minimum for clockwise and counterclockwis...
class Solution { public int distanceBetweenBusStops(int[] distance, int start, int destination) { int firstDistance = 0; int secondDistance = 0; if (start < destination) { //check clockwise rotation for (int i = start; i < destination; i++) firstDistan...
class Solution { public: int distanceBetweenBusStops(vector<int>& distance, int start, int destination) { int n = distance.size(); if (start == destination) return 0; int one_way = 0; int i = start; while (i != destination) // find distance of one way { ...
/** * @param {number[]} distance * @param {number} start * @param {number} destination * @return {number} */ let sumArray = (arr) => { return arr.reduce((prev, curr) => prev + curr, 0) } var distanceBetweenBusStops = function(distance, start, destination) { let dist = sumArray(distance.slice((start < dest...
Distance Between Bus Stops
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. &nbsp; Example 1: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to pos...
class Solution: def hammingDistance(self, x: int, y: int) -> int: # First, using XOR Bitwise Operator, we take all distinct set bits. z = x ^ y # We inicialize our answer with zero. ans = 0 # Iterate while our z is not zero. while z: # Every iteration we add one to our answer. ...
class Solution { public int hammingDistance(int x, int y) { int ans=x^y; int count=0; while(ans>0){ count+=ans&1; ans>>=1; } return count; } }
class Solution { public: int hammingDistance(int x, int y) { int val = (x^y); int ans = 0; for(int i = 31; i >= 0; --i){ if(val & (1 << i)) ans++; } return ans; } };
var hammingDistance = function(x, y) { x = x.toString(2).split('') y = y.toString(2).split('') let count = 0; const len = Math.max(x.length,y.length); if (x.length < y.length) { x = Array(len - x.length).fill('0').concat(x) } else { y = Array(len - y.length).fill('0').concat(y) } for (let ...
Hamming Distance
A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right, return a list of all the self-dividi...
class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: res = [] for num in range(left, right + 1): num_str = str(num) if '0' in num_str: continue elif all([num % int(digit_str) == 0 for digit_str in num_str]): ...
class Solution { public List<Integer> selfDividingNumbers(int left, int right) { List<Integer> ans= new ArrayList<>(); while(left<=right){ if(fun(left)) ans.add(left); left++; } return ans; } boolean fun(int x){ int k=x;...
class Solution { public: bool check(int n){ vector<bool> isif(10); for(int i = 1; i <= 9; i++){ if(n % i == 0) isif[i] = 1; } while(n > 0){ if(isif[n%10] == 0) return false; n /= 10; } return true; } vector<int> sel...
/** * @param {number} left * @param {number} right * @return {number[]} */ var selfDividingNumbers = function(left, right) { const selfDivisibles = []; for (let i = left; i <= right; i++) { if (checkDivisibility(i)) { selfDivisibles.push(i); } } return selfDivisibles; }; function checkDivisib...
Self Dividing Numbers
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise. &nbsp; Example ...
class Solution: def isPalindrome(self, s: str) -> bool: cleaned = "" for c in s: if c.isalnum(): cleaned += c.lower() return (cleaned == cleaned[::-1])
class Solution { public boolean isPalindrome(String s) { if(s.length()==1 || s.length()==0) { return true; } s=s.trim().toLowerCase(); //s=s.toLowerCase(); String a=""; boolean bool=false; for(int i=0;i<s.length();i++) { ...
class Solution { public: bool isPalindrome(string s) { auto it = remove_if(s.begin(), s.end(), [](char const &c) { return !isalnum(c); }); s.erase(it, s.end()); transform(s.begin(), s.end(), s.begin(), ::tolower); int i = 0; int j = s.size()-1; ...
var isPalindrome = function(s) { const toLower = s.toLowerCase().replace(/[\W_\s]+/g, '').replace(/ /g, '') let m = 0 let n = toLower.length - 1 while (m < n) { if (toLower[m] !== toLower[n]) { return false } m++ n-- } return true }
Valid Palindrome
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target. Note that the letters wrap around. For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'. &nbsp; Example 1: Input: letters = ...
class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: beg = 0 end = len(letters)-1 while beg <= end: mid = (beg+end)//2 if letters[mid]>target: end = mid -1 else: beg = mid +1 return l...
class Solution { public char nextGreatestLetter(char[] letters, char target) { int start=0,end=letters.length-1; while(start<=end){ int mid=start+(end-start)/2; if(letters[mid]>target){ //strictly greater is the solution we want end = mid-1; }else{ start=mid+1; ...
class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { int siz = letters.size(); bool isPresent = false; char ans; char temp = target; if (target == letters[siz-1]) return letters[0]; for(int i=0; i<siz-1; i++) { if (targ...
/** * @param {character[]} letters * @param {character} target * @return {character} */ var nextGreatestLetter = function(letters, target) { let result=[] for (letter of letters){ if (letter>target){ result.push(letter); } } if (result.length){ return result[0]; ...
Find Smallest Letter Greater Than Target
You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. ...
class Solution: def minimumDeviation(self, nums: List[int]) -> int: from sortedcontainers import SortedList for i in range(len(nums)): if nums[i]%2!=0: nums[i]=nums[i]*2 nums = SortedList(nums) result = 100000000000 while True: min_value = nums[0] max_value = nums[-1] if max_value % 2 ...
class Solution { public int minimumDeviation(int[] nums) { TreeSet<Integer> temp = new TreeSet<>(); for(int i: nums){ if(i % 2 == 0){ temp.add(i); } else{ temp.add(i * 2); } } int md = temp.last() - temp...
// πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰Please upvote if it helps πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰ class Solution { public: int minimumDeviation(vector<int>& nums) { int n = nums.size(); int mx = INT_MIN, mn = INT_MAX; // Increasing all elements to as maximum as it can and tranck the minimum, // number and also the resu...
var minimumDeviation = function(nums) { let pq = new MaxPriorityQueue({priority: x => x}) for (let n of nums) { if (n % 2) n *= 2 pq.enqueue(n) } let ans = pq.front().element - pq.back().element while (pq.front().element % 2 === 0) { pq.enqueue(pq.dequeue().element / 2) ...
Minimize Deviation in Array
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. &nbsp; Example 1: Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]] Example 2: Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] ...
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: rows = len(matrix) cols = len(matrix[0]) visited=set() for r in range(rows): for c in range(cols): if matrix[r][c]==0 and (r,c) not in visited : for ...
class Solution { public void setZeroes(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int row = matrix.length; int col = matrix[0].length; boolean firstColumnZero = false; boolean firstRowZero = false; // Check if first column should be made ze...
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { unordered_map<int,int>ump; unordered_map<int,int>mp; for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[0].size();j++){ if(matrix[i][j]==0){ ump[i]=1; ...
var setZeroes = function(matrix) { let rows = new Array(matrix.length).fill(0); //to store the index of rows to be set to 0 let cols = new Array(matrix[0].length).fill(0);//to store the index of columns to be set to 0 for(let i=0; i<matrix.length; i++){ for(let j=0; j<matrix[i].length; j++){ if(matrix[i][j]...
Set Matrix Zeroes
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string. An English letter b is greater than another letter a if b appears after a in the English alph...
class Solution: def greatestLetter(self, s: str) -> str: cnt = Counter(s) return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "")
class Solution { public String greatestLetter(String s) { Set<Character> set = new HashSet<>(); for(char ch : s.toCharArray()) set.add(ch); for(char ch = 'Z'; ch >= 'A'; ch--) if(set.contains(ch) && set.contains((char)('a'+(ch-'A')))) retur...
class Solution { public: string greatestLetter(string s) { vector<int> low(26), upp(26); //storing occurences of lower and upper case letters string res = ""; for(auto it : s) //iterate over each char and mark it in respective vector { if(it-'A'>=0 && it-'A'<26) ...
var greatestLetter = function(s) { let set=new Set(s.split("")); // ASCII(A-Z, a-z)=(65-90, 97-122). for(let i=90; i>=65; i--){ if(set.has(String.fromCharCode(i)) && set.has(String.fromCharCode(i+32))){ return String.fromCharCode(i); } } return ""; };
Greatest English Letter in Upper and Lower Case
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). &nbsp; Example 1: Input: ...
class Solution: def isMatch(self, s: str, p: str) -> bool: m= len(s) n= len(p) dp = [[False]*(n+1) for i in range(m+1)] dp[0][0] = True for j in range(len(p)): if p[j] == "*": dp[0][j+1] = dp[0][j] for i in range(1,m+1): for...
class Solution { public boolean isMatch(String s, String p) { int i=0; int j=0; int starIdx=-1; int lastMatch=-1; while(i<s.length()){ if(j<p.length() && (s.charAt(i)==p.charAt(j) || p.charAt(j)=='?')){ i++; j++; ...
class Solution { public: bool match(int i, int j, string &a, string &b, vector<vector<int>>&dp) { if(i<0 && j<0) return true; if(i>=0 && j<0) return false; if(i<0 && j>=0) { for(;j>-1;j--) if(b[j]!='*') return false; return true; } if(dp[i]...
var isMatch = function(s, p) { const slen = s.length, plen = p.length; const dp = new Map(); const solve = (si = 0, pi = 0) => { // both are compared and are equal till end if(si == slen && pi == plen) return true; // we have consumed are wildcard string and still s is remaini...
Wildcard Matching
Given the head of a singly linked list and two integers left and right where left &lt;= right, reverse the nodes of the list from position left to position right, and return the reversed list. &nbsp; Example 1: Input: head = [1,2,3,4,5], left = 2, right = 4 Output: [1,4,3,2,5] Example 2: Input: head = [5], left = ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: # revrese api def reverse(start, end...
class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if(left==right) return head; ListNode last = null; ListNode present = head; for(int i=0; present != null && i<left-1;i++){ last = present; present = present.next; ...
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverse(ListNode* head) { ...
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} left * @param {number} right * @return {ListNode} */ var reverseBetween = function(h...
Reverse Linked List II
You are given two non-negative integers num1 and num2. In one operation, if num1 &gt;= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operati...
class Solution: def countOperations(self, num1: int, num2: int) -> int: ct=0 while num2 and num1: if num1>=num2: num1=num1-num2 else: num2=num2-num1 ct+=1 return ct
class Solution { public int countOperations(int num1, int num2) { int count=0; while(num1!=0 && num2!=0){ if(num1<num2){ count+=num2/num1; num2=num2%num1; }else{ count+=num1/num2; num1=num1%num2; } ...
class Solution { public: int countOperations(int num1, int num2) { if(num1==0 || num2==0) return 0; if(num1>=num2) num1=num1-num2; else if(num2>num1) num2=num2-num1; return 1+countOperations(num1,num2); } };
/** * @param {number} num1 * @param {number} num2 * @return {number} */ var countOperations = function(num1, num2) { let count = 0; while (num1 !== 0 && num2 !== 0) { if (num1 <= num2) num2 -= num1; else num1 -= num2; count++; } return count; };
Count Operations to Obtain Zero
You are given an array of n strings strs, all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: abc bce cae You want to delete the columns that are not sorted lexicographically. In the above example (0-in...
class Solution: def minDeletionSize(self, strs: List[str]) -> int: cols={} l=len(strs) l_s = len(strs[0]) delete = set() for i in range(l): for col in range(l_s): if col in cols: if cols[col]>strs[i][col]: ...
class Solution { public int minDeletionSize(String[] strs) { int count = 0; for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column for(int j = 0; j < strs.length-1; j++){ if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(...
class Solution { public: int minDeletionSize(vector<string>& strs) { int col = strs[0].size(); int row = strs.size(); int count = 0; for(int c = 0 ; c < col ; c++){ for(int r = 1 ; r < row ; r++){ if(strs[r][c] - strs[r - 1][c] < 0){ co...
/** * @param {string[]} strs * @return {number} */ var minDeletionSize = function(strs) { let count = 0; for(let i=0; i<strs[0].length; i++){ for(let j=0; j<strs.length-1; j++){ if(strs[j].charAt(i) > strs[j+1].charAt(i)){ count++; break; } ...
Delete Columns to Make Sorted
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. &nbsp; Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2...
''' First of all, I'm making a few tuples using zip function. Then extracting every created tuple. (for tup in zip()) After that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup) ''' class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]:...
class Solution { public int[] shuffle(int[] nums, int n) { int[] arr = new int[2*n]; int j = 0; int k = n; for(int i =0; i<2*n; i++) { if(i%2==0) { arr[i] = nums[j]; j++; } else { ...
class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { vector<int> ans; int size = nums.size(); int i = 0, j =0; for(i=0,j=n; i<n && j<size; i++, j++){ ans.push_back(nums[i]); ans.push_back(nums[j]); } return ans; } };
var shuffle = function(nums, n) { while (n--) { nums.splice(n + 1, 0, nums.pop()); } return nums; };
Shuffle the Array
You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match. Return a list answer of size 2 where: answer[0] is a list of all players that have not lost any matches. answer[1] is a list of all players that have lost exactly one mat...
class Solution: def findWinners(self, matches: List[List[int]]) -> List[List[int]]: winners, losers, table = [], [], {} for winner, loser in matches: # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented. # map.get(key, 0) re...
class Solution { public List<List<Integer>> findWinners(int[][] matches) { int[] won = new int[100001]; int[] loss = new int[100001]; for(int[] match : matches) { won[match[0]]++; loss[match[1]]++; } // System.out.print(Arrays.toStrin...
class Solution { public: vector<vector<int>> findWinners(vector<vector<int>>& matches) { unordered_map<int,int> umap; vector<vector<int>> result(2); for(int i=0;i<matches.size();i++) { umap[matches[i][1]]++; } for(auto i=umap.begin();i!=umap.end();i++) ...
/** * @param {number[][]} matches * @return {number[][]} */ var findWinners = function(matches) { var looser = {}; var allPlayer={}; for(var i=0; i<matches.length; i++) { if(looser[matches[i][1]]) looser[matches[i][1]]++; else looser[matches...
Find Players With Zero or One Losses
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]] Example 2: Input: root = [1] Output: [[1]] Ex...
class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] ans = [] node = root q = collections.deque([node]) order = -1 ...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * ...
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> ans; if(!root) return ans; vector<int> r; queue<TreeNode*> q; int count=1; q.push(root); q.push(NULL); while(1){ if(q.front()==NULL){ q.pop(); if(count%...
var zigzagLevelOrder = function(root) { let result = [] if(root == null) return result let queue = [] let leftToRight = true queue.push(root) while(queue.length != 0) { let qSize = queue.length let ans = [] // Processing level for(let i=0;i...
Binary Tree Zigzag Level Order Traversal
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swappe...
class Solution: def minSwaps(self, st: str) -> int: def swap(st,c): n = len(st) mis = 0 for i in range(n): if i%2==0 and st[i]!=c: mis+=1 if i%2==1 and st[i]==c: mis+=1 return mis//2 dic = Counter(st) z...
class Solution { public int minSwaps(String s) { int cntZero=0 , cntOne=0; for(char ch:s.toCharArray()){ if(ch=='0') cntZero++; else cntOne++; } //Invalid if(Math.abs(cntOne-cntZero)>1) return -1; if(cntOne>cntZero){ ...
class Solution { int minFillPos(string& s, char ch, int current = 0) { int count = 0; for(int i=0; i<s.size(); i+=2) { if(s[i] != ch) count++; } return count; } public: int minSwaps(string s) { int oneCount = count(s.begin(), s.end(), '1'); ...
var minSwaps = function(s) { let ones = 0; let zeroes = 0; for(let c of s) { if(c === "1") ones++ else zeroes++ } if(Math.abs(ones - zeroes) > 1) return -1 function count(i) { let res = 0 for(let c of s) { if(i !== c) res++; ...
Minimum Number of Swaps to Make the Binary String Alternating
There are n flights that are labeled from 1 to n. You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range. Return an array answer of length n, where answer[...
class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: flights = [0]*n for start,end,seats in bookings: flights[start-1] += seats if end < n: flights[end] -= seats for i in range(n-1): flights[i+1] += flights[i] return flights
class Solution { public int[] corpFlightBookings(int[][] bookings, int n) { // nums all equals to zero int[] nums = new int[n]; // construct the diffs Difference df = new Difference(nums); for (int[] booking : bookings) { // pay attention to the index ...
class Solution { public: vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) { vector<int> arr(n); for (const auto& b : bookings) { int start = b[0] - 1, end = b[1], seats = b[2]; arr[start] += seats; if (end < n) { arr[end] -= sea...
var corpFlightBookings = function(bookings, n) { // +1 as dummy guard on the tail, which allow us not to check right boundary every time let unitStep = Array(n+1).fill(0); for(const [first, last, seatVector ] of bookings ){ // -1 because booking flight is 1-indexed, given by descr...
Corporate Flight Bookings
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we...
class Solution(object): def maxChunksToSorted(self, arr): n= len(arr) count=0 currentmax= -2**63 for i in range(0,n): currentmax=max(currentmax, arr[i]) if (currentmax==i): count+=1 return count
class Solution { public int maxChunksToSorted(int[] arr) { int max=0, count=0; for(int i=0; i<arr.length; i++){ max = Math.max(arr[i],max); if(i==max) count++; }return count; } }
class Solution { public: int maxChunksToSorted(vector<int>& arr) { // using chaining technique int maxi=INT_MIN; int ans =0; for(int i=0;i<size(arr);i++) { maxi = max(maxi,arr[i]); if(maxi==i) { //.. found partition ...
var maxChunksToSorted = function(arr) { let count = 0, cumSum = 0; arr.forEach((el, index) => { cumSum += el-index; if (cumSum === 0) count++; }); return count; };
Max Chunks To Make Sorted
Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s. Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: s = "10101" Output: 4 Exp...
class Solution: def numWays(self, s: str) -> int: ones = 0 # Count number of Ones for char in s: if char == "1": ones += 1 # Can't be grouped equally if the ones are not divisible by 3 if ones > 0 and ones % 3 != 0: return 0 ...
class Solution { public int numWays(String s) { long n=s.length(); long one=0;//to count number of ones long mod=1_000_000_007; char[] c=s.toCharArray(); for(int i=0;i<c.length;i++) { if(c[i]=='1') one++; } //t...
class Solution { public: int MOD = 1e9 + 7 ; int numWays(string s) { int ones = count(begin(s),end(s),'1') , n = s.size() ; if(ones % 3) return 0 ; if(!ones) return (((n-1) * 1LL * (n-2) * 1LL) / 2) % MOD ; /// n- 1 C 2 int left = 0 , right = 0 , count = 0 , i = 0 ; ...
var numWays = function(s) { let one = 0; let list = []; for(let i = 0; i < s.length; i++){ if(s[i]==="1") one++, list.push(i); } if(one%3!==0) return 0; if(one===0) return ((s.length-1)*(s.length-2)/2) % 1000000007; one/=3; return ((list[one]-list[one-1])*(list[2*one]-list[2*one-...
Number of Ways to Split a String
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or f...
##################################################################################################################### # Problem: Hand of Straights # Solution : Hash Table, Min Heap # Time Complexity : O(n logn) # Space Complexity : O(n) ###################################################################################...
class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { if(hand.length % groupSize != 0) return false; Map<Integer, Integer> map = new HashMap<>(); PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int card : hand){ if(map.cont...
class Solution { public: bool isNStraightHand(vector<int>& hand, int groupSize) { int n = hand.size(); if(n%groupSize != 0) // We can't rearrange elements of size groupsize so return false return false; map<int,int>mp; for(auto it : hand) mp[it]++; w...
var isNStraightHand = function(hand, groupSize) { if(hand.length%groupSize!==0) return false; const map = new Map(); hand.forEach(h=>{ map.set(h,map.get(h)+1||1); }); // sort based on the key in asc order const sortedMap = new Map([...map.entries()].sort((a,b)=>a[0]-b[0])); ...
Hand of Straights
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Return true if you can make this square and false oth...
class Solution: def makesquare(self, matchsticks: List[int]) -> bool: target,m=divmod(sum(matchsticks),4) if m:return False targetLst=[0]*4 length=len(matchsticks) matchsticks.sort(reverse=True) def bt(i): if i==length: return len(set(targe...
/* Time complexity: O(2 ^ n) Space complexity: O(n) Inutition: --------- Same as "Partition to K Equal Sum Subsets" */ class Solution { public boolean backtrack(int[] nums, int idx, int k, int subsetSum, int target, boolean[] vis) { // base case if (k == 0) return t...
class Solution { public: bool makesquare(vector<int>& matchsticks) { int goal = 0, totalSum = 0; for (int i : matchsticks) { totalSum += i; } goal = totalSum / 4; sort(matchsticks.begin(), matchsticks.end(), [](auto left, auto right) { return left > ri...
var makesquare = function(matchsticks) { const perimeter = matchsticks.reduce((a, b) => a + b, 0); if(perimeter % 4 != 0 || matchsticks.length < 4) return false; const sideLen = perimeter / 4; // find a way to divide the array in 4 group of sum side length const sides = new Array(4).fill(0); ...
Matchsticks to Square
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. &nbsp; Example 1: Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7] Example ...
import bisect # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def buildTree(self, inorder, postorder): """ 7 2 ...
class Solution { int[] io; int[] po; int n; // nth post order node public TreeNode buildTree(int[] inorder, int[] postorder) { this.n = inorder.length-1; this.io = inorder; this.po = postorder; return buildTree(0, n); } public TreeNode buildTree(int low, int high) { if(n...
class Solution { public: TreeNode* buildTree(vector<int>& ino, vector<int>& post) { int i1 = post.size()-1; return solve(i1,ino,post,0,ino.size()-1); } TreeNode* solve(int &i,vector<int> &in,vector<int> &post,int l,int r){ if(l>r)return NULL; int x = r; while(post[i] != i...
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[]} inorder * @param {number[]} postorder * @return {TreeNode} ...
Construct Binary Tree from Inorder and Postorder Traversal
Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order. If a folder[i] is located within another folder[j], it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: '/' followed by one or ...
# a TrieNode class for creating new node class TrieNode(): def __init__(self): self.children = {} self.main = False # the main class class Solution(object): def removeSubfolders(self, folder): node = TrieNode() res = [] # sort the list to prevent adding the ...
class Solution { TrieNode root; public List<String> removeSubfolders(String[] folder) { List<String> res = new ArrayList<>(); Arrays.sort(folder, (a, b) -> (a.length() - b.length())); root = new TrieNode(); for (String f : folder) { if (insert(f)) { re...
class Solution { public: int check(string &s,unordered_map<string,int>&mp) { string temp; temp.push_back(s[0]); //for maintaining prefix string for(int i=1;i<s.size();i++) { if(s[i]=='/') { if(mp.count(temp)) //for checking p...
var removeSubfolders = function(folder) { folder = folder.sort() const result = []; for(let i in folder){ const f = folder[i]; if(result.length == 0 || !f.startsWith(result[result.length -1] + "/")) result.push(f); } return result; };
Remove Sub-Folders from the Filesystem