algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: Jumbo Burger: 4 tomato slices and 1 cheese slice. Small Burger: 2 Tomato slices and 1 cheese slice. Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of rem...
class Solution(object): def numOfBurgers(self, t, c): if t==c==0: return [0,0] four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c two=c-four #number of small burgers if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or ...
class Solution { public List<Integer> numOfBurgers(int tomatoSlices, int cheeseSlices) { List<Integer>list=new ArrayList<>(); int ts=tomatoSlices; int cs=cheeseSlices; if (ts<cs*2 || ts>cs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0)) { return list; ...
class Solution { public: vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) { // Observation // Total Number of Burgers is Equal to Number of cheeseSlices // Try to make 1 --> cheeseSlices Amount of Jumbo Burgers and // remaining will be Small Burger vector <int> an...
/** * @param {number} tomatoSlices * @param {number} cheeseSlices * @return {number[]} */ var numOfBurgers = function(tomatoSlices, cheeseSlices) { if (tomatoSlices & 1) return []; // return [] if tomatoSlices is odd const j = (tomatoSlices >> 1) - cheeseSlices; // jumbo = (tomatoSlices / 2) - cheeseSlices ...
Number of Burgers with No Waste of Ingredients
Given an n-ary tree, return the level order 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: [[1],[3,2,4],[5,6]] Exampl...
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] result = [] level = [root] while level: current_level = [] next_level = [] for node in level: c...
class Solution { public List<List<Integer>> result= new ArrayList(); public List<List<Integer>> levelOrder(Node root) { if(root==null) return result; helper(root,0); return result; } private void helper(Node node,int level){ if(result.size()<=level){ result....
class Solution { public: vector<vector<int>> ans; vector<vector<int>> levelOrder(Node* root) { dfs(root, 0); return ans; } void dfs(Node* root, int level) { if(!root) { return; } if(level == ans.size()) { an...
var levelOrder = function(root) { if(!root) return []; const Q = [[root, 0]]; const op = []; while(Q.length) { const [node, level] = Q.shift(); if(op.length <= level) { op[level] = []; } op[level].push(node.val); for(const ...
N-ary Tree Level Order Traversal
There is an exam room with n seats in a single row labeled from 0 to n - 1. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat...
class ExamRoom: def __init__(self, n: int): self.N = n self.pq = [] self.dict = {} self.addSegment(0, self.N - 1) def seat(self) -> int: start, end, distance = heapq.heappop(self.pq) self.dict.pop(start, None) #Remove old segment from dictionary self.dic...
class ExamRoom { private final int max; private final TreeSet<Interval> available; private final TreeSet<Integer> taken; public ExamRoom(int n) { this.max = n - 1; this.available = new TreeSet<>((a, b) -> { var distA = getMinDistance(a); var distB = getMinDistan...
class ExamRoom { public: set<int> s; // ordered set int num; ExamRoom(int n) { num=n; // total seats } int seat() { if(s.size()==0) { s.insert(0); return 0;} // if size is zero place at seat 0 auto itr = s.begin(); if(s.size()==1) { ...
/** * @param {number} n */ var ExamRoom = function(n) { this.n = n this.list = [] }; /** * @return {number} */ ExamRoom.prototype.seat = function() { // if nothing in the list, seat the first student at index 0. if(this.list.length === 0){ this.list.push(0) return 0 } // fi...
Exam Room
Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: s = "aa" Output: 0 Explanation: The optimal substring here is ...
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: last, ans = {}, -1 for i, c in enumerate(s): if c not in last: last[c] = i else: ans = max(ans, i - last[c] - 1) return ans
class Solution { public int maxLengthBetweenEqualCharacters(String s) { int ans = -1; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (map.containsKey(ch)) { ans = Math.max(ans, i - 1 - m...
class Solution { public: int maxLengthBetweenEqualCharacters(string s) { vector<int> v(26, -1); int maxi = -1; for (int i = 0; i < s.size(); i++) { if (v[s[i] - 'a'] == -1) v[s[i] - 'a'] = i; else maxi = max(maxi, abs(v[s[i] - 'a'] - i) - 1); } ...
var maxLengthBetweenEqualCharacters = function(s) { const map = new Map(); let max=-1; for(let i=0;i<s.length;i++){ if(map.has(s[i])){ max=Math.max(max,i-(map.get(s[i])+1)) }else{ map.set(s[i],i) } } return max; };
Largest Substring Between Two Equal Characters
There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes. Retu...
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: # ignore restricted node # bfs from 0 # O(E), EDITED: the time complexity here is wrong, plz see my comment adj_dict = collections.defaultdict(list) for u, v in ed...
class Solution { int count=0; ArrayList<ArrayList<Integer>> adj=new ArrayList<>(); public int reachableNodes(int n, int[][] edges, int[] restricted) { boolean[] vis=new boolean[n]; for(int i:restricted){ vis[i]=true; } for(int i=0;i<n;i++){ adj.add(new...
class Solution { public: int count=1; // node 0 is already reached as it is starting point vector<vector<int>> graph; unordered_set<int> res; // to store restricted numbers for fast fetch vector<bool> vis; // visited array for DFS void dfs(int i){ for(int y: graph[i]){ if...
/** * @param {number} n * @param {number[][]} edges * @param {number[]} restricted * @return {number} */ var reachableNodes = function(n, edges, restricted) { const adj = {}; for (const [u, v] of edges) { if (adj[u]) { adj[u].add(v); } else { adj[u] = new Set()....
Reachable Nodes With Restrictions
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in...
class Solution: def findMin(self, nums: List[int]) -> int: if len(nums) == 1 or nums[0] < nums[-1]: return nums[0] l, r = 0, len(nums) - 1 while l <= r: mid = l + (r - l) // 2 if mid > 0 and nums[mid - 1] > nums[mid]: ...
class Solution { public int findMin(int[] nums) { int min=nums[0]; for(int i=0;i<nums.length;i++) { if(min>nums[i]) { min=nums[i]; } } return min; } }
class Solution { public: int findMin(vector<int>& nums) { int result = -1; int first = nums[0]; // check the array for rotated point when it is obtained break the loop and assign result as rotation point for(int i = 1; i<nums.size();i++){ if(nums[i-1]>nums[i]){ ...
var findMin = function(nums) { let min = Math.min(...nums) return min; };
Find Minimum in Rotated Sorted Array
Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, w...
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): res=0 for i in range(32): bit=(n>>i)&1 res=res|bit<<(31-i) return res
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int mask = 0; int smask = 0; int j = 0; int rev = 0; // basically we are checking that the number is set bit or not // if the number is set bit then we are a...
class Solution { public: uint32_t reverseBits(uint32_t n) { int ans =0; int i =1; int bit =0; while(i<32){ bit = n&1; ans = ans|bit; n = n>>1; ans = ans<<1; i++; } if (i ==32){ bit = n&1; ...
/** * @param {number} n - a positive integer * @return {number} - a positive integer */ // remember the binary must always be of length 32 ;); var reverseBits = function(n) { const reversedBin = n.toString(2).split('').reverse().join(''); const result = reversedBin.padEnd(32,'0'); return parseInt(resu...
Reverse Bits
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During...
class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: def getPreStates(m,c,t): ans = [] if t == 1: for c2 in graph[c]: if c2 == 0:continue ans.append((m,c2,2)) else: for m2 in graph[m...
class Solution { int TIME_MAX = 200; int DRAW = 0; int MOUSE_WIN = 1; int CAT_WIN = 2; public int catMouseGame(int[][] graph) { return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]); } private int dfs(int time, int[] p, int[][] graph, Integer[][]...
class Solution { public: int catMouseGame(vector<vector<int>>& graph) { int N = graph.size(); vector<vector<int>> dp[2]; vector<vector<int>> outdegree[2]; queue<vector<int>> q; // q of {turn, mouse position, cat position} for topological sort dp[0] = vector<vector<int>>(N, v...
var catMouseGame = function(graph) { let n=graph.length, memo=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2*n+1)])), seen=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2)])) //dfs returns 0 1 2, whether the current player loses,wins, or draws respectively let dfs=(M,C,l...
Cat and Mouse
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: There are at least ti...
class Solution: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: decreasing = [0] * len(security) increasing = [0] * len(security) for i in range(len(security)): if i > 0 and security[i - 1] >= security[i]: decreasing[i] = decreasing[i - 1...
class Solution { public List<Integer> goodDaysToRobBank(int[] security, int time) { List<Integer> res = new ArrayList<>(); if (time == 0) { for (int i = 0; i < security.length; i++) res.add(i); return res; } Set<Integer> set = new HashSet<>(); int coun...
class Solution { public: vector<int> goodDaysToRobBank(vector<int>& security, int time) { int n = security.size(); vector<int> prefix(n), suffix(n); vector<int> ans; prefix[0] = 0; for(int i=1;i<n;i++) { if(security[i] <= security[i-1]) prefix[i] = prefix...
var goodDaysToRobBank = function(security, time) { let res = []; if(!time){ let i = 0; while(i<security.length) res.push(i), i++; return res; } let increasing = 0; let decreasing = 0; let set = new Set(); for(let i = 1; i < security.length; i++){ if(security[i]...
Find Good Days to Rob the Bank
Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently. You are given two integer arrays of length n, aliceValues and bo...
class Solution: def stoneGameVI(self, A, B): G = [a+b for a,b in zip(A,B)] G.sort() L = len(A) d = -sum(B) + sum( G[i] for i in range(L-1,-1,-2) ) return 1 if d>0 else ( -1 if d<0 else 0 )
class Solution { static class Pair { int sum=0; int alice=0; int bob=0; public Pair(int sum,int alice, int bob) { this.sum=sum; this.alice = alice; this.bob = bob; } } // class to define user defined conparator static class Compare { static void compare(Pair arr[], int n) { //...
vector<int> alice, bob; struct myComp { bool operator()(pair<int, int>& a, pair<int, int>& b){ return alice[a.second] + bob[a.second] < alice[b.second] + bob[b.second]; } }; class Solution { public: int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) { alice = aliceValues; ...
var stoneGameVI = function(aliceValues, bobValues) { let aliceVal = 0 let bobVal = 0 let turn = true const combined = {} let n = aliceValues.length for (let i = 0; i < n; i++) { if (combined[aliceValues[i] + bobValues[i]]) { combined[aliceValues[i] + bobValues[i]].push({value...
Stone Game VI
There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. ...
class Solution: def chalkReplacer(self, chalk: List[int], k: int) -> int: x = sum(chalk) if x<k: k = k%x if x == k: return 0 i = 0 n = len(chalk) while True: if chalk[i]<=k: k -= chalk[i] else: ...
class Solution { public int chalkReplacer(int[] chalk, int k) { long sum = 0; for (int c : chalk) { sum += c; } long left = k % sum; for (int i = 0; i < chalk.length; i++){ if(left >= chalk[i]){ left -= chalk[i]; } else { return i; } ...
class Solution { public: // T(n) = O(n) S(n) = O(1) int chalkReplacer(vector<int>& chalk, int k) { // Size of the vector int n = chalk.size(); // Store the sum of the elements in the vector long sum = 0; // Calculate the sum of the elements for (int n : chalk) s...
var chalkReplacer = function(chalk, k) { const sum = chalk.reduce((r, c) => r + c, 0); k %= sum; for (let i = 0; i < chalk.length; i++) { if (chalk[i] > k) { return i; } k -= chalk[i]; } };
Find the Student that Will Replace the Chalk
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: If word1 is non-empty, append the first character in word1 to merge and delete it from word1. For example, if word1 = "abc" and me...
class Solution: def largestMerge(self, word1: str, word2: str) -> str: res = '' p1 = 0 p2 = 0 while p1 < len(word1) and p2 < len(word2): if word1[p1:] > word2[p2:]: res += word1[p1] p1 += 1 else: res += word2[p2]...
class Solution { public String largestMerge(String word1, String word2) { StringBuilder sb = new StringBuilder(); int i=0; int j=0; char[] w1 = word1.toCharArray(); char[] w2 = word2.toCharArray(); int n1=w1.length; int n2=w2.length; ...
class Solution { public: string largestMerge(string word1, string word2) { string ans=""; while(word1.size()!=0 && word2.size()!=0){ if(word1>=word2) {ans+=word1[0];word1=word1.substr(1);} else {ans+=word2[0];word2=word2.substr(1);} ...
var largestMerge = function(word1, word2) { let ans = ''; let w1 = 0, w2 = 0; while(w1 < word1.length && w2 < word2.length) { if(word1[w1] > word2[w2]) ans += word1[w1++]; else if(word2[w2] > word1[w1]) ans += word2[w2++]; else { const rest1 = word1.slice(w1); ...
Largest Merge Of Two Strings
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n, return true if n is a perfect number, otherwise return false. &nbsp; Example 1: Input: num = 28 Output: true Exp...
class Solution: def checkPerfectNumber(self, num: int) -> bool: sum = 0 root = num**0.5 if num ==1: return False for i in range(2,int(root)+1): if num%i== 0: sum +=(num//i)+i return sum+1 == num
class Solution { public boolean checkPerfectNumber(int num) { if(num==1) return false; int sum = 1; for(int i=2; i<Math.sqrt(num); i++){ if(num%i==0){ sum += i + num / i; } } if(sum==num){ return true; } els...
class Solution { public: bool checkPerfectNumber(int num) { // we are initialising sum with 1 instead of 0 because 1 will be divisor of every number int sum=1; for(int i=2; i<sqrt(num); i++){ if(num%i==0){ // it checks if both are same factors, for ex, if num=9, i=3, num/...
/** * @param {number} num * @return {boolean} */ var checkPerfectNumber = function(num) { let total = 0 for(let i = 1 ; i < num;i++){ if(num % i == 0){ total += i } } return total == num ? true : false };
Perfect Number
Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in t...
class Solution: def getFolderNames(self, names: List[str]) -> List[str]: # Hashmap will store the name as key and the number of times that name has duplicated so fas as value. hashmap = {} for name in names: modified = name # Check whether the name has already been u...
class Solution { Map<String, Integer> map = new HashMap<>(); public String[] getFolderNames(String[] names) { String[] op = new String[names.length]; int i = 0; for(String cur : names){ if(map.containsKey(cur)) { cur = generateCopyName(cur); ...
class Solution { unordered_map<string, int> next_index_; bool contain(const string& fn) { return next_index_.find(fn) != next_index_.end(); } string get_name(string fn) { if (!contain(fn)) { next_index_.insert({fn, 1}); return fn; } ...
/** * @param {string[]} names * @return {string[]} */ var getFolderNames = function(names) { // save existed folder names let hashMap = new Map(); for(let name of names) { let finalName = name; // next smallest suffix number // if this name is not present in the map, next smallest...
Making File Names Unique
A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com"&nbsp;and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" impl...
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: output, ans = {}, [] for domain in cpdomains : number, domain = domain.split(' ') sub_domain = domain.split('.') pair = '' print(sub_domain) for i in reversed(ra...
class Solution { public List<String> subdomainVisits(String[] cpdomains) { List<String> result = new LinkedList<>(); HashMap<String, Integer> hmap = new HashMap<>(); for(int i = 0; i < cpdomains.length; i++){ String[] stringData = cpdomains[i].split(" "); Str...
class Solution { public: vector<string> subdomainVisits(vector<string>& cpdomains) { vector<string> v; unordered_map<string,int> m; for(auto it : cpdomains){ string rep=""; int i=0; while(it[i]!=' '){ rep+=(it[i]); i++...
/** * @param {string[]} cpdomains * @return {string[]} */ var subdomainVisits = function(cpdomains) { let map = {} cpdomains.forEach(d => { let data = d.split(" "); let arr = data[1].split(".") while(arr.length > 0) { if(arr.join(".") in map) map[arr.join(".")]+=+data[0] ...
Subdomain Visit Count
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expr...
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i == "+": stack[-1] = stack[-2] + stack.pop() elif i == "-": stack[-1] = stack[-2] - stack.pop() elif i == "*": stack[...
class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack(); for(String i: tokens){ if(i.equals("+") || i.equals("-") || i.equals("*") || i.equals("/")){ int a = stack.pop(); int b = stack.pop(); int temp = 0; ...
class Solution { public: int stoi(string s){ int n = 0; int i = 0; bool neg = false; if(s[0] == '-'){ i++; neg = true; } for(; i < s.size(); i++){ n = n*10 + (s[i]-'0'); } if(neg) n = -n; return n; } ...
const ops = new Set(['+', '-', '*', '/']); /** * @param {string[]} tokens * @return {number} */ var evalRPN = function(tokens) { const stack = []; for (const token of tokens) { if (!ops.has(token)) { stack.push(Number(token)); continue; } const val1 = stack....
Evaluate Reverse Polish Notation
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is...
class Solution: def dfs(self, pos: int, jobs: List[int], workers: List[int]) -> int: if pos >= len(jobs): return max(workers) mn = float("inf") # we keep track of visited here to skip workers # with the same current value of assigned work # this is an impo...
class Solution { int result = Integer.MAX_VALUE; public int minimumTimeRequired(int[] jobs, int k) { int length = jobs.length; Arrays.sort(jobs); backtrack(jobs, length - 1, new int [k]); return result; } public void backtrack(int [] jobs, int current, int [] workers...
class Solution { public: int minimumTimeRequired(vector<int>& jobs, int k) { int sum = 0; for(int j:jobs) sum += j; sort(jobs.begin(),jobs.end(),greater<int>()); int l = jobs[0], r = sum; while(l<r){ int mid = (l+r)>>1; vector<int> worker(k...
var minimumTimeRequired = function(jobs, k) { let n=jobs.length, maskSum=[...Array(1<<n)].map(d=>0) for(let mask=0;mask<(1<<n);mask++) //pre-store the sums of every mask for(let i=0;i<n;i++) maskSum[mask]+=Number(((1<<i) & mask)!=0)*jobs[i] let dp=[...Array(k+1)].map(d=>[...Array(1<<n)]....
Find Minimum Time to Finish All Jobs
Given the root of a binary tree, return the inorder traversal of its nodes' values. &nbsp; Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]. -10...
from typing import List, Optional class Solution: """ Time: O(n) """ def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: inorder = [] stack = [] while stack or root is not None: if root: stack.append(root) root = root.left else: node = stack.pop() inorder.append(node...
/** * 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<int> v; vector<int> inorderTraversal(TreeNode* root) { if(root!=NULL){ inorderTraversal(root->left); v.push_back(root->val); inorderTraversal(root->right); } return v; } };
var inorderTraversal = function(root) { let result = []; function traverse(node) { if(!node) { return; } traverse(node.left); result.push(node.val); traverse(node.right); } traverse(root); return result; };
Binary Tree Inorder Traversal
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: Trie() Initializes the trie object. void insert(String wo...
class Node : def __init__(self ): self.child = {} # to hold the nodes. self.end = False # to mark a node if it is the end node or not. class Trie: def __init__(self): self.root = Node() def insert(self, word:str) -> None: # time compl len(word) sz = l...
class Trie { private class Node{ char character; Node[] sub; Node(char c){ this.character = c; sub = new Node[26]; } } Node root; HashMap<String, Boolean> map; public Trie() { root = new Node('\0'); map = new HashMap<>(); } ...
class Trie { public: struct tr { bool isword; vector<tr*> next; tr() { next.resize(26, NULL); // one pointer for each character isword = false; } }; tr *root; Trie() { root = new tr(); } void insert(string word) { ...
var Trie = function() { this.children = {}; this.word = false; }; /** * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { if (!word) { this.word = true; return null; } let head = word[0]; let tail = word.substring(1); if (!this.children[he...
Implement Trie (Prefix Tree)
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degre...
class Solution: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: result = n ** 2 # placeholder value adj = [set() for _ in range(n + 1)] visited = set() for edge in edges: adj[edge[0]].add(edge[1]) adj[edge[1]].add(edge[0]) for first in ...
class Solution { public int minTrioDegree(int n, int[][] edges) { // to store edge information boolean[][] graph = new boolean[n+1][n+1]; //to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph) int[] inDegree = new int[n+1]; for(int[] edge : edges) { ...
class Solution { public: int minTrioDegree(int n, vector<vector<int>>& edges) { vector<unordered_set<int>> adj(n+1); int res = INT_MAX; for (vector<int>& edge : edges) { adj[edge[0]].insert(edge[1]); adj[edge[1]].insert(edge[0]); } for (int i = 1; i <...
var minTrioDegree = function(n, edges) { // create an adjacency list of all the edges; const adjacencyList = new Array(n + 1).fill(0).map(() => new Set()); for (const [x, y] of edges) { adjacencyList[x].add(y); adjacencyList[y].add(x); } let minimumDegree = Infinity; // Find al...
Minimum Degree of a Connected Trio in a Graph
You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more...
class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: heap = [-p for p in piles] heapq.heapify(heap) for _ in range(k): cur = -heapq.heappop(heap) heapq.heappush(heap, -(cur-cur//2)) return -sum(heap)
class Solution { public int minStoneSum(int[] A, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>((a, b)->b - a); int res = 0; for (int a : A) { pq.add(a); res += a; } while (k-- > 0) { int a = pq.poll(); pq.add(a - ...
class Solution { public: int minStoneSum(vector<int>& piles, int k) { priority_queue<int> pq; int sum = 0, curr; for (auto pile : piles) { pq.push(pile); sum += pile; } while (k--) { curr = pq.top(); pq.pop(); sum ...
/** * @param {number[]} piles * @param {number} k * @return {number} */ var minStoneSum = function(piles, k) { var heapArr = []; for (let i=0; i<piles.length; i++){ heapArr.push(piles[i]); heapifyUp(); } function heapifyUp(){ let currIndex = heapArr.length-1; while ...
Remove Stones to Minimize the Total
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its ne...
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: t=len(nums) nums+=nums l=[-1]*len(nums) d={} stack=[0] for x in range(1,len(nums)): #print(x) if nums[x]>nums[stack[-1]]: while nums[x]>nums[stack[-1]]...
class Solution { public int[] nextGreaterElements(int[] nums) { Stack<Integer>s=new Stack<>(); for(int i=nums.length-1;i>=0;i--){ s.push(nums[i]); } for(int i=nums.length-1;i>=0;i--){ int num=nums[i]; while(!s.isEmpty() && s.peek()<=nums[i]){ ...
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); vector<int> res; for(int i = 0; i < n; i++){ int j = i + 1; if(j == n) j = 0; int next = -1; while(j != i){ ...
var nextGreaterElements = function(nums) { const len = nums.length; const ans = new Array(len).fill(-1); const stack = []; for(let i = 0; i < len; i++) { if(i == 0) stack.push([i, nums[i]]); else { while(stack.length && stack.at(-1)[1] < nums[i]) { ans[stack.p...
Next Greater Element II
Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted. &nbsp; Example 1: Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3] Output: 2.00000 Explanation: After er...
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])
class Solution { public double trimMean(int[] arr) { Arrays.sort(arr); int length = arr.length; int toRemove = length * 5 / 100; int total = 0; for (int number: arr) { total += number; } for (int i=0; i<toRemove; i++) total -= arr[i]; ...
class Solution { public: double trimMean(vector<int>& arr) { auto first = arr.begin() + arr.size() / 20; auto second = arr.end() - arr.size() / 20; nth_element(arr.begin(), first, arr.end()); nth_element(first, second, arr.end()); return accumulate(first, second, 0.0) / dista...
var trimMean = function(arr) { arr.sort((a,b) => a - b); let toDelete = arr.length / 20; let sum = 0; for (let i = toDelete; i < arr.length - toDelete; i++) { sum += arr[i]; } return sum / (arr.length - (2 * toDelete)); };
Mean of Array After Removing Some Elements
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's nu...
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: boxes = [0] * 100 for i in range(lowLimit, highLimit + 1): # For the current number "i", convert it into a list of its digits. # Compute its sum and increment the count in the frequency table. ...
class Solution { public int countBalls(int lowLimit, int highLimit) { Map<Integer,Integer> map = new HashMap<>(); int count = Integer.MIN_VALUE; for(int i = lowLimit;i<=highLimit;i++){ int value = 0; int temp = i; while (temp!=0){ value += ...
class Solution { public: int countBalls(int lowLimit, int highLimit) { vector<int> box (46,0); for(int i = lowLimit;i<=highLimit;i++) { int sum = 0; int temp = i; while(temp) { sum = sum + temp%10; temp = temp/1...
var countBalls = function(lowLimit, highLimit) { let obj={}; for(let i=lowLimit; i<=highLimit; i++){ i+=''; let sum=0; for(let j=0; j<i.length; j++){ sum+=i[j]*1; } obj[sum]?obj[sum]+=1:obj[sum]=1 } return Math.max(...Object.values(obj)); };
Maximum Number of Balls in a Box
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] ...
class Solution: def validPartition(self, nums: List[int]) -> bool: n = len(nums) dp = [False] * 3 dp[0] = True # An empty partition is always valid for i in range(2, n + 1): ans = False if nums[i - 1] == nums[i - 2]: ans = ans or dp...
// Time O(n) // Space O(n) class Solution { public boolean validPartition(int[] nums) { boolean[] dp = new boolean[nums.length+1]; dp[0]=true; // base case for (int i = 2; i <= nums.length; i++){ dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1 dp[i]|= i>2 && nums[i...
class Solution { public: int solve(int i, vector<int> &nums, vector<int> &dp) { if (i == nums.size()) return 1; if (dp[i] != -1) return dp[i]; int ans = 0; if (i+1 < nums.size() and nums[i] == nums[i+1]) ans = max(ans, solve(i+2, nums, dp)); if (...
var validPartition = function(nums) { let n = nums.length, memo = Array(n).fill(-1); return dp(0); function dp(i) { if (i === n) return true; if (i === n - 1) return false; if (memo[i] !== -1) return memo[i]; if (nums[i] === nums[i + 1] && dp(i + 2)) return memo[i] = true; if (i < n - 2) { ...
Check if There is a Valid Partition For The Array
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your po...
class Solution: def numWays(self, steps: int, arrLen: int) -> int: # obtain maximum index we can reach maxLen = min(steps+1, arrLen) dp = [0]*maxLen dp[0] = 1 for step in range(1, steps+1): dp2 = [0]*maxLen for pos in range(maxLen): ...
class Solution { HashMap<String,Long> map = new HashMap(); public int numWays(int steps, int arrLen) { return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7)); } public long ways(int steps,int arrLen,int index){ String curr = index + "->" + steps; ...
class Solution { public: int n, MOD = 1e9 + 7; int numWays(int steps, int arrLen) { n = arrLen; vector<vector<int>> memo(steps / 2 + 1, vector<int>(steps + 1, -1)); return dp(memo, 0, steps) % MOD; } long dp(vector<vector<int>>& memo, int i, int steps){ if(steps == 0) ...
var numWays = function(steps, arrLen) { let memo = Array(steps + 1).fill(0).map(() => Array(steps + 1).fill(-1)), mod = 10 ** 9 + 7; return dp(0, steps); function dp(i, steps) { if (steps === 0) return i === 0 ? 1 : 0; // found a way if (i > steps || i < 0 || i >= arrLen) return 0; // out of bounds ...
Number of Ways to Stay in the Same Place After Some Steps
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. &nbsp; Example 1: Input: tempera...
class Solution: def dailyTemperatures(self, T): ans, s = [0]*len(T), deque() for cur, cur_tmp in enumerate(T): while s and cur_tmp > T[s[-1]]: ans[s[-1]] = cur - s[-1] s.pop() s.append(cur) return ans
class Solution { public int[] dailyTemperatures(int[] temperatures) { HashMap<Integer,Integer>hm=new HashMap<>(); Stack<Integer>st=new Stack<>(); for(int i=0;i<temperatures.length;i++){ while(st.size()>0&&temperatures[i]>temperatures[st.peek()]){ hm.put(st.pop(),i...
class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { int n = temperatures.size(); stack<int> st; vector<int> result(n, 0); for(int i = 0; i<n; i++){ while(!st.empty() && temperatures[i]>temperatures[st.top()]){ result[st.top(...
var dailyTemperatures = function(temperatures) { const len = temperatures.length; const res = new Array(len).fill(0); const stack = []; for (let i = 0; i < len; i++) { const temp = temperatures[i]; while (temp > (stack[stack.length - 1] || [Infinity])[0]) { cons...
Daily Temperatures
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. &nbsp; Example 1: Input: preord...
class Solution: def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def build(preorder, preStart, preEnd, postorder, postStart, postEnd): if preStart > preEnd: return elif preStart == preEnd: return TreeNod...
class Solution { public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { // O(n) time | O(h) space if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null; TreeNode root = new TreeNode(preorder[0]); int mid = 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...
var constructFromPrePost = function(preorder, postorder) { let preIndex = 0 const dfs = (postArr) => { if (postArr.length === 0) return null const val = preorder[preIndex] const nextVal = preorder[++preIndex] const mid = postArr.indexOf(nextVal) const root = new TreeNo...
Construct Binary Tree from Preorder and Postorder Traversal
You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exact...
from collections import defaultdict class Solution: def destCity(self, paths: List[List[str]]) -> str: deg = defaultdict(int) for v, w in paths: deg[v] += 1 deg[w] for v in deg: if not deg[v]: return v
class Solution { public String destCity(List<List<String>> paths) { HashSet<String> set1 = new HashSet<>(); for (int i = 0; i < paths.size(); ++i) { set1.add(paths.get(i).get(0)); } for (int i = 0; i < paths.size(); ++i) { if (!set1.contains(paths.get(i).get(...
class Solution { public: string destCity(vector<vector<string>>& paths) { string ans; unordered_map<string, int> m; for(int i=0; i<paths.size(); i++){ m[paths[i][0]]++; m[paths[i][1]]--; } for(auto city : m){ if(city.second == -1) ans = cit...
* @param {string[][]} paths * @return {string} */ var destCity = function(paths) { let map={} for(let city of paths){ map[city[0]]=map[city[0]]?map[city[0]]+1:1 } for(let city of paths){ if(!map[city[1]]) return city[1] } };```
Destination City
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases...
class Solution: def minNumberOperations(self, nums: List[int]) -> int: res=nums[0] prev=nums[0] for i in range(1,len(nums)): res += max(0,nums[i]-prev) prev=nums[i] return res
// Imagine 3 cases // Case 1. [3,2,1], we need 3 operations. // Case 2. [1,2,3], we need 3 operations. // Case 3. [3,2,1,2,3], we need 5 operations. // What we need to add is actually the diff (cur - prev) // Time complexity: O(N) // Space complexity: O(1) class Solution { public int minNumberOperations(int[] targe...
class Solution { public: int minNumberOperations(vector<int>& target) { int n=target.size(); int pre=0, cnt=0; for(int i=0;i<n;i++) { if(target[i]>pre) cnt+=target[i]-pre; pre=target[i]; } return cnt; } };
var minNumberOperations = function(target) { let res = target[0]; for(let g=1; g<target.length; g++){ if(target[g] > target[g-1]){ res = res + (target[g] - target[g-1]); } // for target[g] < target[g-1] we need not worry as its already been taken care by previous iterations ...
Minimum Number of Increments on Subarrays to Form a Target Array
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000'...
class Solution: def openLock(self, deadends: List[str], target: str) -> int: def neighbor(s): res = [] for i, c in enumerate(s): res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:]) res.append(s[:i] + chr((ord(c) - ord('0') + 1)...
class Solution { public int openLock(String[] deadends, String target) { // Converted target to Integer type. int t = Integer.parseInt(target); HashSet<Integer> visited = new HashSet<>(); // Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited. ...
class Solution { public: void setPermutations(const string& s, queue<pair<string, int>>& q, int count) { for (int i=0; i<4; i++) { int j = s[i]-'0'; char b = (10+j-1)%10 + '0', n = (10+j+1)%10 + '0'; auto tmp = s; tmp[i]=b; q.push({tmp, count+1}); ...
var openLock = function(deadends, target) { if(deadends.includes('0000')) { return -1 } // treat deadends like visited // if a number is in visited/deadends, simply ignore it const visited = new Set(deadends) const queue = [['0000', 0]]; visited.add('0000') while(queue...
Open the Lock
Given an integer array arr, return true&nbsp;if there are three consecutive odd numbers in the array. Otherwise, return&nbsp;false. &nbsp; Example 1: Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds. Example 2: Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,2...
class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: c=0 for i in arr: if i%2==0: c=0 else: c+=1 if c==3: return True return False
class Solution { public boolean threeConsecutiveOdds(int[] arr) { int count = 0,n = arr.length; for(int i=0;i<n;i++) { if((arr[i] & 1) > 0) { count++; if(count == 3) return true; } else { ...
class Solution { public: bool threeConsecutiveOdds(vector<int>& arr) { int k = 0; for(int i=0;i<arr.size();i++){ if(arr[i] % 2 != 0){ k++; if(k == 3){ return true; } }else{ k = 0; ...
var threeConsecutiveOdds = function(arr) { let c = 0; for(let val of arr){ if(val % 2 === 1){ c++; if(c === 3) { return true; } } else { c=0; } } return false; };
Three Consecutive Odds
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i, you can pick an...
from bisect import bisect_left from functools import lru_cache class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: start = locations[start] end = locations[finish] locations.sort() start = bisect_left(locations, start) end =...
/* Using DFS and Memo : 1. We will start from start pos provided and will dfs travel to each other location . 2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling 3. if fuel goes negetive , we will return 0 , as there is no va...
class Solution { public: int fun(vector<int> &arr , int s , int f , int k , vector<vector<int>> &dp){ if(k<0) return 0 ; if(dp[s][k]!=-1) return dp[s][k] ; int ans=0 ; if(s==f) ans=1 ; for(int i=0 ; i<arr.size() ; i++){ if(i!=s) ans=(ans+fun(arr,i,f,k-abs(arr...
var countRoutes = function(locations, start, finish, fuel) { const memo = new Array(locations.length+1).fill(0).map(()=>new Array(201).fill(-1)); const dfs = function(cur, f){ if(f<0) return 0; if(memo[cur][f]!=-1) return memo[cur][f]; let res = (cur==finish); for(let i in l...
Count All Possible Routes
Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. &nbsp; Example 1: Input: arr = [[1,2,3],[4,5,6],[7,...
class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) if m == 1 and n == 1: return grid[0][0] min_arr = [0 for _ in range(n)] for i in range(m): prefix = [float('inf') for _ in range(n)] suffix = ...
class Solution { // Recursion /* public int minFallingPathSum(int[][] grid) { int n=grid.length; if(n==1) return grid[0][0]; int ans = 10000000; for(int i=0 ; i<n ; i++){ ans = Math.min(ans , grid[0][i] + helper(grid , n , 1 , i)); } return ans; } ...
class Solution { public: int f(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &dp){ //to handle edge cases if the j index is less than 0 or greater than size of the array. if(j<0 or j>=matrix[0].size()) return 1e8; //base case if(i==0) return dp[0][j] = matrix[0][j...
var minFallingPathSum = function(grid) { if(grid.length===1){ return grid[0][0]; } let sums = [];//find first, second and third minimum values in the grid as these are only possible values for path //store the index for fast lookup in a 3D array for(let i=0; i<grid.length; i++){ let min = Math.min(...grid[i]); ...
Minimum Falling Path Sum II
You are given a string num representing a large integer. An integer is good if it meets the following conditions: It is a substring of num with length 3. It consists of only one unique digit. Return the maximum good integer as a string or an empty string "" if no such integer exists. Note: A substring is a co...
class Solution: def largestGoodInteger(self, n: str) -> str: return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else "" for i in range(2, len(n)))
class Solution { public String largestGoodInteger(String num) { String ans = ""; for(int i = 2; i < num.length(); i++) if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2)) if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is l...
class Solution { public: string largestGoodInteger(string num) { string ans = ""; for(int i=1; i<num.size()-1; i++) { if(num[i-1] == num[i] && num[i] == num[i+1]) { string temp = {num[i-1], num[i], num[i+1]}; ans = max(ans, temp); } } retur...
var largestGoodInteger = function(num) { let maxGoodInt = ''; for (let i = 0; i <= num.length - 3; i++) { if (num[i] === num[i+1] && num[i+1] === num[i+2]) { if (num[i] >= maxGoodInt) { maxGoodInt = num[i]; } } } return maxGoodInt + maxGoodInt + ma...
Largest 3-Same-Digit Number in String
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: You choose any number of obst...
from bisect import bisect_right class Solution: def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]: longest, res = [], [] for i in range(len(obstacles)): idx = bisect_right(longest, obstacles[i]) if idx == len(longest): longest.ap...
class Solution { public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { int i = -1, cur = 0, lisSize = -1; int[] lis = new int[obstacles.length]; int[] ans = new int[obstacles.length]; for (int curHeight: obstacles) { if (i == -1 || lis[i] <= curHeig...
class Solution { public: // ranking each element to make segment tree of small size void compress(vector<int>& a){ vector<int> b=a; sort(b.begin(),b.end()); map<int,int> mp; int prev=b[0],rnk=0,n=a.size(); for(int i=0;i<n;i++){ if(b[i]!=prev){ pre...
var longestObstacleCourseAtEachPosition = function(obstacles) { var n = obstacles.length; var lis = []; var res = new Array(n).fill(0); for(var i = 0; i<n; i++) { if(lis.length>0 && obstacles[i] >= lis[lis.length-1]) { lis.push(obstacles[i]); res[i] = lis.leng...
Find the Longest Valid Obstacle Course at Each Position
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between thei...
class Solution: def binaryGap(self, n: int) -> int: prev = 0 res = 0 for i, d in enumerate(bin(n)[3:]): if d == "1": res = max(res, i-prev+1) prev = i + 1 return res
class Solution { public int binaryGap(int n) { char[] arr = Integer.toBinaryString(n).toCharArray(); List<Integer> ans = new ArrayList(); for(int i = 0; i < arr.length ; i++){ if(arr[i] == '1') ans.add(i); } int res = 0; for ( int i = 0 ; i <...
class Solution { public: int binaryGap(int n) { int res=0; int s=0,i=0; while(n){ if(n&1){ s=i;break; } i++; n=n>>1; } while(n){ if(n&1){ res=max(res,(i-s)); s=i; ...
var binaryGap = function(n) { var str = (n >>> 0).toString(2), start = 0, end = 0, diff = 0; for(var i=0;i<str.length;i++) { if(str[i] === '1') { end = i; diff = Math.max(diff, end - start); start = i; } } return diff; };
Binary Gap
Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defined ...
class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: n = len(nums) sub_arrays = set() # generate all combinations of subarray for start in range(n): cnt = 0 temp = '' for i in range(start, n): ...
class Solution { public int countDistinct(int[] nums, int k, int p) { int n = nums.length; // we are storing hashcode for all the substrings so that we can compare them faster. // main goal is to avoid entire sub array comparision using hashcode. Set<Long> ways = new HashSet<>(); ...
class Solution { public: int countDistinct(vector<int>& nums, int k, int p) { int n=nums.size(); set<vector<int>>ans; int i,j; for(i=0;i<n;i++) { vector<int>tt; int ct=0; for(j=i;j<n;j++) { tt....
var countDistinct = function(nums, k, p) { let ans = []; let rec = (index,k,p,nums,ans,curr) => { let val = nums[index]; let check = val%p; let isdiv = false; if(check == 0) isdiv=true; if(index == nums.length) { if(curr.length>0){ ans.push(c...
K Divisible Elements Subarrays
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an intege...
class Solution: def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: # prefix sum to save time acc = [0] + [*accumulate(packages)] packages.sort() ans = float('inf') for box in boxes: tmp = 0 # deal with smallest box first ...
class Solution { public int minWastedSpace(int[] packages, int[][] boxes) { Arrays.sort(packages); int n = packages.length, k = -1; long sum = 0, ans = Long.MAX_VALUE; int[] pos = new int[100001]; for (int i = 0; i < 100001; i++){ // precompute jump position. whil...
class Solution { public: #define MOD 1000000007 #define ll long long int minWastedSpace(vector<int>& packages, vector<vector<int>>& boxes) { int n = packages.size(); int m = boxes.size(); sort(packages.begin(), packages.end()); vector<ll> pack(n + 1); pack[0]...
/** * @param {number[]} packages * @param {number[][]} boxes * @return {number} */ var minWastedSpace = function(packages, boxes) { let count=0,b,minWastage,totalPackagesSize=0n,minBoxesAreaForAnySupplier=BigInt(Number.MAX_SAFE_INTEGER),boxesArea=0n,p,coverdPackagesIndex,totalBoxesAreaForSupplier; packages....
Minimum Space Wasted From Packaging
A cinema&nbsp;has n&nbsp;rows of seats, numbered from 1 to n&nbsp;and there are ten&nbsp;seats in each row, labelled from 1&nbsp;to 10&nbsp;as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8]&nbsp;means the seat located i...
class Solution(object): def maxNumberOfFamilies(self, n, reservedSeats): """ :type n: int :type reservedSeats: List[List[int]] :rtype: int """ d = defaultdict(set) for row,seat in reservedSeats: d[row].add(seat) def row(i): ...
class Solution { public int maxNumberOfFamilies(int n, int[][] reservedSeats) { Map<Integer, int[]> seats = new HashMap<>(); int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots for (int[] seat: reservedSeats) { int row = seat[0]; ...
class Solution { public: int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) { unordered_map<int, vector<int>> o; for (auto r : reservedSeats) { o[r[0]].push_back(r[1]); } int ans = 2 * (n - o.size()); // seats with no occupan...
/** * @param {number} n * @param {number[][]} reservedSeats * @return {number} */ var maxNumberOfFamilies = function(n, reservedSeats) { let a,b,c,reservedMap={},ans=n*2,takenB={}; for(let i=0;i<reservedSeats.length;i++){ let resverd = reservedSeats[i]; let row = resverd[0]; if(reser...
Cinema Seat Allocation
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array t...
import heapq from collections import defaultdict class Solution: def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int: m, n = len(students), len(students[0]) def hamming(student, mentor): return sum([int(student[i] != mentor[i]) for i in range(n)]) ...
class Solution { int max; public int maxCompatibilitySum(int[][] students, int[][] mentors) { boolean[] visited = new boolean[students.length]; helper(visited, students, mentors, 0, 0); return max; } public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos...
class Solution { // Calculating compatibility scores of ith student and jth mentor int cal(int i,int j,vector<vector<int>>& arr1,vector<vector<int>>& arr2){ int cnt=0; for(int k=0;k<arr1[0].size();k++){ if(arr1[i][k]==arr2[j][k]){ cnt++; } } ...
var maxCompatibilitySum = function(students, mentors) { const m = students.length; const n = students[0].length; let max = 0; dfs(0, (1 << m) - 1, 0); return max; function dfs(studentIdx, bitmask, scoreTally) { if (studentIdx === m) { max = Math.max(max, scoreTally); ...
Maximum Compatibility Score Sum
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. &nbsp; Example 1: Input: nums = [1,2,3,2] Output: 4 Explanation: The unique elements are [1,3], and the sum is 4. Example 2: Input: nums =...
class Solution: def sumOfUnique(self, nums: List[int]) -> int: hashmap = {} for i in nums: if i in hashmap.keys(): hashmap[i] += 1 else: hashmap[i] = 1 sum = 0 for k, v in hashmap.items(): if v == 1: sum += k ...
class Solution { public int sumOfUnique(int[] nums) { int res = 0; Map<Integer,Integer> map = new HashMap<>(); for(int i = 0;i<nums.length;i++){ map.put(nums[i],map.getOrDefault(nums[i],0)+1); if(map.get(nums[i]) == 1)res+=nums[i]; else if(map.get(nums[i])...
class Solution { public: int sumOfUnique(vector<int>& nums) { int sum=0; map<int,int>mp; for(auto x:nums) mp[x]++; for(auto m:mp) { if(m.second==1) sum+=m.first; } return sum; } };
var sumOfUnique = function(nums) { let obj = {} let sum = 0 // count frequency of each number for(let num of nums){ if(obj[num] === undefined){ sum += num obj[num] = 1 }else if(obj[num] === 1){ sum -= num obj[num] = -1 } } return sum };
Sum of Unique Elements
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity. void push(int val) Pushes the given in...
class DinnerPlates: def __init__(self, capacity: int): self.heap = [] self.stacks = [] self.capacity = capacity def push(self, val: int) -> None: if self.heap: index = heapq.heappop(self.heap) if index < len(self.stacks): self.stacks[inde...
class DinnerPlates { List<Stack<Integer>> stack; PriorityQueue<Integer> leftEmpty; PriorityQueue<Integer> rightNonEmpty; int cap; public DinnerPlates(int capacity) { this.cap = capacity; this.stack = new ArrayList<>(); this.leftEmpty = new PriorityQueue<>(); this...
class DinnerPlates { public: map<int,stack<int>>mp; set<int>empty; int cap; DinnerPlates(int capacity) { this->cap=capacity; } void push(int val) { if(empty.size()==0) { empty.insert(mp.size()); } mp[*empty.begin()].push(val); ...
/** * @param {number} capacity */ var DinnerPlates = function(capacity) { this.capacity = capacity; this.stacks = []; }; /** * @param {number} val * @return {void} */ DinnerPlates.prototype.push = function(val) { var needNewStack = true for (var i = 0; i < this.stacks.length; i++) { if (t...
Dinner Plate Stacks
Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrenc...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: length = 0 cur = head while cur: length += ...
class Solution { public ListNode[] splitListToParts(ListNode head, int k) { ListNode[] arr=new ListNode[k]; if(k<2 || head==null || head.next==null){ arr[0]=head; return arr; } ListNode temp=head; int len=1; while(temp.next!=null){ ...
class Solution { public: vector<ListNode*> splitListToParts(ListNode* head, int k) { vector<ListNode*>ans; int len=0; ListNode*temp=head; while(temp!=NULL) len++,temp=temp->next; int y=len/k , z=len%k; while(head !=NULL) { ans.push_back(h...
var splitListToParts = function(head, k) { let length = 0, current = head, parts = []; while (current) { length++; current = current.next; } let base_size = Math.floor(length / k), extra = length % k; current = head; for (let i = 0; i < k; i++) { let part_size = base_s...
Split Linked List in Parts
Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. &nbsp; Example 1: Input: s = "aababcaab", maxLetters =...
# 0 1 2 3 # a a a a # l # r #ref: https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/457577/C%2B%2B-Greedy-approach-%2B-Sliding-window-O(n). #Intuition #if a string have occurrences x times, any of its substring must also appear at least x times #there must be a sub...
class Solution { public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { Map<String,Integer> count = new HashMap<>(); int ans = 0; int n = s.length(); for(int i=0;i+minSize-1<n;i++){ String y = s.substring(i,i+minSize); count.put(y,co...
class Solution { public: int maxFreq(string s, int maxLetters, int minSize, int maxSize) { int i, j, k, ans = 0, res, n = s.length(); string temp; unordered_map<char, int> st; unordered_map<string, int> mp; i = 0, j = 0; while(i <= n - minSi...
var maxFreq = function(s, maxLetters, minSize, maxSize) { let output = 0; let left = 0, right = 0; let map = {}; let map2 = {}; let count = 0; while(right < s.length){ if(map[s[right]] === undefined){ // adding letters to map to keep track of occurences (count) map[s[r...
Maximum Number of Occurrences of a Substring
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line ...
class Solution: def fullJustify(self, words: List[str], maxwidth: int) -> List[str]: curr = 0 last = [] res = [] for i in words: if curr + len(i) + len(res) <= maxwidth: curr += len(i) res.append(i) else: last.ap...
class Solution { public List<String> fullJustify(String[] words, int maxWidth) { List<String> unBalanced = new ArrayList<>(); List<String> balanced = new ArrayList<>(); int numSpaces = 0; StringBuffer sb = new StringBuffer(); //Following code creates a list of unbalanced lin...
class Solution { string preprocessing(string &f, int space, int limit) { int noofspace = limit-f.size()+space; int k = 0; string r = ""; while(space) { int n = noofspace / space; if((noofspace%space) != 0) n += 1; noofsp...
/** * @param {string[]} words * @param {number} maxWidth * @return {string[]} */ var fullJustify = function(words, maxWidth) { if (!words || !words.length) return; const wordRows = []; let wordCols = []; let count = 0; words.forEach((word, i) => { if ((count + word.length + wordCols...
Text Justification
Given an integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left &lt;= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, in...
class NumArray: def __init__(self, nums: List[int]): self.nums, Sum = [], 0 for num in nums: Sum += num self.nums.append(Sum) def sumRange(self, left: int, right: int) -> int: return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]
class NumArray { int [] prefix; public NumArray(int[] nums) { int n = nums.length; prefix = new int[n]; prefix[0] = nums[0]; for(int i = 1; i < n; i++){ prefix[i] = nums[i] + prefix[i - 1]; } } public int sumRange(int left, int right) { if(lef...
class NumArray { public: vector<int>arr; NumArray(vector<int>& nums) { arr=nums; } int sumRange(int left, int right) { int sum=0; for(int i=left;i<=right;i++) sum+=arr[i]; return sum; } };
var NumArray = function(nums) { this.nums = nums; }; NumArray.prototype.sumRange = function(left, right) { let sum = 0; for(let i = left; i <= right; i++) sum += this.nums[i] return sum };
Range Sum Query - Immutable
You are given an integer n and an integer start. Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. &nbsp; Example 1: Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8....
class Solution: def xorOperation(self, n: int, start: int) -> int: nums = [start + 2*i for i in range(n)] #generate list of numbers ans = nums[0] for i in range(1,n): ans = ans^nums[i] # XOR operation return ans
class Solution { public int xorOperation(int n, int start) { int nums[]=new int[n]; for(int i=0;i<n;i++) nums[i] = start + 2 * i; for(int i=1;i<n;i++) nums[i] = nums[i-1]^nums[i]; return nums[n-1]; } }
class Solution { public: int xorOperation(int n, int start) { int res = start; for(int i=1 ; i<n ; i++){ res = res ^ (start + 2 * i); } return res; } };
var xorOperation = function(n, start) { let arr = [] for(let i=0; i<n; i++){ arr.push(start+2*i) } return arr.reduce((a,c)=> a^c) };
XOR Operation in an Array
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean h...
class Solution: def minimumRemoval(self, A: List[int]) -> int: return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))
class Solution { public long minimumRemoval(int[] beans) { Arrays.parallelSort(beans); long sum=0,min=Long.MAX_VALUE; int n=beans.length; for(int i:beans) sum+=i; for(int i=0;i<n;i++) { long temp=sum-((n-i+0L)*beans[i]); min=(long)M...
class Solution { public: long long minimumRemoval(vector<int>& beans) { long long n = beans.size(); sort(beans.begin(), beans.end()); long long sum = 0; for(int i=0; i<n; i++) { sum += beans[i]; } long long ans = sum; for(int i=...
/** * @param {number[]} beans * @return {number} */ // time complexity -> O(NlogN) and Space is O(logN) due to sorting. var minimumRemoval = function(beans) { beans.sort((a, b) => a - b); let frontSum = beans.reduce((sum , a) => sum + a, 0); let backSum = 0; let done = 0; let result = Number.M...
Removing Minimum Number of Magic Beans
You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negati...
class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache(None) def fn(i, j): """Return maximum & minimum products ending at (i, j).""" if i == 0 and j == 0: return grid[0][0], grid[0][0] if...
class Solution { public class Pair{ long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; Pair(){ } Pair(long min,long max){ this.min=min; this.max=max; } } public int maxProductPath(int[][] grid) { Pair[][] dp=new Pair[grid.length][grid[0...
const long long MOD = 1e9 + 7; class Solution { public: int maxProductPath(vector<vector<int>>& grid) { long long mx[20][20] = {0}; long long mn[20][20] = {0}; int row = grid.size(), col = grid[0].size(); // Init mx[0][0] = mn[0][0] = grid[0][0]; // ...
var maxProductPath = function(grid) { const R = grid.length, C = grid[0].length; if (R === 0 || C === 0) return -1; const mat = [...Array(R)].map(() => [...Array(C)].map(() => new Array(2))); mat[0][0] = [grid[0][0], grid[0][0]]; for (let i = 1; i < R; i++) mat[i][0] = [mat...
Maximum Non Negative Product in a Matrix
Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value. Note that operands in the returned expressions should not contain leading zeros. &n...
class Solution: def addOperators(self, num: str, target: int) -> List[str]: s=num[0] q=["+","-","*",""] ans=[] def cal(w): i=1 while i<len(w)-1: if w[i]=='*': q=int(w[i-1])*int(w[i+1]) del w[i+1] ...
class Solution { String s; List<String>result; int target; public void operator(int i,int prev,long prod,long mid,String exp,List<Long>l){ if(i==l.size()){ if(mid+prod==target) result.add(exp); return; } if(prev==-1){ operator(i...
class Solution { public: vector<string> res; string s; int target, n; void solve(int it, string path, long long resSoFar, long long prev){ if(it == n){ if(resSoFar == target) res.push_back(path); return; } long long num = 0; string tmp; fo...
var addOperators = function(num, target) { let res = []; let i = 0; const helper = (idx, sum, prev, path) => { if(idx >= num.length) { if(sum === target) { res.push(path); } return null; } for(let j = idx; j < num.length; j++) { ...
Expression Add Operators
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is gi...
class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])): if i > t: return i return len(dist)
class Solution { public int eliminateMaximum(int[] dist, int[] speed) { int n = dist.length; int[] time = new int[n]; for(int i = 0; i < n; i++){ time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]); } Arrays.sort(time); ...
class Solution { public: int eliminateMaximum(vector<int>& dist, vector<int>& speed) { priority_queue<double, vector<double>, greater<double>> pq; for(int i = 0; i < dist.size(); ++i) pq.push(ceil((double)dist[i] / speed[i] )); int t = 0; while(pq.size()...
/** * @param {number[]} dist * @param {number[]} speed * @return {number} */ var eliminateMaximum = function(dist, speed) { let res = 0; let len = dist.length; let map = new Map(); for(let i=0; i<len; i++){ // the last time to eliminate let a = Math.ceil(dist[i] / speed[i]); ...
Eliminate Maximum Number of Monsters
Given the root of a binary tree, invert the tree, and return its root. &nbsp; Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: [] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]...
class Solution(object): def invertTree(self, root): # Base case... if root == None: return root # swapping process... root.left, root.right = root.right, root.left # Call the function recursively for the left subtree... self.invertTree(root.left) #...
class Solution { public TreeNode invertTree(TreeNode root) { swap(root); return root; } private static void swap(TreeNode current) { if (current == null) { return; } swap(current.left); swap(current.right); TreeNode temp = current.left;...
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == NULL) return root; TreeNode* temp = root->left; root->left = root->right; root->right = temp; invertTree(root->left); invertTree(root->right); return root; } };
var invertTree = function(root) { if (!root) return root; [root.left, root.right] = [root.right, root.left]; invertTree(root.right) invertTree(root.left) return root };
Invert Binary Tree
You have n dice and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: n...
class Solution(object): def numRollsToTarget(self, n, k, target): """ :type n: int :type k: int :type target: int :rtype: int """ mem = {} def dfs(i,currSum): if currSum > target: return 0 if i == n: ...
class Solution { public int numRollsToTarget(int n, int k, int target) { if (target < n || target > n*k) return 0; if (n == 1) return 1; int[][] dp = new int[n+1][n*k+1]; for (int i = 1; i<= k; i++) { dp[1][i] = 1; } int mod = 1000000007; for (int...
class Solution { public: int dp[31][1001]; Solution(){ memset(dp,-1,sizeof(dp)); } int help(int dno,int &tdice,int &tf,int target){ if(target<0 or dno>tdice) return 0; if(target==0 and dno==tdice) { return 1; } if(dp[dno][target]!=-1) return dp[dno][target]; int ans=0; for(int i=1;i<=tf;i++){ an...
var numRollsToTarget = function(n, k, target) { if (n > target || n * k < target) return 0 //target is impossible to reach let arr = new Array(k).fill(1), depth = n //start the first layer of Pascal's N-ary Triangle. while (depth > 1) { //more layers of Triangle to fill out tempArr = [] //next layer...
Number of Dice Rolls With Target Sum
Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c &lt;= a and b &lt;= d. Return the number of remaining intervals. &nbsp; Example 1: Inp...
class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key = lambda x: (x[0], -x[1])) current, count = intervals[0], 1 for i in range(1, len(intervals)): if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]: ...
class Solution { public int removeCoveredIntervals(int[][] intervals) { if(intervals == null || intervals.length == 0) return 0; Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0])); int c = intervals[0][0], d = intervals[0][1]; int ans = intervals.length; ...
class Solution { public: int removeCoveredIntervals(vector<vector<int>>& intervals) { int cnt = 0, last = INT_MIN; sort(intervals.begin(), intervals.end(), [] (const vector<int>& v1, const vector<int>& v2) { if(v1[0] != v2[0]) return v1[0] < v2[0]; ...
var removeCoveredIntervals = function(intervals) { intervals.sort((a,b)=> a[0]-b[0] || b[1]-a[1]); let overlap=0; for (i=1,prev=0; i<intervals.length; i++) // if ((intervals[prev][0] <= intervals[i][0]) //no need to check, already done in sort // && (intervals[prev][1] >= intervals[i][1])) if (intervals[...
Remove Covered Intervals
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left &lt;= x &lt; right. Implement the RangeModule class: RangeModule() Initializes ...
from bisect import bisect_left as bl, bisect_right as br class RangeModule: def __init__(self): self._X = [] def addRange(self, left: int, right: int) -> None: # Main Logic # If idx(left) or idx(right) is odd, it's in a interval. So don't add it. # If idx(left) or idx(rig...
class RangeModule { TreeMap<Integer, Integer> map; public RangeModule() { map = new TreeMap<>(); } public void addRange(int left, int right) { // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of ri...
/* https://leetcode.com/problems/range-module/ Idea is to use a height balanced tree to save the intervals. Intervals are kept according to the start point. We search for the position where the given range can lie, then check the previous if it overlaps and keep iterating forward while the interval...
var RangeModule = function() { this.ranges = [] }; /** * @param {number} left * @param {number} right * @return {void} */ //Time: O(logN) RangeModule.prototype.addRange = function(left, right) { const lIdx = this.findIndex(left), rIdx = this.findIndex(-right) if (lIdx === this.ranges.length) { ...
Range Module
We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions...
class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: stack = [] for a in asteroids: while stack and stack[-1] > 0 > a: if stack[-1] < abs(a): stack.pop() continue elif stack[-1] == abs(a): ...
/* 0. Start iterating over the asteroid one by one. 1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision. 2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0)) 3...
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { vector<int>v; stack<int>s; for(auto x: asteroids){ if(x > 0) s.push(x); else{ // Case 1: whem top is less than...
/** * @param {number[]} asteroids * @return {number[]} */ var asteroidCollision = function(asteroids) { const s = []; for (let i = 0; i < asteroids.length; i++) { const a = asteroids[i]; // Negative asteroids to the left of the stack can be ignored. // They'll never collide. Let's j...
Asteroid Collision
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i &lt; j &lt; k and arr[i] + arr[j] + arr[k] == target. As the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by ...
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() count = 0 for i in range(0, len(arr)-2): rem_sum = target - arr[i] hash_map = {} for j in range(i+1, len(arr)): if arr[j] > rem_sum: ...
class Solution { public int threeSumMulti(int[] arr, int target) { long[] cnt = new long[101]; long res = 0; for (int i : arr) { cnt[i]++; } for (int i = 0; i < 101 && i <= target; i++) { if (cnt[i] == 0) { continue; } ...
class Solution { public: int threeSumMulti(vector<int>& arr, int target) { long long ans = 0; int MOD = pow(10, 9) + 7; // step 1: create a counting array; vector<long long> counting(101); // create a vector with size == 101; for(auto &value : arr) counting[...
/** * @param {number[]} arr * @param {number} target * @return {number} */ var threeSumMulti = function(arr, target) { let count=0 arr.sort((a,b)=>a-b) for(let i=0;i<arr.length-2;i++){ let j=i+1,k=arr.length-1 while(j<k){ let sum=arr[i]+arr[j]+arr[k] if(sum<target...
3Sum With Multiplicity
The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). "./" : Remain in the same folder. "x/" : Move to the child f...
class Solution: def minOperations(self, logs: List[str]) -> int: m='../' r='./' #create an empty stack stk=[] #iterate through the list for i in logs: #if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack if(i==m): ...
class Solution { public int minOperations(String[] logs) { var stack = new Stack<String>(); for(var log : logs){ if(log.equals("../")){ if(!stack.empty()) stack.pop(); }else if(log.equals("./")){ }else{ stack.p...
//1.using stack class Solution { public: int minOperations(vector<string>& logs) { if(logs.size()==0) return 0; stack<string> st; for(auto x: logs){ if (x[0] != '.') //Move to the child folder so add children st.push(x); else if(x=="../"){ // Mov...
var minOperations = function(logs) { let count = 0; for(i=0;i<logs.length;i++){ if(logs[i] === '../') { if(count > 0) count = count - 1; continue } if(logs[i] === './') continue; else count = count + 1; } return count };
Crawler Log Folder
Given a non-empty&nbsp;array of integers nums, every element appears twice except for one. Find that single one. You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space. &nbsp; Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Outpu...
class Solution: def singleNumber(self, nums: List[int]) -> int: nums.sort() i=0 while i<len(nums)-1: if nums[i]==nums[i+1]: i+=2 else: return nums[i] return nums[-1]
class Solution { public int singleNumber(int[] nums) { Stack numStack = new Stack(); Arrays.sort(nums); for (var i = 0; i < nums.length; ++i) { numStack.push(nums[i]); if (i < nums.length - 1 && nums[++i] != (int) numStack.peek()) break; } return (int)...
class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int,int> a; for(auto x: nums) a[x]++; for(auto z:a) if(z.second==1) return z.first; return -1; } };
var singleNumber = function(nums) { let s = 0; // Location of first possible suspect for (let i = s + 1; i < nums.length; i++) { if (nums[i] == nums[s]) { // If we found a duplicate nums.splice(i, 1); // Remove duplicate so it won't confuse us next time we come across it s++; // ...
Single Number
Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. You may assume that no string in words is a substring of another string in words. &nbsp; Example 1: Input: words = ["alex","lo...
class Solution: def shortestSuperstring(self, A): @lru_cache(None) def suffix(i,j): for k in range(min(len(A[i]),len(A[j])),0,-1): if A[j].startswith(A[i][-k:]): return A[j][k:] return A[j] n = len(A) @lru_cache(None) ...
class Solution { public String shortestSuperstring(String[] words) { int n = words.length; int[][] discount = new int[n][n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->...
vector<vector<int> > dp,pre,par; bool startWith(string s, string t) { // returns true if string s starts with string t int i; for(i=0; i<s.length()&&i<t.length(); i++) { if(s[i]==t[i]) continue; else return false; } if(i==t.length()) return true; ...
var shortestSuperstring = function(words) { let N = words.length, suffixes = new Map(), edges = Array.from({length: N}, () => new Uint8Array(N)) // Build the edge graph for (let i = 0, word = words; i < N; i++) { let word = words[i] for (let k = 1; k < word.length; k++) { ...
Find the Shortest Superstring
You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x &lt; m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Not...
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_row, max_col = len(grid), len(grid[0]) dp = [[-1] * max_col for _ in range(max_row)] def recursion(row, col): if row == max_row - 1: # If last row then return nodes value ...
class Solution { Integer dp[][]; public int minPathCost(int[][] grid, int[][] moveCost) { dp=new Integer[grid.length][grid[0].length]; int ans=Integer.MAX_VALUE; for(int i=0;i<grid[0].length;i++) { ans=Math.min(ans,grid[0][i]+helper(grid,moveCost,grid[0][...
class Solution { public: int solve(vector<vector<int>> &grid,vector<vector<int>>& moveCost,int i,int j,int n,int m){ if(i==n-1){ return grid[i][j]; } int ans=INT_MAX; for(int k=0;k<m;k++){ ans=min(ans,grid[i][j]+moveCost[grid[i][j]][k]+solve(grid,moveCost,i+1,...
var minPathCost = function(grid, moveCost) { const rows = grid.length; const cols = grid[0].length; const cache = []; for (let i = 0; i < rows; i++) { cache.push(Array(cols).fill(null)); } function move(row, col) { const val = grid[row][col]; if (cache...
Minimum Path Cost in a Grid
Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example, 21 written in binary is 10101, whi...
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} return sum(bin(n).count('1') in primes for n in range(left, right + 1))
class Solution { public int calculateSetBits(String s){ int count=0; for (int i = 0; i < s.length(); i++) { if(s.charAt(i)=='1') count++; } return count; } public boolean isPrime(int n){ if (n==0 || n==1) return false; for (int i = 2; i <= n/2; i...
class Solution { public: int countPrimeSetBits(int left, int right) { int ans=0; while(left<=right) { int cnt=__builtin_popcount(left); if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19) ++ans; ++left; } ...
/** * @param {number} L * @param {number} R * @return {number} */ var countPrimeSetBits = function(L, R) { let set = new Set([2, 3, 5, 7, 11, 13, 17, 19]); let countPrime = 0; for (let i = L; i <= R; i++) { if (set.has(i.toString(2).replace(/0/g, '').length)) countPrime++; } return countPrime; };
Prime Number of Set Bits in Binary Representation
Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 &lt; j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length...
class Solution: def canThreePartsEqualSum(self, arr: List[int]) -> bool: total = sum(arr) if total % 3 != 0: return False ave = total // 3 stage = 0 add = 0 for i in arr[:-1]: add += i if add == ave: stage +=1 ...
class Solution { public boolean canThreePartsEqualSum(int[] arr) { int sum = 0; for (Integer no : arr) { sum += no; } if (sum % 3 != 0) { return false; } sum = sum / 3; int tempSum = 0; int count = 0; for (in...
class Solution { public: bool canThreePartsEqualSum(vector<int>& arr) { int sum=0; for(auto i : arr) sum+=i; if(sum%3!=0) return false; //partition not possible int part=sum/3,temp=0,found=0; for(int i=0;i<arr.size();i++){ temp+=arr[i]; if(temp==part){ temp=0; found++; } } return...
var canThreePartsEqualSum = function(arr) { const length = arr.length; let sum =0, count = 0, partSum = 0; for(let index = 0; index < length; index++) { sum += arr[index]; } if(sum%3 !== 0) return false; partSum = sum/3; sum = 0; for(let index = 0; index < length; index++) { ...
Partition Array Into Three Parts With Equal Sum
A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'. Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. For example, "AACCGGTT" --&gt; "AACCGGTA...
class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: q = deque() q.append(start) n = len(bank) last = 0 used = [False] * n for i, x in enumerate(bank): if start == x: used[i] = True if end == x: ...
class Solution { public int minMutation(String start, String end, String[] bank) { Set<String> set = new HashSet<>(); for(String tmp: bank){ set.add(tmp); } if(!set.contains(end)) return -1; if(start.equals(end)) return 0; char[] var = {'A','C','G','T'}; ...
class Solution { public: int minMutation(string start, string end, vector<string>& bank) { unordered_set<string> st(bank.begin(), bank.end()); if (st.find(end) == st.end()) return -1; queue<string> q; q.push(start); unordered_set<string> vis; vis.ins...
/** * @param {string} start * @param {string} end * @param {string[]} bank * @return {number} */ var minMutation = function(start, end, bank) { if(start.length!=end.length || !contains(end,bank)){ return -1; } return bfs(start,end,bank); }; function contains(end,bank){ ...
Minimum Genetic Mutation
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. &nbsp; Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] &nbsp; Constrain...
class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ notzero = 0 zero = 0 while notzero < len(nums): if nums[notzero] != 0: nums[zero] , nums[notzero] = nums[notzero]...
class Solution { public void moveZeroes(int[] nums) { int a = 0, z = 0, temp; while(a < nums.length){ if(nums[a] != 0){ temp = nums[z]; nums[z] = nums[a]; nums[a] = temp; z += 1; } a += 1; } ...
class Solution { public: void moveZeroes(vector<int>& nums) { int nums_size = nums.size(); int cntr=0; for(int i=0;i<nums_size;i++) { if(nums[i] != 0) { nums[cntr] = nums[i]; cntr++; } } for( int i=c...
var moveZeroes = function(nums) { let lastNonZeroNumber = 0; //Moves all the non zero numbers at the start of the array for(let i=0; i<nums.length;i++){ if(nums[i] !=0){ nums[lastNonZeroNumber] = nums[i]; lastNonZeroNumber++; } } //Moves all the zeroes replaced ...
Move Zeroes
Given the head of a singly linked list, reverse the list, and return the reversed list. &nbsp; Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] &nbsp; Constraints: The number of nodes in the list is the range [0, 50...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head==None or head.next==None: return head p = None while(h...
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(he...
/** * 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* reverseList...
var reverseList = function(head) { // Iteratively [cur, rev, tmp] = [head, null, null] while(cur){ tmp = cur.next; cur.next = rev; rev = cur; cur = tmp; //[current.next, prev, current] = [prev, current, current.next] } }
Reverse Linked List
Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order. &nbsp; Example 1: Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] Output: [3,2] Explanation: The values that are p...
class Solution: def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]: output = [] for i in nums1: if i in nums2 or i in nums3: if i not in output: output.append(i) for j in nums2: if j in nums3 ...
class Solution { public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { int[] bits = new int[101]; for (int n : nums1) bits[n] |= 0b110; for (int n : nums2) bits[n] |= 0b101; for (int n : nums3) bits[n] |= 0b011; List<Integer> result = new ArrayList(); ...
class Solution { public: vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) { vector<int>f(110, 0); for (int n : nums1) f[n] |= 1<<0; for (int n : nums2) f[n] |= 1<<1; for (int n : nums3) f[n] |= 1<<2; vector<int>ret; for (i...
var twoOutOfThree = function(nums1, nums2, nums3) { let newArr = []; newArr.push(...nums1.filter(num => nums2.includes(num) || nums3.includes(num))) newArr.push(...nums2.filter(num => nums1.includes(num) || nums3.includes(num))) return Array.from(new Set(newArr)) };
Two Out of Three
Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It c...
class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: if not root: return root if root.val < low: return self.trimBST(root.right, low, high) if root.val > high: return self.trimBST(root.left, low, high) root.left = self.trimBST(root.left, low, high) root.right = self.trimBST(roo...
class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { if (root == null) return root; while (root.val < low || root.val > high) { root = root.val < low ? root.right : root.left; if (root == null) return root; } root.left =...
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(!root) return NULL; root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); if(root->val < low){ if(root->right){ TreeN...
var trimBST = function(root, low, high) { if(!root) return null; const { val, left, right } = root; if(val < low) return trimBST(root.right, low, high); if(val > high) return trimBST(root.left, low, high); root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high...
Trim a Binary Search Tree
You are given an array of integers&nbsp;nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. &nbsp; Example 1: Input: nums = [...
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: ans = [] pq = [] for i in range(k): heapq.heappush(pq,(-nums[i],i)) ans.append(-pq[0][0]) for i in range(k,len(nums)): heapq.heappush(pq,(-nums[i],i)) while pq and pq[...
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { Deque<Integer> queue = new LinkedList<>(); int l = 0, r = 0; int[] res = new int[nums.length - k + 1]; int index = 0; while (r < nums.length) { int n = nums[r++]; while (!queue.isEmpty...
class Solution { public: #define f first #define s second vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> ans; priority_queue<pair<int,int>> pq; for(int i=0;i<k;i++)pq.push({nums[i],i}); ans.push_back(pq.top().f); for(int i=k; i<nums.size(); i++){ pq.push({nums[i],i}); while(!p...
/** * @param {number[]} nums * @param {number} k * @return {number[]} */ var maxSlidingWindow = function(nums, k) { var i=0, j=0, max=0, deque=[], output=[]; while(j<nums.length){ if(deque.length === 0){ deque.push(nums[j]) }else if(deque[deque.length-1] > nums[j]){ d...
Sliding Window Maximum
You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string ...
class Solution: def numTimesAllBlue(self, flips: List[int]) -> int: l = len(flips) s = 0 c = 0 for i in range(len(flips)): f = flips[i] s = 1 << (f - 1) | s if s == (1 << (i+1))-1: c += 1 ...
class Solution { public int numTimesAllBlue(int[] flips) { int counter=0,total=0,max=Integer.MIN_VALUE; for(int i=0;i<flips.length;i++){ if(max<flips[i])max=flips[i]; if(++counter==max)total++; } return total; } }
class BIT{ public: vector<int>bit; int n; BIT(int n){ bit.resize(n+1,0); this->n=n; } int findSum(int i){ int sum=0; while(i>0){ sum+=bit[i]; i-=(i&(-i)); } return sum; } void update(int i,int val){ while(i<=n){ bit[i]+=val; i+=(i&(-i)); } ...
var numTimesAllBlue = function(flips) { const flipped = new Array(flips.length).fill(0); let prefixAlignedCount = 0; flips.forEach((i, step) => { flipped[i - 1] = 1; if(isPrefixAligned(step)) { ++prefixAlignedCount; } }) return prefixAlignedCount; functio...
Number of Times Binary String Is Prefix-Aligned
There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student. You may perform the following move any number of times: Increase or decrease ...
class Solution: def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: seats.sort() students.sort() return sum(abs(seat - student) for seat, student in zip(seats, students))
class Solution { public int minMovesToSeat(int[] seats, int[] students) { Arrays.sort(seats); Arrays.sort(students); int diff = 0; for(int i=0; i<seats.length; i++){ diff += Math.abs(students[i]-seats[i]); } return diff; } }
class Solution { public: int minMovesToSeat(vector<int>& seats, vector<int>& students) { sort(seats.begin(), seats.end()); sort(students.begin(), students.end()); int res = 0; for (int i = 0; i < seats.size(); i++) res += abs(seats[i] - students[i]); return ...
var minMovesToSeat = function(seats, students) { let sum = 0 seats=seats.sort((a,b)=>a-b) students=students.sort((a,b)=>a-b) for(let i=0;i<seats.length;i++) sum+=Math.abs(seats[i]-students[i]) return sum };
Minimum Number of Moves to Seat Everyone
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits. &nbsp; Example 1: Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2...
class Solution: def countEven(self, num: int) -> int: if num%2!=0: return (num//2) s=0 t=num while t: s=s+(t%10) t=t//10 if s%2==0: return num//2 else: return (num//2)-1
class Solution { public int countEven(int num) { int count = 0; for(int i = 1; i <= num; i++) if(sumDig(i)) count++; return count; } private boolean sumDig(int n) { int sum = 0; while(n > 0) { sum += n % 10; ...
class Solution { public: int countEven(int num) { int temp = num, sum = 0; while (num > 0) { sum += num % 10; num /= 10; } return sum % 2 == 0 ? temp / 2 : (temp - 1) / 2; } };
var countEven = function(num) { let count=0; for(let i=2;i<=num;i++){ if(isEven(i)%2==0){ count++; } } return count }; const isEven = (c) =>{ let sum=0; while(c>0){ sum+=(c%10) c=Math.floor(c/10) } return sum }
Count Integers With Even Digit Sum
You are standing at position 0 on an infinite number line. There is a destination at position target. You can make some number of moves numMoves so that: On each move, you can either go left or right. During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction. Given the...
class Solution: def reachNumber(self,target): jumpCount = 1 sum = 0 while sum<abs(target): sum+=jump jumpCount+=1 if (sum-target)%2==0: return jumpCount-1 else: if ((sum+jumpCount)-target)%2==0: return jumpCount else: return jumpCount+1
class Solution { public int reachNumber(int target) { int sum =0 ,steps = 0; if(target ==0) return 0; target = Math.abs(target); while(sum< target){ sum+=steps; steps++; } while(((sum-target)%2!=0)){ sum+=steps; ...
long long fun(long long a){ //sum of all natural from 1 to a long long b=a*(a+1)/2; return b; } class Solution { public: int reachNumber(int target) { long long i=1,j=pow(10,5),x=abs(target),ans=0; //for -ve or +ve positive of a number the minimum no. of steps from the origin will be same wh...
/** * @param {number} target * @return {number} */ var reachNumber = function(target) { target = Math.abs(target); let steps = 0, sum = 0; while (sum < target) { steps++; sum += steps; } while ((sum - target) % 2 !== 0) { steps++; sum += steps; } return ste...
Reach a Number
You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the va...
class Solution: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n) if rem == 0: if 1 <= missing_val <= 6: return [missing_val] * n elif 1 <= missing_val < 6: retu...
class Solution { public int[] missingRolls(int[] rolls, int mean, int n) { int i,m=rolls.length,sum=0; for(i=0;i<m;i++) sum+=rolls[i]; int x=(mean*(m+n))-sum; if(x<=0||n*6<x||((x/n)==0)) { return new int[] {}; } int arr[]=new int[n]; int p=x/n,q=x%n; ...
class Solution { public: vector<int> missingRolls(vector<int>& rolls, int mean, int n) { int size=rolls.size(),sum=accumulate(rolls.begin(),rolls.end(),0),missingSum=0; missingSum=mean*(n+size)-sum; if(missingSum<n || missingSum>6*n) return {}; int rem=missingSum%n; ...
var missingRolls = function(rolls, mean, n) { let res = []; let sum = ((n + rolls.length) * mean) - rolls.reduce((a,b)=>a+b); if(sum>6*n || sum<1*n) return res; let dec = sum % n; let num = Math.floor(sum / n); for(let i = 0; i < n; i++){ if(dec) res.push(num+1), dec--; else res....
Find Missing Observations
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types o...
class Solution: def distributeCandies(self, candyType: List[int]) -> int: return min(len(set(candyType)), (len(candyType)//2))
class Solution { public int distributeCandies(int[] candyType) { Set<Integer> set = new HashSet<>(); for (int type : candyType) set.add(type); return Math.min(set.size(), candyType.length / 2); } }
class Solution { public: int distributeCandies(vector<int>& candyType) { unordered_set<int> s(candyType.begin(),candyType.end()); return min(candyType.size()/2,s.size()); } }; //if you like the solution plz upvote.
/** * @param {number[]} candyType * @return {number} */ var distributeCandies = function(candyType) { const set = new Set(); candyType.map(e => set.add(e)); return candyType.length/2 > set.size ? set.size : candyType.length/2 };
Distribute Candies
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. In...
class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: intervals.append(newInterval) intervals.sort(key=lambda x: x[0]) result = [] for interval in intervals: if not result or result[-1][1] < interval[0]: ...
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { if (newInterval == null || newInterval.length == 0) return intervals; List<int[]> merged = new LinkedList<>(); int i = 0; // add not overlapping while (i < intervals.length && intervals[i]...
class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { vector<vector<int>> output; int n = intervals.size(); int i = 0; while(i < n){ if(newInterval[1] < intervals[i][0]){ output.push_back(newInterva...
var insert = function(intervals, newInterval) { //Edge case if (intervals.length === 0) { return [newInterval]; } //Find the index to insert newIntervals let current = 0; while (current < intervals.length && intervals[current][0] < newInterval[0]) { current++; } intervals.sp...
Insert Interval
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. &nbsp; Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Exampl...
# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict. #as soon as len(delete) == k delete those indexes from the initial string and thats the answer. #if len(delete) < k remove k-len(delete) chars from right and thats the answer class Solution: def removeKdigits(self, s:...
class Solution { public String removeKdigits(String num, int k) { int n = num.length(); if(n == k){ return "0"; } Deque<Character> dq = new ArrayDeque<>(); for(char ch : num.toCharArray()){ while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){ ...
// 😉😉😉😉Please upvote if it helps 😉😉😉😉 class Solution { public: string removeKdigits(string num, int k) { // number of operation greater than length we return an empty string if(num.length() <= k) return "0"; // k is 0 , no need of removing / preformin...
var removeKdigits = function(num, k) { if(k == num.length) { return '0' } let stack = [] for(let i = 0; i < num.length; i++) { while(stack.length > 0 && num[i] < stack[stack.length - 1] && k > 0) { stack.pop() k-- } stack.push(num[i]) } whi...
Remove K Digits
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note:&nbsp;You are not all...
class Solution: def toHex(self, num: int) -> str: ret = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] ans = "" if num < 0: num = pow(2,32) +num if num == 0: return "0" while num > 0: ans = ret[num%16] +ans ...
class Solution { public String toHex(int num) { if(num == 0) return "0"; boolean start = true; StringBuilder sb = new StringBuilder(); for(int i = 28; i >= 0; i -= 4) { int digit = (num >> i) & 15; if(digit > 9) { char curr = (char)(digit%10...
class Solution { public: string toHex(int num) { string hex = "0123456789abcdef"; unsigned int n = num; // to handle neg numbers string ans = ""; if (n == 0) return "0"; while (n > 0) { int k = n % 16; ans += hex[k]; ...
var toHex = function(num) { let hexSymbols = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; if (num >= 0) { let hex = ""; do { let reminder = num % 16; num = Math.floor(num/16); hex = hexSymbols[reminder] + hex; } while (num > 0) ...
Convert a Number to Hexadecimal
You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 &lt;= i &lt; nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between th...
class Solution: def smallestRangeI(self, nums: List[int], k: int) -> int: return max(0, max(nums)-min(nums)-2*k)
class Solution { public int smallestRangeI(int[] nums, int k) { if (nums.length == 1) return 0; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int num: nums) { min = Math.min(min, num); max = Math.max(max, num); } ...
class Solution { public: int smallestRangeI(vector<int>& nums, int k) { int mx = *max_element(nums.begin(), nums.end()); int mn = *min_element(nums.begin(), nums.end()); return max(0, (mx-mn-2*k)); } };
var smallestRangeI = function(nums, k) { let max = Math.max(...nums); let min = Math.min(...nums); return Math.max(0, max - min- 2*k) };
Smallest Range I
Given an integer array&nbsp;nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. &nbsp; Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,...
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: if not nums or len(nums) == 0: return 0 def find_pos(sub, val): left, right = 0, len(sub) - 1 while left < right: mid = (left + right) >> 1 if sub[...
class Solution { public int findNumberOfLIS(int[] nums) { int N = nums.length; int []dp =new int[N]; int []count = new int[N]; Arrays.fill(dp,1);Arrays.fill(count,1); int maxi = 1; for(int i=0;i<N;i++){ for(int j=0;j<i;j++){ if(nums[j] < nu...
class Solution { public: int findNumberOfLIS(vector<int>& nums) { int n = nums.size(), maxI=0, inc=0; vector<int> dp(n,1), count(n,1); for(int i=0;i<n;i++) { for(int j=0;j<i;j++){ if(nums[i]>nums[j] && 1+dp[j] > dp[i]) { dp[i] = 1+dp[j]; count[i] = count[j]; } else if(nums[i]>nums[...
var findNumberOfLIS = function(nums) { const { length } = nums; const dpLength = Array(length).fill(1); const dpCount = Array(length).fill(1); for (let right = 0; right < length; right++) { for (let left = 0; left < right; left++) { if (nums[left] >= nums[right]) continue; ...
Number of Longest Increasing Subsequence
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The sh...
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: n = len(arr) i = 0 while i < n-1 and arr[i+1] >= arr[i]: i += 1 if i == n-1: return 0 j = n-1 while j >= 0 and arr[j-1] <= arr[j]: j -=...
class Solution { public int findLengthOfShortestSubarray(int[] arr) { int firstLast=0,lastFirst=arr.length-1; for(;firstLast<arr.length-1;firstLast++){ if(arr[firstLast]>arr[firstLast+1]) break; } //Base case for a non-decreasing sequence if(firstLast==arr.length-1) ret...
// itne me hi thakk gaye? class Solution { public: bool ok(int &size, vector<int> &pref, vector<int> &suff, vector<int> &arr, int &n) { for(int start=0; start<=n-size; start++) { int end = start + size - 1; int left = (start <= 0) ? 0 : pref[start-1]; int right = (end >= ...
var findLengthOfShortestSubarray = function(arr) { const n = arr.length; if (n <= 1) { return 0; } let prefix = 1; while (prefix < n) { if (arr[prefix - 1] <= arr[prefix]) { prefix++; } else { break; } } if (prefix =...
Shortest Subarray to be Removed to Make Array Sorted
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false. &nbsp; Example 1: Input: s = "00110110", k = 2 Output: true Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1,...
class Solution: def hasAllCodes(self, s: str, k: int) -> bool: Z = set() for i in range(len(s)-k+1): Z.add(s[i:i+k]) if len(Z) == 2**k: return True return False
class Solution { public boolean hasAllCodes(String s, int k) { HashSet<String> hs=new HashSet(); for(int i=0;i<=s.length()-k;i++){ hs.add(s.substring(i,i+k)); } if(hs.size() == Math.pow(2,k))return true; return false; } }
class Solution { public: bool hasAllCodes(string s, int k) { if (s.size() < k) { return false; } unordered_set<string> binary_codes; for (int i = 0; i < s.size()-k+1; i++) { string str = s.substr(i, k); binary_codes.insert(str); ...
/** * @param {string} s * @param {number} k * @return {boolean} */ var hasAllCodes = function(s, k) { if (k > s.length) { return false; } /* Max strings can be generated of k chars 0/1. */ const max = Math.pow(2, k); /* * Create a set. * It will contain all unique...
Check If a String Contains All Binary Codes of Size K
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j]. Return the minimum number of swaps required to make s1 and s2 equa...
class Solution: def minimumSwap(self, s1: str, s2: str) -> int: h = defaultdict(int) count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd for i in range(len(s1)): if s1[i] != s2[i]: count += 1 ...
class Solution { public int minimumSwap(String s1, String s2) { if(s1.length() != s2.length()) return -1; int n = s1.length(); int x = 0 , y = 0; for(int i = 0 ; i < n ; i ++){ char c1 = s1.charAt(i) , c2 = s2.charAt(i); if(c1 == 'x' && c2 == 'y') x++; ...
class Solution { public: int minimumSwap(string s1, string s2) { int n = s1.size(); int cnt1=0,cnt2=0,i=0; while(i<n){ int x = s1[i]; int y = s2[i++]; if(x=='x' and y=='y') cnt1++; if(x=='y' and y=='x') cnt2++; } ...
var minimumSwap = function(s1, s2) { let count1 = 0; let count2 = 0; for(let i in s1) { if(s1[i] === "x" && s2[i] === "y") { count1++ } if(s1[i] === "y" && s2[i] === "x") { count2++ } } let ans = Math.floor(count1 / 2) + Math.floor(count2 / 2); if...
Minimum Swaps to Make Strings Equal
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. &nbsp; Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined...
# TC : O(N) # SC : O(1) class Solution: def longestOnes(self, nums: List[int], k: int) -> int: z_count = 0 #count zeors in nums mx_ones = 0 j = 0 for i in range(len(nums)): if nums[i] == 0: z_count+=1 while z_count>k:#if zeros count cross k de...
class Solution { public int longestOnes(int[] nums, int k) { int ans = 0; int j = -1; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { count++; } while (count > k) { j++; if ...
class Solution { public: int longestOnes(vector<int>& nums, int k) { // max length of subarray with at most k zeroes int i=0; int j=0; int cnt = 0; int ans = 0; int n = nums.size(); while(j<n) { if(nums[j]==0) ...
* @param {number[]} nums * @param {number} k * @return {number} */ var longestOnes = function(nums, k) { let left = 0; let oneCount = 0; let maxLength = 0; for (let right = 0; right < nums.length; right ++) { if (nums[right]) { // so if the element is a 1 since 0 is falsy o...
Max Consecutive Ones III
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1....
class Solution: def longestCycle(self, edges: List[int]) -> int: preorder = [-1 for _ in range(len(edges))] self.ans = -1 self.pre = 0 def dfs(self, i: int, st: int) -> None: preorder[i] = self.pre self.pre += 1 if edges[i] ==...
class Solution { public int longestCycle(int[] edges) { int[] map = new int[edges.length]; int result = -1; for (int i = 0; i < edges.length; i++) result = Math.max(result, helper(i, 1, edges, map)); return result; } int helper(int index, int total, int[] edges...
class Solution { public: int maxLength = -1; void getcycle(vector<int> &edges,int si,vector<bool>& visit,vector<int>& store){ if(si == -1)return ; if(visit[si]){ int count = -1; for(int i =0;i<store.size();i++){ if(store[i]==si){ ...
/** * @param {number[]} edges * @return {number} */ function getCycleTopology(edges){ const indeg = new Array(edges.length).fill(0); const queue = []; const map = {}; for(const src in edges){ const des = edges[src] if(des >= 0){ indeg[des] ++; } map[src] ? ...
Longest Cycle in a Graph
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. &nbsp; Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the f...
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] i=0 for num in pushed: stack.append(num) #we are pushing the number to the stack while len(stack) >0 and stack[len(stack)-1] == popped[i] : #if th...
class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { Stack<Integer> st = new Stack<>(); // Create a stack int j = 0; // Intialise one pointer pointing on popped array for(int val : pushed){ st.push(val); // insert the values in stack ...
class Solution { public: bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { stack<int> st; // Create a stack int j = 0; // Intialise one pointer pointing on popped array for(auto val : pushed){ st.push(val); // insert the values in stack ...
var validateStackSequences = function(pushed, popped) { let stack = []; let j = 0; for(let i=0; i<pushed.length; i++){ stack.push(pushed[i]); while(stack.length != 0 && popped[j]== stack[stack.length-1]){ stack.pop(); j++ } } return stack.length<1...
Validate Stack Sequences
You are given a 0-indexed positive integer array nums and a positive integer k. A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Both the numbers num1 and num2 exist in the array nums. The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than o...
class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: hamming = sorted([self.hammingWeight(num) for num in set(nums)]) ans = 0 for h in hamming: ans += len(hamming) - bisect.bisect_left(hamming, k - h) return ans def hammingWeight(self, n): ...
class Solution { public long countExcellentPairs(int[] nums, int k) { HashMap<Integer,Set<Integer>> map = new HashMap<>(); for(int i : nums){ int x = Integer.bitCount(i); map.putIfAbsent(x,new HashSet<>()); map.get(x).add(i); } long ans = 0; ...
class Solution { public: typedef long long ll; int setbits(int n){ int cnt = 0; while(n){ cnt += (n%2); n /= 2; } return cnt; } long long countExcellentPairs(vector<int>& nums, int k) { unordered_set<int> s(nums.begin(),nums.end()); ...
var countExcellentPairs = function(nums, k) { const map = new Map(); const set = new Set(); const l = nums.length; let res = 0; for (let num of nums) { let temp = num.toString(2).split("1").length - 1; if (!map.has(temp)) { map.set(temp, new Set([num])); } else { ...
Number of Excellent Pairs
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| &lt;= d. &nbsp; Example 1: Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2 Ou...
class Solution: def findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int: result = 0 array2 = sorted(array2) for num in array1: flag = True low = 0 high = len(array2)-1 while low <= high: mid = (low + high) // 2 if abs(array2[mid] - num) <= d: flag = Fa...
class Solution { public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { int x=0,val=0; for(int i:arr1){ for(int j:arr2){ if(Math.abs(i-j)<=d){ x--; break; } } x++; } ret...
class Solution { public: int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) { sort(arr2.begin(),arr2.end()); int ans = 0; for(int i : arr1){ int id = lower_bound(arr2.begin(),arr2.end(),i) - arr2.begin(); int closest = d+1; if(id != arr2...
/** * @param {number[]} arr1 * @param {number[]} arr2 * @param {number} d * @return {number} */ var findTheDistanceValue = function(arr1, arr2, d) { const arr2Sorted = arr2.sort((a, b) => a - b); let dist = 0; for (const num of arr1) { if (isDistanceValid(num, d, arr2Sorted)) { dis...
Find the Distance Value Between Two Arrays
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) bein...
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: #dic for memoization dic = {} def dfs(i, j): if (i, j) in dic: return dic[(i, j)] #see if there is any case where both i and j reach to the end, cuz that will be the true conditi...
class Solution { public boolean isLongPressedName(String name, String typed) { int i = 0; int j = 0; int m = name.length(); int n = typed.length(); while(j < n) { if(i < m && name.charAt(i) == typed.charAt(j)) { i++; ...
class Solution { public: bool isLongPressedName(string name, string typed) { int j = 0, i = 0; for( ; i<name.length() && j<typed.length() ; i++) { if(name[i]!=typed[j++]) return false; if(i<name.length() && name[i]!= ...
var isLongPressedName = function(name, typed) { let i = 0; let j = 0; while (j < typed.length) { if (i < name.length && name[i] === typed[j]) i++; else if (typed[j] !== typed[j - 1]) return false; // this needs when name is traversed but there is tail of characters in typed j++; // B...
Long Pressed Name
You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li &lt;= j &lt;= ri is colored white. You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. Return the maximum number of white tiles that can be covered by the carpe...
class Solution: def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: tiles.sort() #j: window index j = cover = res = 0 for i in range(len(tiles)): #slide the window as far as we can to cover fully the intervals with the carpet while j<len(tiles) and ti...
class Solution { public int maximumWhiteTiles(int[][] tiles, int carpetLen) { Arrays.sort(tiles,(a,b)->{return a[0]-b[0];}); int x = 0; int y = 0; long maxCount = 0; long count = 0; while(y < tiles.length && x <= y) { long start = tile...
class Solution { public: int maximumWhiteTiles(vector<vector<int>>& tiles, int carpetLen) { long long n = tiles.size() , ans = INT_MIN; sort(tiles.begin(),tiles.end()); vector<long long> len(n) , li(n); //len array stores the prefix sum of tiles //li array stores the last index tiles[i] ...
/** * @param {number[][]} tiles * @param {number} carpetLen * @return {number} */ var maximumWhiteTiles = function(tiles, carpetLen) { const sorted = tiles.sort((a, b) => a[0]-b[0]) let res = 0 let total = 0 let right = 0 for (let tile of sorted){ const start = tile[0] const en...
Maximum White Tiles Covered by a Carpet
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. &nbsp; Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Exa...
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l,r = 0, len(nums)-1 pointer = 0 arr = [0] *len(nums) pointer = r while l<=r: if abs(nums[r]) > abs(nums[l]): arr[pointer] = nums[r] **2 r-=1 poi...
class Solution { public int[] sortedSquares(int[] nums) { int s=0; int e=nums.length-1; int p=nums.length-1; int[] a=new int[nums.length]; while(s<=e){ if(nums[s]*nums[s]>nums[e]*nums[e]){ a[p--]=nums[s]*nums[s]; s++; } ...
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { for(int i=0;i<nums.size();i++){ nums[i] = nums[i]*nums[i]; } sort(nums.begin(),nums.end()); return nums; } };
var sortedSquares = function(nums) { let left = 0; let right = nums.length - 1; const arr = new Array(nums.length); let arrIndex = arr.length - 1; while (left <= right) { if (Math.abs(nums[left]) > Math.abs(nums[right])) { arr[arrIndex] = nums[left] * nums[left]; left++; } else { arr[arrIndex] = nums...
Squares of a Sorted Array
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row ...
class Solution: def minFallingPathSum(self, matrix: List[List[int]]) -> int: for row in range(1, len(matrix)): for col in range(0, len(matrix[row])): if col == 0: matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col]) elif col == len...
class Solution { public int min(int[][] matrix, int[][]dp, int i, int j) { int a,b,c; if(i==0) return matrix[i][j]; if(dp[i][j] != Integer.MAX_VALUE) return dp[i][j]; if(j==0) { dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp,...
class Solution { public: int check( int i , int j , int n ){ if( i <0 || j<0 || i>=n || j>=n ) return 0; return 1; } int solve(vector<vector<int>>&mat , int i , int j , int n , vector<vector<int>>&dp ){ if(not check( i , j , n )) return 9...
var minFallingPathSum = function(matrix) { let n = matrix.length; let m = matrix[0].length; let dp = new Array(n).fill(0).map(() => new Array(m).fill(0)); // tabulation // bottom-up approach // base case - when i will be 0, dp[0][j] will be matrix[0][j] for(let j = 0; j < m; j++) dp[0]...
Minimum Falling Path Sum
You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i &lt; j and j - i != nums[j] - nums[i]. Return the total number of bad pairs in nums. &nbsp; Example 1: Input: nums = [4,1,3,3] Output: 5 Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4. The pair (0, 2) is a bad ...
class Solution: def countBadPairs(self, nums: List[int]) -> int: nums_len = len(nums) count_dict = dict() for i in range(nums_len): nums[i] -= i if nums[i] not in count_dict: count_dict[nums[i]] = 0 count_dict[nums[i]] += 1 ...
class Solution { public long countBadPairs(int[] nums) { HashMap<Integer, Integer> seen = new HashMap<>(); long count = 0; for(int i = 0; i < nums.length; i++){ int diff = i - nums[i]; if(seen.containsKey(diff)){ count += (i - seen.get(diff)); ...
class Solution { public: long long countBadPairs(vector<int>& nums) { //j - i != nums[j] - nums[i] means nums[i]-i != nums[j]-j map<long long,long long >mp; for(int i=0;i<nums.size();i++) { nums[i] = nums[i]-i; mp[nums[i]]++; } ...
/** * @param {number[]} nums * @return {number} */ var countBadPairs = function(nums) { let map={},goodPair=0; for(let i=0;i<nums.length;i++){ let value = nums[i]-i; if(map[value]!==undefined){ goodPair += map[value]; map[value]++; }else{ map[value]...
Count Number of Bad Pairs
A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string s is primitive if it is nonempty, and there does ...
class Solution: def removeOuterParentheses(self, s: str) -> str: c=0 res='' for i in s: if i==')' and c==1: c=c-1 elif i=='(' and c==0: c=c+1 elif i=='(': res=res+'(' c=c+1 elif i=...
class Solution { public String removeOuterParentheses(String s) { // if '(' check stack size > 0 add ans else not add ans // if ')' check stack size > 0 add ans else not add ans Stack<Character> st = new Stack<>(); StringBuilder sb = new StringBuilder(); for(int i=0;i<s.length();...
class Solution { public: stack<char>p; int count=0; string removeOuterParentheses(string s) { string ans={}; for(auto &i:s){ if(i=='(' && count==0){ p.push(i); count++; } else if (i=='(' && count!=0){ ans+='...
var removeOuterParentheses = function(s) { let open = -1, ans = "", stack = []; for(let c of s) { if(c == '(') { // open for top level open if(open != -1) ans += c; stack.push(open) open++; } else { open = stack.pop(); // cl...
Remove Outermost Parentheses
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. &nbsp; Example 1: Input: nums = [7,2,5,10,8], m = 2 Output: 18 Explanation: There are four ways to split...
class Solution: def splitArray(self, nums: List[int], m: int) -> int: lo, hi = max(nums), sum(nums) while lo < hi: mid = (lo+hi)//2 tot, cnt = 0, 1 for num in nums: if tot+num<=mid: tot += num else: ...
class Solution { int[] nums; public int splitArray(int[] nums, int m) { this.nums = nums; int low = 0, high = 0, min = Integer.MAX_VALUE; for(int i=0;i<nums.length;i++){ low = Math.max(low, nums[i]); high += nums[i]; } while(low <= high) { ...
class Solution { public: int splitArray(vector<int>& nums, int m) { long long low = 0; long long res =0; long long high = 1000000005; while(low<=high){ long long mid = (low+high)/2; int cnt = 1; long long current_sum = 0; int can = 1; ...
var splitArray = function(nums, m) { const n = nums.length; var mat = []; var sumArr = [nums[0]]; for(let i=1; i<n; i++){ sumArr.push(sumArr[i-1]+nums[i]);//find prefix sum } mat.push(sumArr); for(let i=0; i<n-1;i++){//form prefix matrix, i.e. every row i shows prefix sum starting from i let arr = new Array(n)....
Split Array Largest Sum
Given a 2D grid of 0s and 1s, return the number of elements in&nbsp;the largest square&nbsp;subgrid that has all 1s on its border, or 0 if such a subgrid&nbsp;doesn't exist in the grid. &nbsp; Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1 &nbsp; Const...
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)] for i in range(m): for j in range(n): if i > 0: if grid[i][j] =...
class Solution { public int largest1BorderedSquare(int[][] grid) { int m=grid.length; int n=grid[0].length; // rows[r][c] is the length of the line ended at [r,c] on row r int[][] rows=new int[m][n]; // the length of the line ended at [r,c] on colume c int[][] cols=new in...
class Solution { public: int largest1BorderedSquare(vector<vector<int>>& g) { int n=g.size(); int m=g[0].size(); int ver[n][m]; // to store lenght of continuous 1's vertically int hor[n][m]; // to store lenght of continuous 1's horizontally // fill vertical table for(int...
var largest1BorderedSquare = function(grid) { let m = grid.length, n = grid[0].length; let top = Array(m).fill(0).map(() => Array(n).fill(0)); let left = Array(m).fill(0).map(() => Array(n).fill(0)); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { left[i][j]...
Largest 1-Bordered Square
Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s ...
class Solution: def compress(self, chars: List[str]) -> int: stri = '' stack = [chars.pop(0)] while chars: p = chars.pop(0) if p in stack: stack.append(p) else: stri = stri + stack[-1] + str(len(stack) ...
class Solution { public int compress(char[] chars) { int index = 0; int i = 0; while (i < chars.length) { int j = i; while (j < chars.length && chars[j] == chars[i]) { j++; } chars[index++] = chars[i]; if (j - i ...
class Solution { public: void add1(vector<int>& arr) { if(arr.back() < 9) { arr.back()++; return ; } reverse(begin(arr),end(arr)); int carry = 1; for(int i=0;i<arr.size();i++) { if(arr[i] < 9) {arr[i]++;carry=0;break;} arr[i] = 0; ...
var compress = function(chars) { for(let i = 0; i < chars.length; i++){ let count = 1 while(chars[i] === chars[i+count]){ delete chars[i+count] count++ } if(count > 1){ let count2 = 1 String(count).split('').forEach((a) =>{ ...
String Compression
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s ...
class Solution: def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str: def find(n: TreeNode, val: int, path: List[str]) -> bool: if n.val == val: return True if n.left and find(n.left, val, path): path += "L" ...
class Solution { private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) { if(currNode == null) return false; if(currNode.val == destVal) return true; if(DFS(currNode.left, path, destVal)) path.append("L"); else if(DFS(currNode.right, path, destVal)) path.append(...
class Solution { public: bool search(TreeNode* root, int target, string &s){ if(root==NULL) { return false; } if(root->val==target) { return true; } bool find1=search(root->left,target, s+='L'); // search on left side if(find1) return...
var getDirections = function(root, startValue, destValue) { const getPath = (node, value, acc='') => { if (node === null) { return ''; } else if (node.val === value) { return acc; } else { return getPath(node.left, value, acc + 'L') + getPath(node.right, v...
Step-By-Step Directions From a Binary Tree Node to Another
On day 1, one person discovers a secret. You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after dis...
```class Solution: def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int: table = [0]*(forget+1) table[1] = 1 days = 1 while days<=n-1: count = 0 for k in range(forget-1,-1,-1): if k+1>delay: table[k+1] = tab...
class Solution { public int peopleAwareOfSecret(int n, int delay, int forget) { long mod = 1000000007L; long[] shares = new long[n + 1]; long[] forgets = new long[n + 1]; if (delay < n) { shares[delay + 1] = 1; } if (forget < n) { forgets[forg...
static int MOD=1e9+7; class Solution { public: int delay,forget; vector<long> memo; // Total number of people who would have found out about the secret by the nth day. long dp(int n) { if(!n) return 0; if(memo[n]!=-1) // Return cached result if exists. return mem...
/** * @param {number} n * @param {number} delay * @param {number} forget * @return {number} */ var peopleAwareOfSecret = function(n, delay, forget) { const dp=new Array(n+1).fill(0); let numberOfPeopleSharingSecret = 0; let totalNumberOfPeopleWithSecret = 0; const MOD = 1000000007n; dp[1]=...
Number of People Aware of a Secret