algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums =...
class Solution: def waysToMakeFair(self, nums: List[int]) -> int: if len(nums) == 1: return 1 if len(nums) == 2: return 0 prefixEven = sum(nums[2::2]) prefixOdd = sum(nums[1::2]) result = 0 if prefixEven == prefixOdd and len(set(nums)) == 1: result += 1 for i in range(1,len(nums)): if i =...
class Solution { public int waysToMakeFair(int[] nums) { /* Idea - have left (odd & even) & right (odd & even) odd & even sums separately as we move each element subtract & add appropriately */ int count = 0; int evenLeft =...
class Solution { public: int waysToMakeFair(vector<int>& nums) { //it looks a quite complicated problem but actually it is not //the main observation here is when a element is deleted the odd sum after the element becomes the evensum and vice versa //so we maintain two vectors left and right...
/** * @param {number[]} nums * @return {number} */ var waysToMakeFair = function(nums) { let oddSum = 0; let evenSum = 0 ; let count = 0; for (let i = 0; i < nums.length; i++) { if (i % 2 === 0) { evenSum += nums[i]; } else { oddSum += nums[i]; } ...
Ways to Make a Fair Array
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multipl...
class Solution: def simplifyPath(self, path: str) -> str: stack = [] i = 0 while i < len(path): if path[i] == '/': i += 1 continue else: cur = '' while i < len(path) and path[i] != '/': cur += pa...
class Solution { public String simplifyPath(String path) { String[] paths = path.split("/"); Stack<String> st=new Stack<>(); for(String dir:paths){ if(dir.equals(".") || dir.length()==0) continue; else{ if(!st.isEmpty() && dir.equals("..")) ...
// Please upvote if it helps class Solution { public: string simplifyPath(string path) { stack<string> st; string res; for(int i = 0; i<path.size(); ++i) { if(path[i] == '/') continue; string temp; // iterate t...
var simplifyPath = function(path) { let stack=[]; path=path.split("/") for(let i=0;i<path.length;i++){ if(path[i]==="" || path[i]===".")continue; if(path[i]===".."){ stack.pop(); }else{ stack.push(path[i]); } } //edge case if(stack.length==...
Simplify Path
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i &lt;= k &lt;= j. Return the maximum possible score of a good subarray. &nbsp; Example 1: Input: nums = [1,4,3,...
class Solution: def nextSmallerElement(self, nums): nextSmaller = [None] * len(nums) stack = [[-sys.maxsize, -1]] for i in range(len(nums)-1, -1, -1): while nums[i] <= stack[-1][0]: stack.pop() nextSmaller[i] = stack[-1][1] stack.append([nu...
class Solution { public int maximumScore(int[] nums, int k) { int n = nums.length; int i = k - 1, j = k + 1; int min = nums[k]; int ans = min; while(i >= 0 || j < n) { int v1 = 0, v2 = 0; int min1 = min, min2 = min; if(i >= 0) { ...
class Solution { public: int maximumScore(vector<int>& nums, int k) { nums.push_back(0); stack<int> st ; int n = nums.size(), res = 0; for(int i=0; i<n ; i++){ while(!st.empty() && nums[st.top()] >= nums[i]){ int height = nums[st.top()]; st...
/* JAVASCRIPT */ var maximumScore = function(nums, k) { // iterate to the left to update the minimum value at each index let min = nums[k]; for (let i = k - 1; i >= 0; i--) { min = Math.min(min, nums[i]); nums[i] = min; } // iterate to the right to update the minimum value at ea...
Maximum Score of a Good Subarray
Given an array of integers&nbsp;arr&nbsp;and an integer k.&nbsp;Find the least number of unique integers&nbsp;after removing exactly k elements. &nbsp; Example 1: Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Remove the single 4, only 5 is left. Example 2: Input: arr = [4,3,1,1,3,3,2], k = 3 Output: 2 Expla...
from heapq import heappop, heapify class Solution: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: counter = collections.Counter(arr) min_heap = [(count, num) for num, count in counter.items()] heapify(min_heap) while k > 0: count, num = mi...
class Solution { public int findLeastNumOfUniqueInts(int[] arr, int k) { Map<Integer,Integer> freqMap = new HashMap<>(); for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1); PriorityQueue<Integer> pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2))); ...
class Solution { public: int findLeastNumOfUniqueInts(vector<int>& arr, int k) { int ans; unordered_map<int,int> mp; for(int i=0; i<arr.size(); i++){ mp[arr[i]]++; } priority_queue< int, vector<int>, greater<int>> pq; for(auto it : mp){ ...
var findLeastNumOfUniqueInts = function(arr, k) { var hsh = {}; var instance = {}; // store set with index # of occurence var count = 0; for (var i = 0; i < arr.length; i++) { if (hsh[arr[i]] == null) { count ++; hsh[arr[i]] = 1; if (instance[1] =...
Least Number of Unique Integers after K Removals
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: Move the poin...
class Solution: def minTimeToType(self, word: str) -> int: prev = "a" res = 0 for c in word: gap = abs(ord(c)-ord(prev)) res += min(gap, 26 - gap) prev = c return res + len(word)
class Solution { public int minTimeToType(String word) { char prevChar = 'a'; int totalTime = word.length(); for(int i = 0; i < word.length(); i++){ char currChar = word.charAt(i); int diff = Math.abs(currChar - prevChar); totalTime += Math.min(diff, 26 - ...
class Solution { public: int minTimeToType(string word) { int res = word.size(), point = 'a'; for (auto ch : word) { res += min(abs(ch - point), 26 - abs(point - ch)); point = ch; } return res; } };
var minTimeToType = function(word) { let ops = 0; let cur = 'a'; for(const char of word) { const diff = Math.abs(cur.charCodeAt(0) - char.charCodeAt(0)); if(diff > 13) { ops += 26 - diff + 1; } else { ops += diff + 1; } cur = char; } return ops; };
Minimum Time to Type Word Using Special Typewriter
Given a 0-indexed n x n integer matrix grid, return the number of pairs (Ri, Cj) such that row Ri and column Cj are equal. A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array). &nbsp; Example 1: Input: grid = [[3,2,1],[1,7,6],[2,7,7]] Output: 1 Explanati...
class Solution: def equalPairs(self, grid: List[List[int]]) -> int: m = defaultdict(int) cnt = 0 for row in grid: m[str(row)] += 1 for i in range(len(grid[0])): col = [] for j in range(len(grid)): col.append(grid[j][i]) ...
class Solution { public int equalPairs(int[][] grid) { HashMap<String, Integer> map = new HashMap<>(); int row = grid.length; int col = grid.length; for(int i = 0; i < row; i++){ String res = ""; for(int j = 0; j < col; j++){ res += "-" + grid[...
class Solution { public: int equalPairs(vector<vector<int>>& grid) { // Number to store the count of equal pairs. int ans = 0; map<vector<int>, int> mp; // Storing each row int he map for (int i = 0; i < grid.size(); i++) mp[grid[i]]++; for (...
var equalPairs = function(grid) { let n = grid.length let count = 0; let map = new Map() //making rowArray for(let row = 0; row < n; row++){ let temp = [] for(let col = 0; col < n; col++){ temp.push(grid[row][col]) } temp = temp.join() if(map.h...
Equal Row and Column Pairs
A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself. The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and ...
class Solution: def magicalString(self, n: int) -> int: queue, ans, i = deque([2]), 1, 1 while i <= n - 2: m = queue.popleft() ans += (m == 1) queue.extend([1 + (i % 2 == 0)] * m) i += 1 return ans
class Solution { public int magicalString(int n) { if(n <= 3) return 1; Magical m = new Magical(); int ans = 1; for(int i = 3; i < n; ++i) if(m.next() == 1) ++ans; return ans; } } class Magical{ private Deque<Integer> nums; ...
class Solution { public: int magicalString(int n) { string s="122"; int sz=3; int start=2,lastDig=2; while(sz<n){ int cnt=s[start++]-'0'; int currDig=(lastDig==2)?1:2; for(int i=0;i<cnt;i++){ s.push_back('0'+currDig); ...
var magicalString = function(n) { const stack = ['1', '2', '2']; let magic = 2; while (stack.length < n) { const count = stack[magic++]; const last = stack[stack.length - 1]; const addStr = last === '1' ? '2' : '1'; for (let n = 1; n <= count; n++) stack.push(addStr); }...
Magical String
Design a text editor with a cursor that can do the following: Add text to where the cursor is. Delete text from where the cursor is (simulating the backspace key). Move the cursor either left or right. When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain with...
class TextEditor: def __init__(self): self.s = '' self.cursor = 0 def addText(self, text: str) -> None: self.s = self.s[:self.cursor] + text + self.s[self.cursor:] self.cursor += len(text) def deleteText(self, k: int) -> int: new_cursor = max(0, self.cursor - k) ...
class TextEditor { StringBuilder res; int pos=0; public TextEditor() { res = new StringBuilder(); } public void addText(String text) { res.insert(pos,text); pos += text.length(); } public int deleteText(int k) { int tmp = pos; pos -= k; if(p...
class TextEditor { stack<char> left; stack<char> right; public: TextEditor() { } void addText(string text) { for(auto &c : text){ left.push(c); } } int deleteText(int k) { int cnt=0; while(!left.empty() and k>0){ left.pop(); ...
var TextEditor = function() { this.forward = []; this.backward = []; }; /** * @param {string} text * @return {void} */ TextEditor.prototype.addText = function(text) { for (let letter of text) { this.forward.push(letter); } }; /** * @param {number} k * @return {number} */ TextEditor.pro...
Design a Text Editor
You are given a 0-indexed integer array nums. In one operation, you may do the following: Choose two integers in nums that are equal. Remove both integers from nums, forming a pair. The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the n...
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: ans = [0] * 2 c = Counter(nums) for v in c.values(): ans[0] += (v // 2) ans[1] += (v % 2) return ans
class Solution { public int[] numberOfPairs(int[] nums) { if(nums.length == 1) return new int[]{0,1}; HashSet<Integer> set = new HashSet<>(); int pairs=0; for(int i : nums){ if(!set.contains(i)){ set.add(i); // No pair present }else{ ...
class Solution { public: //store the frequency of each of the number in the map and //then return the answer as sum all the values dividing 2 and //sum all by taking reminder of 2 vector<int> numberOfPairs(vector<int>& nums) { unordered_map<int, int> mp; for(auto i: nums) mp[i]++; int c1...
/** * @param {number[]} nums * @return {number[]} */ var numberOfPairs = function(nums) { let pairs = 0; const s = new Set(); for (const num of nums) { if (s.has(num)) { pairs += 1; s.delete(num); } else { s.add(num); } } return [pairs, nums.length - pairs * 2]; };
Maximum Number of Pairs in Array
You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not eng...
class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: n = len(prices) lookup = {} def f(ind, buy, lookup): if ind == n: return 0 if (ind, buy) in lookup: return lookup[(ind, buy)] profit = 0 if buy: ...
class Solution { public int maxProfit(int[] prices, int fee) { int[][] dp = new int[prices.length][2]; for (int[] a : dp) { a[0] = -1; a[1] = -1; } return profit(prices, fee, 0, 1, dp); } public int profit(int[] prices, int fee, int i, int buy, int[][]...
class Solution { public: int ans=0; int f(vector<int>&prices,int i,int buy,vector<vector<int>>&dp,int fee){ if(i==prices.size())return 0; if(dp[i][buy]!=-1)return dp[i][buy]; int take=0; if(buy){ take=max(-prices[i]+f(prices,i+1,0,dp,fee),f(prices,i+1,1,dp,fee)); ...
/** * @param {number[]} prices * @param {number} fee * @return {number} */ var maxProfit = function(prices, fee) { let purchase = -1*prices[0];//If we purchase on 0th day let sell=0;//If we sell on 0th day let prevPurchase; for(let i=1;i<prices.length;i++){ prevPurchase = purchase; p...
Best Time to Buy and Sell Stock with Transaction Fee
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: If a word begins with a vowel ('a', 'e', 'i'...
class Solution: def toGoatLatin(self, sentence: str) -> str: wordList, result, index = sentence.split(' '), "", 1 for word in wordList: if index > 1: result += " " firstLetter = word[0] if firstLetter in 'aeiouAEIOU': result += word...
class Solution { public String toGoatLatin(String sentence) { StringBuffer sb = new StringBuffer(); StringBuffer temp = new StringBuffer("a"); // temporary stringbuffer for(String str : sentence.split(" ")) { if(beginsWithConsonant(str)) { sb.append(str.substring...
class Solution { public: string toGoatLatin(string sentence) { sentence += ' '; vector<string> Words; string TEMP, SOL, A = "a"; for (int i = 0; i < sentence.size(); ++i) { if (sentence[i] == ' ') { Words.push_back(TEMP); ...
/** * @param {string} S * @return {string} */ var toGoatLatin = function(S) { let re = /[aeiou]/gi let word = S.split(' ') let add = 0 let arr = [] for(let i= 0; i < word.length; i++) { if(!word[i].substring(0,1).match(re)) { arr = word[i].split('') let letter...
Goat Latin
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. &nbsp; Example 1: Input: root = [4,2,6,1,3] Output: 1 Example 2: Input: root = [1,0,48,null,null,12,49] Output: 1 &nbsp; Constraints: The number of nodes in the tree ...
class Solution: def getMinimumDifference(self, root: Optional[TreeNode]) -> int: cur, stack, minDiff, prev = root, [], 10**5, -10**5 while stack or cur: while cur: stack.append(cur) cur = cur.left node = stack.pop() minDiff...
class Solution { public int getMinimumDifference(TreeNode root) { Queue<Integer> queue=new PriorityQueue<>(); Queue<TreeNode> nodesQueue=new LinkedList<>(); int min=Integer.MAX_VALUE; if(root==null) return 0; nodesQueue.add(root); while(!nodesQueue.isEmpty()) { ...
class Solution { TreeNode* pre = nullptr; int minimum = std::numeric_limits<int>:: max(); public: void inorder(TreeNode* node) { if (!node) return; inorder(node->left); if(pre) { minimum = min(node->val - pre->val, minimum); } pre = node; inorder(n...
var getMinimumDifference = function(root) { let order = inOrder(root, []); let diff = Math.abs(order[1] - order[0]); for(let i=0;i<order.length;i++) { for(let j=i+1;j<order.length;j++) { if(Math.abs(order[i] - order[j]) < diff) diff = Math.abs(order[i] - order[j]) } } ret...
Minimum Absolute Difference in BST
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tre...
class Codec: def serialize(self, root: Optional[TreeNode]) -> str: """Encodes a tree to a single string. """ if not root: return "" res = [] def dfs(node): res.append(str(node.val)) if node.left: dfs(node.left) i...
public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder string = new StringBuilder(); traverse(root, string); return string.toString(); } private void traverse(TreeNode root, StringBuilder string){ if(root == nul...
class Codec { public: string pre(TreeNode * root) { if(root==NULL) return ""; int temp = root->val; string tempz = to_string(temp); string l = pre(root->left); string r = pre(root->right); return (tempz + "," + l + "," + r); } vector<i...
;/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */ var serialize = function(root) { // Using Preorder traversal to create a string...
Serialize and Deserialize BST
You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm: The ith (0-indexed) request arrives. If...
class Solution: def busiestServers(self, k: int, A: List[int], B: List[int]) -> List[int]: available = list(range(k)) # already a min-heap busy = [] res = [0] * k for i, a in enumerate(A): while busy and busy[0][0] <= a: # these are done, put them back as available ...
class Solution { public List<Integer> busiestServers(int k, int[] arrival, int[] load) { // use a tree to track available servers TreeSet<Integer> availableServerIdxs = new TreeSet<Integer>(); for (int num = 0; num < k; num++) { availableServerIdxs.add(num); } //...
class Solution { public: vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) { int n = (int)arrival.size(); set<int> freeServers; for (int i = 0; i < k; i++) freeServers.insert(i); vector<int> serverTaskCount(k, 0); set<pair<i...
var busiestServers = function(k, arrival, load) { let loadMap = {}; let pq = new MinPriorityQueue({ compare: (a,b) => a[1] - b[1] }); let availableServers = new Set(new Array(k).fill(0).map((_, index) => index)); for (let i = 0; i < arrival.length; i++) { // calc end time let end = arri...
Find Servers That Handled Most Number of Requests
You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 &lt;= i &lt; nums.le...
class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: for i in range(1, len(nums) -1): pre = nums[i-1] current = nums[i] next = nums[i+1] # If block will run when we meet 1 2 3 or 6 4 2 if (pre < current < next) or (p...
class Solution { public int[] rearrangeArray(int[] nums) { Arrays.sort(nums); // sort in wave format for(int i = 0;i<nums.length-1;i+=2){ int temp = nums[i]; nums[i] = nums[i+1]; nums[i+1] = temp; } return nums; } }
//Approach-1 (Using sorting O(nlogn)) /* If you make sure that nums[i-1] < nums[i] > nums[i+1] You are good to go. So, just sort the input and choose wisely to satisfy above condition. Example : [6,2,0,9,7] sort it : [0, 2, 6, 7, 9] result : [0, _, 2, _, 6] - 1st loop (fill alternalte...
var rearrangeArray = function(nums) { let arr=[], res=[] for(let q of nums) arr[q]= 1 let l=0, r=arr.length-1 while(l<=r){ while(!arr[l])l++ while(!arr[r])r-- if(l<=r)res.push(l++) if(l<=r)res.push(r--) } return res };
Array With Elements Not Equal to Average of Neighbors
Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only. You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given th...
class Solution: def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int: special.sort() special.insert(0, bottom - 1) special.append(top + 1) ans = 0 for i in range(len(special)-1): ans = max(ans, special[i+1] - special[i] - 1) ...
class Solution { public int maxConsecutive(int bottom, int top, int[] special) { int max = Integer.MIN_VALUE; Arrays.sort(special); // from bottom to the first special floor max = Math.max(max, special[0] - bottom); // middle floors for(int i = 1; i < special.lengt...
class Solution { public: int maxConsecutive(int bottom, int top, vector<int>& special) { int res(0), n(size(special)); sort(begin(special), end(special)); for (int i=1; i<n; i++) { res = max(res, special[i]-special[i-1]-1); } return max({res, special[0]-bottom,...
/** * @param {number} bottom * @param {number} top * @param {number[]} special * @return {number} */ var maxConsecutive = function(bottom, top, special) { special.push(top+1); special.push(bottom-1); special.sort((a, b) => a - b); let specialMax = 0; for (let i = 1; i < special.length; i++){ ...
Maximum Consecutive Floors Without Special Floors
We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Given a string word, return true if the usage o...
class Solution: def detectCapitalUse(self, word: str) -> bool: l=len(word) if l==1: return True if word[0]==word[0].lower() and word[1]==word[1].upper(): return False u=False if word[0]==word[0].upper(): if word[1]==word[1].upp...
class Solution { public boolean detectCapitalUse(String word) { int count = 0; for(int i=0; i < word.length(); i++){ if('A' <= word.charAt(i) && word.charAt(i) <= 'Z') count++; } if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt...
class Solution { public: bool detectCapitalUse(string word) { int n = word.size(); //if the first letter of the string is lower-case if(islower(word[0])){ int c = 0; for(int i=0; i<n; i++){ if(islower(word[i])){ c++; ...
var detectCapitalUse = function(word) { if((word.charAt(0)==word.charAt(0).toUpperCase() && word.slice(1)==word.slice(1).toLowerCase()) || (word == word.toUpperCase() || word == word.toLowerCase())) { return true } else{ return false } };
Detect Capital
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle. You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes t...
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1) res = [] for i, ch in enumerate(s): psum[i + 1] = psum[i] + (ch == '|') prev[i + 1] = i if ch...
class Solution { // O(sLen + queries.length) time, O(sLen) space public int[] platesBetweenCandles(String s, int[][] queries) { int sLen = s.length(); // cumulative number of plates from the left int[] numberOfPlates = new int[sLen+1]; for (int i=0; i<sLen; i++) { num...
class Solution { public: vector<int> platesBetweenCandles(string s, vector<vector<int>>& queries) { vector<int> candlesIndex; for(int i=0;i<s.length();i++){ if(s[i] == '|') candlesIndex.push_back(i); } vector<int> ans; for(auto q ...
// time O(N + M) Space O(N) N = s.length M = query.length var platesBetweenCandles = function(s, queries) { let platPreFixSum = [...Array(s.length + 1)]; let leftViewCandle = [...Array(s.length + 1)]; let rightViewCandle = [...Array(s.length + 1)]; platPreFixSum[0] = 0; leftViewCandle[0] = -1; ...
Plates Between Candles
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another". Given a dictionary consisting of many roots and a sentence consi...
class Solution { public: class trii{ public: char data; trii* dict[26]; bool isTerminal; trii(){ } trii(char d){ data=d; for(int i=0;i<26;i++){ dict[i]=NULL; } isTerm...
class Solution { public: class trii{ public: char data; trii* dict[26]; bool isTerminal; trii(){ } trii(char d){ data=d; for(int i=0;i<26;i++){ dict[i]=NULL; } isTerm...
class Solution { public: class trii{ public: char data; trii* dict[26]; bool isTerminal; trii(){ } trii(char d){ data=d; for(int i=0;i<26;i++){ dict[i]=NULL; } isTerm...
class Solution { public: class trii{ public: char data; trii* dict[26]; bool isTerminal; trii(){ } trii(char d){ data=d; for(int i=0;i<26;i++){ dict[i]=NULL; } isTerm...
Replace Words
In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You a...
class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: possible = set([i for i in range(1,n+1)]) in_edges = [0] * (n+1) for first, second in trust: possible.discard(first) in_edges[second] += 1 if len(possible) != 1: ...
class Solution { public int findJudge(int n, int[][] trust) { int count=0; int x[]=new int[n+1]; int y[]=new int[n+1]; Arrays.fill(x, 0); Arrays.fill(y, 0); for(int i=0;i<trust.length;i++) { x[trust[i][0]]=1; } for(int i=1;i<=n;i+...
class Solution { public: int findJudge(int n, vector<vector<int>>& trust) { vector<pair<int,int>> v(n+1,{0,0}); for(auto i : trust){ v[i[0]].first++; v[i[1]].second++; } int ans = -1; for(int i=1;i<=n;i++){ auto ...
var findJudge = function(n, trust) { const length = trust.length; let possibleJudge = [], judgeMap = new Map(), value, judge = -1; for(let i = 0; i < length; i++) { if(judgeMap.has(trust[i][0])){ value = judgeMap.get(trust[i][0]); value.push(trust[i][1]); judgeMap...
Find the Town Judge
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s. &nbsp; Example 1: Input: str1 = ...
class Solution: def shortestCommonSupersequence(self, A, B): n, m = len(A), len(B) dp = [B[:i] for i in range(m + 1)] for i in range(n): prev = A[:i] dp[0] = A[:i + 1] for j in range(m): if A[i] == B[j]: prev, dp[j + 1] ...
class Solution { public String shortestCommonSupersequence(String str1, String str2) { int m=str1.length(); int n=str2.length(); int[][] dp=new int[m+1][n+1]; for(int i=1;i<m+1;i++){ for(int j=1;j<n+1;j++){ if(str1.charAt(i-1)==str2.charAt(j-1)){ ...
class Solution { string LCS(string str1, string str2, int m, int n) { int t[m+1][n+1]; string ans = ""; for(int i = 0;i < m+1; ++i) { for(int j = 0; j< n+1; ++j) { if(i == 0 || j == 0) t[i][j] = 0; } ...
var shortestCommonSupersequence = function(str1, str2) { const lcs = getLCS(str1, str2) let i = 0 let j = 0 let result = '' for (const c of lcs) { while(i < str1.length && str1[i] !== c) { result += str1[i] i++ } while(j < str2.length && str2[j] ...
Shortest Common Supersequence
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train ca...
class Solution: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: # the speed upper is either the longest train ride: max(dist), # or the last train ride divide by 0.01: ceil(dist[-1] / 0.01). # notice: "hour will have at most two digits after the decimal point" upper = ...
class Solution { public int minSpeedOnTime(int[] dist, double hour) { int left = 1; int right = (int) 1e8; while (left < right) { int middle = (left + right) / 2; if (arriveOnTime(dist, hour, middle)) right = middle; else left = middle + 1...
class Solution { bool canReachInTime(const vector<int>& dist, const double hour, int speed) { double time = 0; for (int i = 0; i < dist.size() - 1; ++i) time += ((dist[i] + speed - 1) / speed); time += ((double)dist.back()) / speed; return time <= hour; } public...
var minSpeedOnTime = function(dist, hour) { let left=1,right=10000000,speed,sum,ans=-1; while(left<=right){ //We need to return the minimum positive integer speed (in kilometers per hour) that all the trains must travel. So speed will always be an integer ranging from 1 to 10000000 as per the question d...
Minimum Speed to Arrive on Time
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's&nbsp;such that&nbsp;j != i and nums[j] &lt; nums[i]. Return the answer in an array. &nbsp; Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Ex...
class Solution: def smallerNumbersThanCurrent(self, nums): sortify = sorted(nums) return (bisect_left(sortify, i) for i in nums)
class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { int[] sorted = nums.clone(); int[] res = new int[nums.length];//result array Arrays.sort(sorted); for (int i = 0; i < nums.length; ++i) { //binary search it, if there is no duplicates the idx will be ho...
class Solution { public: vector<int> smallerNumbersThanCurrent(vector<int>& nums) { vector<int> ans; int i,j,size,count; size = nums.size(); for(i = 0; i<size; i++){ count = 0; for(j = 0;j<size;j++){ if(nums[j]<nums[i]) count++; } ...
var smallerNumbersThanCurrent = function(nums) { let count, ans=[]; /*Run a loop on each element excluding nums[i] and compare it with nums[j] if it's large, then count++ else break;*/ for(let i=0; i<nums.length; i++){ let temp=nums[i], count=0; for(let j=0; j<nums.length; j++){...
How Many Numbers Are Smaller Than the Current Number
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16. Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums...
class Solution: def maxProductDifference(self, nums: List[int]) -> int: max_1 = 0 max_2 = 0 min_1 = 10001 min_2 = 10001 for i in nums: if i >= max_1: max_2,max_1 = max_1,i elif i > max_2: max_2 = i if i <= mi...
class Solution { public int maxProductDifference(int[] nums) { int max1 = Integer.MIN_VALUE; int max2 = max1; int min1 = Integer.MAX_VALUE; int min2 = min1; for (int i = 0; i < nums.length; i++) { if (max1 < nums[i]) { max2 = max1; ...
class Solution { public: int maxProductDifference(vector<int>& nums) { //we have to return the result of // (firstMax*secondMax) - (firstMin*secondMin) int max1=INT_MIN; int max2=INT_MIN; int min1=INT_MAX; int min2=INT_MAX; for(int i=0;i<nums.size();i++) ...
var maxProductDifference = function(nums) { nums.sort((a,b) => a-b); return nums.slice(nums.length - 2).reduce((a,b) => a*b, 1) - nums.slice(0, 2).reduce((a,b) => a*b, 1); };
Maximum Product Difference Between Two Pairs
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return None slow = fast = entry = he...
public class Solution { public ListNode detectCycle(ListNode head) { if (head == null) return null; ListNode tortoise = head; ListNode hare = new ListNode(); hare.next = head.next; while (hare != null && hare.next != null && hare != tortoise) { tortoise = tortoise...
class Solution { public: ListNode *detectCycle(ListNode *head) { map<ListNode*, int> m; int index = 0; while (head) { if (m.find(head) == m.end()) m[head] = index; else return (head); head = head->next; ...
var detectCycle = function(head) { let slowRunner = head let fastRunner = head while(fastRunner) { fastRunner = fastRunner.next?.next slowRunner = slowRunner.next if (fastRunner === slowRunner) { fastRunner = slowRunner slowRunner = head while (...
Linked List Cycle II
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target. In one move, you can either: Increment the current integer by one (i.e., x = x + 1). Double the current integer (i.e., x = 2 * x). You can use the increment operation any number of times, however, you can...
class Solution: def minMoves(self, target: int, maxDoubles: int) -> int: c=0 while(maxDoubles>0 and target>1): c += target%2 target //= 2 c += 1 maxDoubles -=1 return c + target-1
class Solution { public int minMoves(int target, int maxDoubles) { int ans = 0; for(int i=0;i<maxDoubles;i++){ if(target==1)break; if(target%2==0){ ans+=1; target=(target)/2; }else{ ans+=2; ...
class Solution { public: int minMoves(int target, int maxDoubles) { int cnt = 0; while(target>1 && maxDoubles>0){ if(target%2==0){ cnt++; maxDoubles--; target = target/2; } else{ cnt++; ...
var minMoves = function(target, maxDoubles) { if (maxDoubles === 0) return target - 1; let count = 0; while (target > 1) { if (target % 2 === 0 && maxDoubles > 0) { target /= 2; maxDoubles--; } else { target--; } count++; } retur...
Minimum Moves to Reach Target Score
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. You can only ch...
from collections import deque from math import log2, ceil class Solution: def minDays(self, n: int) -> int: maxd = 2*ceil(log2(n)) que = deque([(1,1)]) seen = set() while que: v, d = que.popleft() seen.add(v) if v == n: return d ...
class Solution { HashMap<Integer,Integer>map; public int minDays(int n) { map = new HashMap<>(); map.put(0,0); map.put(1,1); return dp(n); } public int dp(int n){ if(map.get(n)!=null) return map.get(n); int one = 1+(n%2)+dp(n/2); int ...
class Solution { public: // approach: BFS int minDays(int n) { int cnt=0; queue<int>q; q.push(n); unordered_set<int>s; s.insert(n); while(!q.empty()){ int l=q.size(); while(l--){ int a=q.front(); q.pop(); ...
var minDays = function(n) { const queue = [ [n,0] ]; const visited = new Set(); while (queue.length > 0) { const [ orangesLeft, days ] = queue.shift(); if (visited.has(orangesLeft)) continue; if (orangesLeft === 0) return days; visited.add(orangesLeft);...
Minimum Number of Days to Eat N Oranges
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. &nbsp; Example 1: Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this resu...
class Solution: def largestInteger(self, num: int): n = len(str(num)) arr = [int(i) for i in str(num)] odd, even = [], [] for i in arr: if i % 2 == 0: even.append(i) else: odd.append(i) odd.sort() even.sort() ...
class Solution { public int largestInteger(int num) { PriorityQueue<Integer> opq = new PriorityQueue<>(); PriorityQueue<Integer> epq = new PriorityQueue<>(); int bnum = num; while(num>0){ int cur = num%10; if(cur%2==1){ opq.add(cur); ...
class Solution { public: int largestInteger(int num) { priority_queue<int> p; // priority queue to store odd digits in descending order priority_queue<int> q; // priority queue to store even digits in descending order string nums=to_string(num); // converting num to a string for easy access ...
/** * @param {number} num * @return {number} */ var largestInteger = function(num) { var nums = num.toString().split("");//splitting the numbers into an array var odd=[];//helps keep a track of odd numbers var even =[];//helps keep a track of even numbers for(var i=0;i<nums.length;i++){ if(nu...
Largest Number After Digit Swaps by Parity
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may ret...
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: # create a r, c matrix given the rows & cols # each element represents a list [r, c] where r is the row & c the col # find find the distances of all cells from the center (append...
//--------------------Method 1---------------------- class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { int [][]res=new int[rows*cols][2]; int idx=0; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ res[idx][0]=i...
class Solution { public: vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { vector<vector<int>> ans; multimap<int,vector<int>> mp; for(int i = 0;i<rows;i++){ for(int j = 0;j<cols;j++){ mp.insert(pair<int,vector<int>>(abs(i-rC...
var allCellsDistOrder = function(rows, cols, rCenter, cCenter) { let distances = [] let result = [] //create a new "visited" cells matrix let visited = new Array(rows).fill([]) for(i=0;i<visited.length;i++){ visited[i] = new Array(cols).fill(0) } const computeDistances = (row, col,...
Matrix Cells in Distance Order
You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'. In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example, if stamp = "abc" and target = "abcba", then s is "?????" initially...
class Solution: def movesToStamp(self, S: str, T: str) -> List[int]: if S == T: return [0] S, T = list(S), list(T) slen, tlen = len(S), len(T) - len(S) + 1 ans, tdiff, sdiff = [], True, True while tdiff: tdiff = False for i in range(tlen): ...
class Solution { public int[] movesToStamp(String stamp, String target) { /* * Intitution: * Instead of creating target string from intial state, * create the intial state from the target string. * - take a window of stamp length * - reverse that window to th...
class Solution { public: vector<int> movesToStamp(string stamp, string target) { auto isUndone = [](auto it, auto endIt) { return all_of(it, endIt, [](char c) { return c == '?'; }); }; vector<int> res; while (!isUndone(begin(target), end(target))) { auto prev...
var movesToStamp = function(stamp, target) { var s = target.replace(/[a-z]/g,"?") var repl = s.substr(0,stamp.length) let op = [] let s1 = target while(s1 !== s){ let idx = getIndex() if(idx === -1) return [] op.push(idx) } return op.reverse() function getIn...
Stamping The Sequence
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules: Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; k &lt; nums2.length. Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j]...
class Solution: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: sqr1, sqr2 = defaultdict(int), defaultdict(int) m, n = len(nums1), len(nums2) for i in range(m): sqr1[nums1[i]**2] += 1 for j in range(n): sqr2[nums2[j]**2] += 1 res = 0...
class Solution { public int numTriplets(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); return count(nums1 , nums2) + count(nums2 , nums1); } public int count(int a[] , int b[]){ int n = a.length; int m = b.length; int count = 0; f...
class Solution { public: int numTriplets(vector<int>& nums1, vector<int>& nums2) { unordered_map<long, int> m1, m2; for(int i : nums1) m1[(long long)i*i]++; for(int i : nums2) m2[(long long)i*i]++; int ans = 0; for(int i=0; i<nums2.size()-1; i++){ for(int j=i+1...
var numTriplets = function(nums1, nums2) { const nm1 = new Map(), nm2 = new Map(); const n = nums1.length, m = nums2.length; for(let i = 0; i < n; i++) { for(let j = i + 1; j < n; j++) { const product = nums1[i] * nums1[j]; if(!nm1.has(product)) nm1.set(product, 0); ...
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. &nbsp; Example 1: Input: n = 12, k = 3 Output: 3 Explanation:...
class Solution: def kthFactor(self, n: int, k: int) -> int: start=[1] end=[n] for i in range(2,math.ceil(math.sqrt(n))+1): if n%i==0: start.append(i) if i!=n//i: end.append(n//i) start=sorted(set(start).union(set(end))) ...
class Solution { public int kthFactor(int n, int k) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (n % i == 0){ list.add(i); } } if (list.size() < k){ return -1; } return lis...
class Solution { public: int kthFactor(int n, int k) { vector<int> sol; sol.push_back(1); for(int i = 2; i <= n / 2; i++) { if(n % i == 0) sol.push_back(i); } if(n != 1) sol.push_back(n); if(k > sol.size()) return -1; return sol[k - 1]; } };
/** * @param {number} n * @param {number} k * @return {number} */ var kthFactor = function(n, k) { const res = [1] for(let i=2; i<n; i++){ if(n%i === 0){ res.push(i) } } res.push(n) return res[k-1] || -1 };
The kth Factor of n
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise. The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y). &nbsp; Example 1: Input: sx = 1, sy = 1, tx = 3, ty = ...
from collections import defaultdict class Solution: def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: def nextNum(ta,tb,s): if ta % tb == s % tb: return min(ta, s) return ta % tb visited = defaultdict(bool) while tx >= sx and ty >=...
class Solution { public boolean reachingPoints(int sx, int sy, int tx, int ty) { if (sx==tx && sy==ty){ return true; } if (tx < sx || ty < sy){ return false; } return tx<ty? reachingPoints(sx, sy, tx, Math.min(ty%tx+sy/tx*tx,ty-tx)) ...
/* Explanation: Let's say at some point we have coordinates as (a,b) if(a>b) then at the previous step coordinate must be (a-b,b) as it can't be (a,b-a) because all the coordinates are positive and for a>b... b-a<0 this continues till the point when a becomes <=b we can run a loop till there but its time taking we can...
/** * @param {number} sx * @param {number} sy * @param {number} tx * @param {number} ty * @return {boolean} */ var reachingPoints = function(sx, sy, tx, ty) { while (tx >= sx && ty >= sy) { if (tx == ty) break; if (tx > ty) { if (ty > sy) tx %= ty; else return ...
Reaching Points
You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). &nbsp; Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6...
class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: tot = 0 # initialise total Head = head while Head: # count total nodes Head = Head.next # move forward tot += 1 # incerse count by one for each node one, two = None, N...
class Solution { public ListNode swapNodes(ListNode head, int k) { ListNode fast = head; ListNode slow = head; ListNode first = head, second = head; // Put fast (k-1) nodes after slow for(int i = 0; i < k - 1; ++i) fast = fast.next; // Save the node for ...
class Solution { public: ListNode* swapNodes(ListNode* head, int k) { // declare a dummy node ListNode* dummy = new ListNode(0); // point dummy -> next to head dummy -> next = head; // declare a tail pointer and point to dummy ...
var swapNodes = function(head, k) { let A = head, B = head, K, temp for (let i = 1; i < k; i++) A = A.next K = A, A = A.next while (A) A = A.next, B = B.next temp = K.val, K.val = B.val, B.val = temp return head };
Swapping Nodes in a Linked List
You are given a 0-indexed integer array nums whose length is a power of 2. Apply the following algorithm on nums: Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2. For every even index i where 0 &lt;= i &lt; n / 2, assign the value of ...
class Solution: def minMaxGame(self, a: List[int]) -> int: def solve(n): if n==1: return for i in range(n//2): if i%2: a[i] = max (a[2*i], a[2*i+1]) else: a[i] = min (a[2*i], a[2*i+1]) ...
class Solution { public int minMaxGame(int[] nums) { var isMin = true; var n=1; while(n<nums.length) { for(int i=0; i<nums.length; i+= n*2) { nums[i] = isMin ? Math.min(nums[i], nums[i+n]) : Math.max(n...
class Solution { public: int minMaxGame(vector<int>& nums) { int n = nums.size(); if(n==1) return nums[0]; // Base case vector<int> newNum(n/2); for(int i=0; i<n/2; i++) { if(i%2==0) newNum[i] = min(nums[2 * i], nums[2 * i + 1]); else newNum[i] = max(nums...
var minMaxGame = function(nums) { while (nums.length > 1) { let half = nums.length / 2; for (let i = 0; i < half; i++) nums[i] = i % 2 === 0 ? Math.min(nums[2 * i], nums[2 * i + 1]) : Math.max(nums[2 * i], nums[2 * i + 1]); nums.length = half; } return nums[0]; };
Min Max Game
The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 &lt;= i &lt; j &lt; nums.length. &nbsp; Example 1: Input: nums = [1,3,1], k = 1 Output: 0 Ex...
from heapq import heappush, heappop, heapify class Solution: def smallestDistancePair(self, nums: List[int], k: int) -> int: # pairs = list(combinations(nums, 2)) maxHeap = [] heapify(maxHeap) for idx, val1 in enumerate(nums): for val2 in nums[idx + 1:]:...
class Solution { public int smallestDistancePair(int[] nums, int k) { Arrays.sort(nums); int low = 0, high = nums[nums.length-1] - nums[0]; while(low<=high){ int mid = low + (high-low)/2; if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1; el...
class Solution { public: int count(vector<int> &temp,int mid){ int i=0,j=0,n=temp.size(); int len=0; while(i<n){ while(j<n && (temp[j]-temp[i])<=mid) j++; len+=j-i-1; i++; } return len; } int smallestDistancePair(vector<int>& nums,...
var smallestDistancePair = function(nums, k) { nums.sort((a,b) => a - b); let left = 0, right = nums[nums.length-1] - nums[0], mid = null, total = 0; while (left < right) { mid = left + Math.floor((right - left) / 2); total = 0; for (var i = 0, j = 1; i < nums.le...
Find K-th Smallest Pair Distance
A Bitset is a data structure that compactly stores bits. Implement the Bitset class: Bitset(int size) Initializes the Bitset with size bits, all of which are 0. void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs. void unfix(int idx) Updates the value...
class Bitset(object): def __init__(self, size): self.a = 0 self.size = size self.cnt = 0 def fix(self, idx): if self.a & (1 << idx) == 0: self.a |= 1 << idx self.cnt += 1 def unfix(self, idx): if self.a & (1 << idx): self.a ^= 1 ...
class Bitset { int size; Set<Integer> one = new HashSet<>(); Set<Integer> zero = new HashSet<>(); public Bitset(int size) { this.size = size; for(int i=0;i<size;i++) zero.add(i); } public void fix(int idx) { one.add(idx); zero.remove(idx); } publ...
class Bitset { public: vector<int>arr; int cnt,cntflip; Bitset(int size) { arr.resize(size,0); cnt=0,cntflip=0; } void fix(int idx) { // means current bit is 0 ,so set it to 1 if((arr[idx]+cntflip)%2==0){ arr[idx]++; cnt++; } } void un...
var Bitset = function(size) { //this.bits = new Array(size).fill(0); //this.bitsOp = new Array(size).fill(1); this.set0 = new Set(); this.set1 = new Set(); for (let i = 0; i<size; i++) this.set0.add(i); }; /** * @param {number} idx * @return {void} */ Bitset.prototype.fix = function(idx) { //...
Design Bitset
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied: t is a subsequence of the string s. The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k. Return the length of the l...
class Solution: def longestIdealString(self, s: str, k: int) -> int: DP = [0 for _ in range(26)] ans = 1 for ch in s: i = ord(ch) - ord('a') DP[i] = DP[i] + 1 for j in range(max(0, i - k), min(25, i + k) + 1): if j != ...
class Solution { public int longestIdealString(String s, int k) { int DP[] = new int[26], ans = 1; for (int ch = 0, n = s.length(); ch < n; ch++) { int i = s.charAt(ch) - 'a'; DP[i] = DP[i] + 1; for (int j = Math.max(0, i - k); j <= Math.min(25, i + k); j++) ...
class Solution { public: int longestIdealString(string s, int k) { int DP[26] = {0}, ans = 1; for (char &ch: s) { int i = ch - 'a'; DP[i] = DP[i] + 1; for (int j = max(0, i - k); j <= min(25, i + k); j++) if (j != i) DP[i] = m...
var longestIdealString = function(s, k) { let n = s.length let dp = Array(26).fill(0); let ans = 0; for(let i=0; i<n; i++){ const cur = s.charCodeAt(i)-97; dp[cur] += 1; for(let j=Math.max(0, cur-k); j<=Math.min(cur+k, 25); j++){ if(j !== cur){ dp[cur]...
Longest Ideal Subsequence
Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the&nbsp;next&nbsp;pointer. Internally, pos&nbsp;is used to denote the index of the node that&nbsp;tail's&nbsp;n...
class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: for i in range(0, 10001): if head == None: return False head = head.next return True
public class Solution { public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; boolean result = false; while(fast!=null && fast.next!=null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ ...
class Solution { public: bool hasCycle(ListNode *head) { // if head is NULL then return false; if(head == NULL) return false; // making two pointers fast and slow and assignning them to head ListNode *fast = head; ListNode *slow = head; // till fast and ...
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {boolean} */ function hasCycle(head){ let fast = head; while (fast && fast.next) { head = head.next; fast = fast.next.next; if (h...
Linked List Cycle
Given a binary tree with the following rules: root.val == 0 If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1 If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2 Now the binary tree is contaminated, which means all treeNode.val have been changed...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class FindElements: def __init__(self, root: Optional[TreeNode]): def recoverTree(root): if not root: return None ...
class FindElements { TreeNode tree,nodept; public FindElements(TreeNode root) { tree=root; tree.val=0; go(tree); } void go(TreeNode node){ if(node.left!=null){ node.left.val=node.val*2+1; go(node.left); } if(node.right!=null){ ...
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l...
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var FindElements = function(root) { this.st = new...
Find Elements in a Contaminated Binary Tree
Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: LFUCache(int capacity) Initializes the object with the capacity of the data structure. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1. void put(int key, in...
class Node: def __init__(self, key, val, cnt=1, nxxt=None, prev=None): self.key = key self.val = val self.cnt = cnt self.nxxt = nxxt self.prev = prev class NodeList(Node): def __init__(self): self.head = Node(0,0) self.tail = No...
class LFUCache { // Declare Node class for Doubly Linked List class Node{ int key,value,freq;// to store key,value and frequency Node prev,next;// Next and Previous Pointers Node(int k,int v){ // initializing in constructor key=k; value=v; fr...
class list_node { public: int key, val, cnt; list_node* next; list_node* prev; list_node(int k, int v, list_node* n, list_node* p) { key = k; val = v; cnt = 1; next = n; prev = p; } }; class LFUCache { public: int min_cnt; bool zero; unordered_map<int, list_node*> key2nod...
/** * @param {number} capacity */ var LFUCache = function(capacity) { this.capacity = capacity; this.cache = []; }; /** * @param {number} key * @return {number} */ LFUCache.prototype.get = function(key) { let val = -1; if (!this.capacity) return val; const existIndex = this.cache.findIndex(it...
LFU Cache
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". &nbsp; Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix...
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: cmp=strs[0] for i in range(1,len(strs)): l=0 if (len(cmp)>len(strs[i])): l+=len(strs[i]) else: l+=len(cmp) ans="" for j in range(l): ...
class TrieNode{ TrieNode[] childs; int frequency; TrieNode(){ childs = new TrieNode[26]; this.frequency = 1; } } class Solution { TrieNode root = new TrieNode(); public String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; if(strs.length =...
class Solution { public: string longestCommonPrefix(vector<string>& strs) { //brute string ans=""; string ref=strs[0]; for(int i=0;i<ref.size();i++) { int j=1; for(;j<strs.size();j++) { if(ref[i]!=strs[j][i]) ...
var longestCommonPrefix = function(strs) { let commonStr=strs[0]; for(let i=1; i<strs.length;i++){ let currentStr= strs[i] for(let j=0; j<commonStr.length;j++){ if (commonStr[j]!==currentStr[j]){ commonStr=currentStr.slice(0,j) break; } } } return commonStr
Longest Common Prefix
You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the nu...
class RecentCounter: # Here we use list to store ping details. def __init__(self): self.store = [] def ping(self, t: int) -> int: # Basically what we need to return is how many pings fall in the range(t-3000, t). # So here we append every t. Now in loop how many t from left side < t...
class RecentCounter { ArrayList<Integer> calls ; public RecentCounter() { calls = new ArrayList<Integer>(); } public int ping(int t) { calls.add(t); int count = 0; for(Integer call:calls){ if( t-call<=3000) count++; } return count; ...
class RecentCounter { public: queue<int> q; RecentCounter() { } int ping(int t) { q.push(t); int x = q.front(); while(x < t-3000){ q.pop(); x = q.front(); } return q.size(); } };
var RecentCounter = function() { this.arr = []; }; RecentCounter.prototype.ping = function(t) { this.arr.push(t); while(t > this.arr[0]+3000){ this.arr.shift(); } return this.arr.length; };
Number of Recent Calls
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. F...
class Solution: def countSubstrings(self, s: str, t: str) -> int: res = 0 for i in range(len(s)): for j in range(len(t)): miss, pos = 0, 0 while i + pos < len(s) and j + pos < len(t) and miss < 2: miss += s[i + pos] != t[j + pos] ...
// version 1 : O(mn) space class Solution { public int countSubstrings(String s, String t) { int m = s.length(), n = t.length(); int[][][] dp = new int[m][n][2]; int res = 0; // first col s[0:i] match t[0:0] for (int i = 0; i < m; i++) { dp[i][0][0] = (s...
class Solution { public: int countSubstrings(string s, string t) { int n=s.size(); int m=t.size(); int ans=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int diff=0; for(int k=0;i+k<n&&j+k<m;k++) { ...
var countSubstrings = function(s, t) { const count1 = countAllSubstr(s); const count2 = countAllSubstr(t); let res = 0; for (const [substr1, freq1] of count1) { for (const [substr2, freq2] of count2) { if (differByOneChar(substr1, substr2)) { res += freq1 * freq2; ...
Count Substrings That Differ by One Character
Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need o...
class Node: def __init__(self, val: int): self.val = val self.next = None self.prev = None class MyLinkedList: def __init__(self): self.head = Node(0) self.tail = Node(0) self.head.next = self.tail self.tail.prev = self.head self.size = 0 ...
class MyLinkedList { public class ListNode { public int val; public ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next =...
class MyLinkedList { struct Node{ int val; Node *next,*prev; Node(int x){val=x,next=prev=NULL;} }; Node *head;int size; public: MyLinkedList() { head=NULL;size=0; } int get(int index) { if(index>=size or index<0) return -1; Node *ptr=head; ...
var MyLinkedList = function() { this.linked = []; }; MyLinkedList.prototype.get = function(index) { if(index < this.linked.length){ return this.linked[index]; } return -1; }; MyLinkedList.prototype.addAtHead = function(val) { this.linked.unshift(val); }; MyLinkedList.prototype.addAtTail =...
Design Linked List
Given an integer array nums, handle multiple queries of the following types: Update the value of an element in nums. 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 inte...
class NumArray: nums = [] s = 0 l = 0 def __init__(self, nums: List[int]): self.nums = nums self.s = sum(nums) self.l = len(nums) def update(self, index: int, val: int) -> None: self.s -= self.nums[index] self.nums[index] = val self.s += self.num...
class NumArray { SegmentTree s; public NumArray(int[] nums) { s = new SegmentTree(nums); s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built } public void update(int index, int val) { int oldvalue = s.arr[index];//Find old value with tradition...
class NumArray { public: vector<int>v; //vector to store input vector. int sum; //sum of all element of vector NumArray(vector<int>& nums) { v=nums; sum=0; for(int i=0;i<nums.size();i++){ sum+=nums[i]; } } void update(int index, int val) { su...
var NumArray = function(nums) { this.nums = nums; this.n = nums.length; this.fenwickTree = new Array(this.n + 1).fill(0); nums.forEach((num, index) => this.init(index, num)); }; NumArray.prototype.init = function(index, val) { let j = index + 1; while(j <= this.n) { this.fenwickTree[j] ...
Range Sum Query - Mutable
You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target&nbsp;or false otherwise. &nbsp; Example 1: Input: target = [1,2,3,4], arr = [2,4,1,3...
class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: target.sort() arr.sort() if len(target)==len(arr): if target==arr: return True else: return False
class Solution { public boolean canBeEqual(int[] target, int[] arr) { HashMap<Integer,Integer>hm1=new HashMap(); for(int i: arr){ if(hm1.containsKey(i)) hm1.put(i,hm1.get(i)+1); else hm1.put(i,1); } for(int i: target){ ...
class Solution { public: bool canBeEqual(vector<int>& target, vector<int>& arr) { int arr1[1001]={0}; int arr2[1001]={0}; for(int i =0 ; i<target.size(); i++) { arr1[arr[i]]++; arr2[target[i]]++; } for(int i =0 ;i<=1000;i++) ...
var canBeEqual = function(target, arr) { if(arr.length==1){ if(arr[0]===target[0]){ return true } } let obj = {} for(let i =0;i<arr.length; i ++){ if(obj[arr[i]]==undefined){ obj[arr[i]]=1 }else{ obj[arr[i]]++ } } for(le...
Make Two Arrays Equal by Reversing Sub-arrays
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 &lt;= j &lt; i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the...
class Solution: def solve(self, nums, index, d): if index == len(nums) or d == 1: #print(max(nums[index:])) return max(nums[index:]) ans = float("inf") for i in range(index, len(nums)-d+1): curr = max(nums[index:i+1]) + self.solve(nums, i+1, d-1) ...
class Solution { // Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray. public int minDifficulty(int[] jobDifficulty, int d) { if(d>jobDifficulty.length){ return -1; } int[][] memo = new int[d+1][jobDifficulty.length]...
class Solution { vector<int> v; int len; int dp[301][11]; int dfs(int idx, int d){//n*d if(idx>=len) return 0; if(d==1) return *max_element(v.begin()+idx,v.end()); if(dp[idx][d]!=-1) return dp[idx][d]; int maxx=INT_MIN; int res=...
var minDifficulty = function(jobDifficulty, d) { // don't have enought jobs to distribute if (jobDifficulty.length < d) { return -1; } // in dynamic programming top-down approach // we need to have memoisation to not repeat calculations let memo = new Array(d+1).fill(-1).map( ()...
Minimum Difficulty of a Job Schedule
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e.,&nbsp;0-indexed). You can ...
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: di = (0, 1, 0, -1) dj = (1, 0, -1, 0) m, n = len(heights), len(heights[0]) visited = [[False] * n for _ in range(m)] h = [(0, 0, 0)] while h: effort, i, j = heappop(h) ...
class Tuple { int distance; int row; int col; Tuple(int distance, int row, int col) { this.distance = distance; this.row = row; this.col = col; } } class Solution { public int minimumEffortPath(int[][] heights) { // Create a min heap based on t...
#define pii pair<int, pair<int,int>> class Solution { public: //Directions (top, right, bottom, left) const int d4x[4] = {-1,0,1,0}, d4y[4] = {0,1,0,-1}; int minimumEffortPath(vector<vector<int>>& h) { int n = h.size(), m = h[0].size(); //min-heap priority_queue <pii, vector<pi...
/** * @param {number[][]} heights * @return {number} * T: O((M*N)log(M*N)) * S: O(M*N) */ var minimumEffortPath = function(heights) { const directions = [ [1, 0], [0, 1], [-1, 0], [0, -1], ]; const row = heights.length; const col = heights[0].length; const differ...
Path With Minimum Effort
Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. &nbsp; Example 1: Input: nums = [1,2,0] Output: 3 Explanation: The numbers in the range [1,2] are all in the array. Example 2: Input: nums = [3,...
class Solution: def firstMissingPositive(self, nums: List[int]) -> int: mn = float('inf') mx = 0 numsSet = set() for i in range(len(nums) - 1, -1, -1): if nums[i] > 0: if nums[i] < mn: mn = nums[i] if nums[i] > mx: ...
class Solution { public int firstMissingPositive(int[] nums) { //cyclic sort int i = 0; while (i<nums.length){ int correct = nums[i]-1; if(nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[correct]){ swap(nums,i,correct); }else{ ...
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for(int i=0; i<n; i++){ if(nums[i]==i+1 || nums[i]<=0 || nums[i]>n) continue; while(nums[i]!=i+1 && nums[i]>0 && nums[i]<=n && nums[nums[i]-1] != nums[i]){ swap(nums[i]...
/** * @param {number[]} nums * @return {number} */ var firstMissingPositive = function (nums) { //first make all negative numbers to zero =>zero means we ignore whis number for (let index = 0; index < nums.length; index++) { if (nums[index] < 0) nums[index] = 0 } for (let index ...
First Missing Positive
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 &lt; x &lt; n and n % x == 0. Replacing the number n on the chalkboard with n - x. Also, if a player cannot ma...
class Solution: def divisorGame(self, n: int) -> bool: """ let's forget about Alice and Bob for a second and just concentrate on the n and plays if played optimally : 1 - player at 1 will loose since no factors 2 - player at 2 will win by choosing 1 ...
class Solution { public boolean divisorGame(int n) { return n%2==0; } }
class Solution { public: bool divisorGame(int n) { if(n%2==0) return true; return false; } };
var divisorGame = function(n) { let count = 0; while(true){ let flag = true; for(let i = 1;i<n;i++){ if(n%i==0){ flag = false; n = n-i; break; } } if(flag){ if(count %2==0) return false; else return true; } count++; } };
Divisor Game
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Choose 2 distinct names from ideas, call them ideaA and ideaB. Swap the first letters of ideaA and ideaB with each other. If both of the new names ar...
class Solution: def distinctNames(self, ideas: List[str]) -> int: names=defaultdict(set) res=0 #to store first letter as key and followed suffix as val for i in ideas: names[i[0]].add(i[1:]) #list of distinct first-letters availabl...
class Solution { public long distinctNames(String[] ideas) { // HashSet + String Manipulation; TC: O(26*26*n); SC: O(26*n) HashSet<String> [] arr = new HashSet[26]; for(int i=0; i<26; i++) { arr[i] = new HashSet<>(); } for(String s: ideas) { arr[s.char...
class Solution { public: long long distinctNames(vector<string>& ideas) { unordered_map <char,unordered_set<string>> mp; for(auto u : ideas) mp[u[0]].insert(u.substr(1,u.size()-1)); long long ans = 0; for(int i = 0; i<26; i++){ for(int j = i+1; j<26; j++...
/** * @param {string[]} ideas * @return {number} */ var distinctNames = function(ideas) { let res = 0; let lMap = new Map(); for(let i=0; i<ideas.length; i++){ let idea = ideas[i]; // extract first letter let l = idea[0].charCodeAt() - 97; // extract substring let...
Naming a Company
You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. &nbsp; Example 1: Input: s = "ilovecodingonleetcode", target = "code" Output: 2 Ex...
class Solution: def rearrangeCharacters(self, s: str, target: str) -> int: counter_s = Counter(s) return min(counter_s[c] // count for c,count in Counter(target).items())
class Solution { public int rearrangeCharacters(String s, String target) { int[] freq = new int[26], freq2 = new int[26]; for(char ch : s.toCharArray()) freq[ch-'a']++; for(char ch : target.toCharArray()) freq2[ch-'a']++; int min = Integer.MAX_VALUE; ...
Approach : => Take two map, one to store frequency of target, and another for sentence. => Traverse over the mp(frequency of target ) and calculate the minimum frequency ratio mn = min(mn , frequency of a char in sentance / frequency of same char in target) ; ...
/** * @param {string} s * @param {string} target * @return {number} */ var rearrangeCharacters = function(s, target) { let cnt = Number.MAX_VALUE; let m1 = new Map(); for(const x of target) m1.set(x , m1.get(x)+1 || 1); let m2 = new Map(); for(const x of s) m2.set(x , m2.get(x)+1 || 1); f...
Rearrange Characters to Make Target String
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. &nbsp; Example 1: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3] &nbsp; Constraints: The number of nodes in the list is in th...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return head cur=head.next ...
class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) { return head; } ListNode result = head; while (result != null) { if (result.next == null) { break; } if (result.val == result.next...
class Solution { public: // Recursive Approach ListNode* deleteDuplicates(ListNode* head){ // base case if(head==NULL || head->next==NULL) return head; // 1-1-2-3-3 //we are giving next pointer to recursion and telling it to get it done for me ListNode* newNod...
var deleteDuplicates = function(head) { // Special case... if(head == null || head.next == null) return head; // Initialize a pointer curr with the address of head node... let curr = head; // Traverse all element through a while loop if curr node and the next node of curr node are present......
Remove Duplicates from Sorted List
On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The north direction is the positive direction of the y-axis. The south direction is the negative direction of the y-axis. The east direction is the positive direction of the x-axis. The west direction is the negative direction of...
class Solution: def isRobotBounded(self, instructions: str) -> bool: pos, d = [0,0], "N" def move(d, pos, instructions): for i in instructions: if i == "G": if d == "N": pos[1] += 1 elif d == "S": pos[1] -= 1 eli...
class Solution { public boolean isRobotBounded(String instructions) { if (instructions.length() == 0) { return true; } Robot bender = new Robot(); int[] start = new int[]{0, 0}; // 4 represents the max 90 degree turns that can restart initial orientation. ...
class Solution { public: bool isRobotBounded(string instructions) { char direction = 'N'; int x = 0, y = 0; for (char &instruction: instructions) { if (instruction == 'G') { if (direction == 'N') y++; else if (direction == 'S') y--; ...
var isRobotBounded = function(instructions) { // north = 0, east = 1, south = 2, west = 3 let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Initial position is in the center let x = 0, y = 0; // facing north let idx = 0; let movements = [...instructions]; ...
Robot Bounded In Circle
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. &nbsp; Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true &nbsp; Constrain...
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))
class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); int n = nums.length; for (int i = 1; i < n; i++) { if (nums[i] == nums[i - 1]) return true; } return false; } }
class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); for (int i=0; i<n-1; i++){ if (nums[i]==nums[i+1]) return true; } return false; } };
var containsDuplicate = function(nums) { if(nums.length <= 1) return false; let cache = {}; let mid = Math.floor(nums.length /2) let left = mid -1; let right = mid; while(left >= 0 || right < nums.length) { if(nums[left] === nums[right]) { return true; }; if(...
Contains Duplicate
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area c...
class SegmentTree: def __init__(self, xs): #cnts[v] means that the node's interval is active self.cnts = defaultdict(int) #total[v] length of active intervals that are contained the node's interval self.total = defaultdict(int) self.xs = xs def update(self, v, tl, tr, l,...
class Solution { public int rectangleArea(int[][] rectangles) { int n = rectangles.length; Set<Integer> coorx = new HashSet<>(); Set<Integer> coory = new HashSet<>(); for (int[] rec : rectangles) { coorx.add(rec[0]); coorx.add(rec[2]); coory.add(...
struct Point { int X; int delta; }; class Solution { public: int rectangleArea(vector<vector<int>>& rectangles) { map<int, vector<Point>> lines; // y -> array of Points for (auto&r : rectangles) { auto x1 = r[0]; auto y1 = r[1]; auto x2 = r[2]...
var rectangleArea = function(rectangles) { let events = [], active = [], area = 0n; let mod = BigInt(1000000007); for (var rec of rectangles) { events.push([rec[1], 'open', rec[0], rec[2]]); events.push([rec[3], 'close', rec[0], rec[2]]); } events = events.sort((a, b) => a[0] - b[0]); let y = even...
Rectangle Area II
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the no...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxSumBST(self, root: Optional[TreeNode]) -> int: # declaire a variable maxSum to hold the max p...
class Solution { int ans = 0; public int maxSumBST(TreeNode root) { solve(root); return ans; } // int[] = { min, max, sum }; private int[] solve(TreeNode root) { if(root == null) return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 }; int[] left = ...
class Solution { public: int ans = 0 ; array<int,4> solve(TreeNode * root){ if(!root) return {1,0,INT_MIN,INT_MAX} ; array<int,4> l = solve(root->left) ; array<int,4> r = solve(root->right) ; if(l[0] and r[0]){ if(root->val > l[2] and root->val < r[3]){ ...
var maxSumBST = function(root) { let max = 0; const dfs = (node) => { // NoNode if(!node) return [true, 0, Infinity, -Infinity]; // LeafNode if(node && !node.left && !node.right) { max = Math.max(max, node.val); return [true, node.val, node.val, node.val]...
Maximum Sum BST in Binary Tree
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. &nbsp; Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanati...
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() ans = [] i, j = 0, 0 while i < len(nums1) and j < len(nums2): if nums1[i] < nums2[j]: i += 1 elif nums1[i] > nums2[j]: ...
class Solution { public int[] intersection(int[] nums1, int[] nums2) { int[] dp = new int[1000]; for(int i:nums1){ dp[i]++; } int[] ans = new int[1000]; //declaring ptr to track ans array index int ptr = 0; for(int i:nums2){ if(dp[i] !...
class Solution { public: //what i think is we have to return the intersection elements from both nums vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { //result vector which will store those values which will be intersecting in both nums vector<int> result; //map inter...
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function(nums1, nums2) { let set = new Set(nums1); let set2 = new Set(nums2); let result = []; for (const val of set) { if (set2.has(val)) { result.push(val); } } re...
Intersection of Two Arrays
Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a refe...
class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: def DFS(node1,node2): if node1==target: return node2 if node1 and node1.left is None and node1.right is None: return res1 = DFS(no...
class Solution { public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { TreeNode[] ref = new TreeNode[]{null}; dfs(cloned, target, ref); return ref[0]; } public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) { ...
class Solution { public: TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { if(original == target || original == NULL) return cloned; TreeNode* found_left = getTargetCopy(original->left, cloned->left, target); TreeNode* found_right = getTargetCopy(o...
var getTargetCopy = function(original, cloned, target) { if( original == null ){ // Base case aka stop condition // empty tree or empty node return null; } // General cases if( original == target ){ // current original node is target, so is clon...
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. &nbsp; Example 1: Input: salary = [4000,3000,1000,2000] Output: 2500.00000 Ex...
class Solution: def average(self, salary: List[int]) -> float: return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)
class Solution { public double average(int[] salary) { int n = salary.length-2; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int sum = 0; for(int i=0;i<n+2;i++){ sum += salary[i]; max = Math.max(max,salary[i]); min = Math.min(m...
class Solution { public: double average(vector<int>& salary) { int n = salary.size(); double ans=0; sort(salary.begin(),salary.end()); for(int i=1;i<n-1;i++){ ans+=salary[i]; } return ans/(n-2); } };
var average = function(salary) { let max = salary[0], min = salary[salary.length-1], sum = 0; for(let i = 0; i < salary.length; i++) { if(salary[i] > max) { max = salary[i]; } else if(salary[i] < min) { min = salary[i]; } sum += salary[i]; } ...
Average Salary Excluding the Minimum and Maximum Salary
Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square. Here are the rules of Tic-Tac...
class Solution: def validTicTacToe(self, board: List[str]) -> bool: # The two criteria for a valid board are: # 1) num of Xs - num of Os is 0 or 1 # 2) X is not a winner if the # o...
class Solution { public boolean validTicTacToe(String[] board) { //cnt number of X and O int x = cntNumber('X', board); //this check can be omitted, it can be covered in the second number check. if(x >5){ return false; } int o = cntNumber('O', board); ...
class Solution { public: bool win(vector<string> board, char player, int size){ int row_win=0, col_win=0, diagonal_win=0, rev_diagonal_win=0; for(int i=0;i<3;i++){ row_win=0; col_win=0; for(int j=0;j<3;j++){ ...
var validTicTacToe = function(board) { let playerX = 0 , playerO = 0; let horizontal = [0,0,0]; let vertical = [0,0,0]; let diagnol = [0, 0]; const transformConfig=(row,col,val)=>{ horizontal[row] +=val; vertical[col]+=val; if(row ===col ){ diagnol[0]+=val; ...
Valid Tic-Tac-Toe State
There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of the...
class Solution: def canSeePersonsCount(self, heights: List[int]) -> List[int]: ans=[] stack=[] n=len(heights) for i in range(n-1,-1,-1): if len(stack)==0: ans.append(0) stack.append(heights[i]) else: if heights[i...
class Solution { public int[] canSeePersonsCount(int[] heights) { Stack<Integer> stack = new Stack<>(); int result[] = new int[heights.length]; for(int i = heights.length - 1; i >= 0; i--) { int visibility = 0; while(!stack.isEmpty() && heights[i] > stack.peek()) { ...
class Solution { public: vector<int> canSeePersonsCount(vector<int>& h) { vector<int>ans ; stack<int>s ; int a = 0; for(int i = h.size()-1 ; i >= 0 ; i--){ if(s.empty()){ ans.push_back(a); s.push(h[i]);a++; } else{ ...
var visibleToRight = function(heights){ const result = new Array(heights.length).fill(0) const stack = [] let i = heights.length-1 // loop from right to left while(i >= 0){ let popCount = 0 // Keep Popping untill top ele is smaller while(stack.length > 0 && st...
Number of Visible People in a Queue
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] ...
class Solution: def maximumNumber(self, num: str, change: List[int]) -> str: flag=0 ls=list(num) for i in range(len(ls)): k=int(ls[i]) if change[k]>k: ls[i]=str(change[k]) flag=1 elif flag==1 and change[k]<k: break return "".join(ls)
class Solution { public String maximumNumber(String num, int[] change) { int i=0, n=num.length(), startIndex=-1, substringLength=0; // traverse through each digit in the input string while(i<n) { int digit=num.charAt(i)-48; // when we encounter a digit which ...
//change first longest encountered substring from left which can make string greater in value class Solution { public: string maximumNumber(string num, vector<int>& change){ int n=num.size(); for(int i=0;i<n;i++){ int x=num[i]-'0'; if(x < change[x]){//checking whether mutatin...
var maximumNumber = function(num, change) { const digits = num.split(""); let started = false; for (let i = 0; i < digits.length; ++i) { const origDig = digits[i]; const changeDig = change[origDig]; if (changeDig > origDig) { started = true; digits[i] = cha...
Largest Number After Mutating Substring
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below. In the American keyboard: the first row consists of the characters "qwertyuiop", the second row consists of the characters "asdfghjkl", and the third row con...
class Solution: def findWords(self, words: List[str]) -> List[str]: first_row = "qwertyuiopQWERTYUIOP" second_row = "asdfghjklASDFGHIJKL" third_row = "zxcvbnmZXCVBNM" first_list = [] second_list = [] third_list = [] one_line_words = [] for word in wor...
class Solution { public String[] findWords(String[] words) { String row1 = "qwertyuiop"; String row2 = "asdfghjkl"; String row3 = "zxcvbnm"; String res = ""; for(int i=0; i<words.length; i++) { int sum1 = 0; int sum2 = 0; int sum3 = 0; ...
class DSU { vector<int> parent, size; vector<int> Q{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'}; vector<int> A{'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'}; vector<int> Z{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'}; public: ...
var findWords = function(words) { const firstRow = {"q":true,"w":true,"e":true,"r":true,"t":true,"y":true,"u":true,"i":true,"o":true,"p":true } const secondRow = {"a":true,"s":true,"d":true,"f":true,"g":true,"h":true,"j":true,"k":true,"l":true } const thirdRow = {"z":true,"x":true,"c":true,"v":true,"b":true,"n":true,"m...
Keyboard Row
You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive. You want to reac...
class Solution: def maxResult(self, nums, k): deq, n = deque([0]), len(nums) for i in range(1, n): while deq and deq[0] < i - k: deq.popleft() nums[i] += nums[deq[0]] while deq and nums[i] >= nums[deq[-1]]: deq.pop() deq.append(i) ...
class Solution { public int maxResult(int[] nums, int k) { int n = nums.length, a = 0, b = 0; int[] deq = new int[n]; deq[0] = n - 1; for (int i = n - 2; i >= 0; i--) { if (deq[a] - i > k) a++; nums[i] += nums[deq[a]]; while (b >= a && nums[deq[b]]...
#define pii pair<int, int> class Solution { public: int maxResult(vector<int>& nums, int k) { int n=nums.size(); int score[n]; priority_queue<pii> pq; for(int i=n-1 ; i>=0 ; i--) { while(pq.size() && pq.top().second>i+k) pq.pop(); ...
var maxResult = function(nums, k) { let n = nums.length, deq = [n-1] for (let i = n - 2; ~i; i--) { if (deq[0] - i > k) deq.shift() nums[i] += nums[deq[0]] while (deq.length && nums[deq[deq.length-1]] <= nums[i]) deq.pop() deq.push(i) } return nums[0] };
Jump Game VI
Given two strings: s1 and s2 with the same&nbsp;size, check if some&nbsp;permutation of string s1 can break&nbsp;some&nbsp;permutation of string s2 or vice-versa. In other words s2 can break s1&nbsp;or vice-versa. A string x&nbsp;can break&nbsp;string y&nbsp;(both of size n) if x[i] &gt;= y[i]&nbsp;(in alphabetical or...
class Solution: def checkIfCanBreak(self, s1: str, s2: str) -> bool: s1, s2 = sorted(s1), sorted(s2) return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2))
class Solution { public boolean checkIfCanBreak(String s1, String s2) { int n = s1.length(); char[] one = s1.toCharArray(); char[] two = s2.toCharArray(); Arrays.sort(one); Arrays.sort(two); if(check(one,two,n) || check(two,one,n)){ return true; } ...
class Solution { public: bool checkIfCanBreak(string s1, string s2) { vector<int>freq1(26,0),freq2(26,0); for(int i=0;i<s1.size();i++) { freq1[s1[i]-'a']++; } for(int i=0;i<s2.size();i++) { freq2[s2[i]-'a']++; } int count1 =...
const canAbreakB = (s1, s2) => { const s1Heap = new MinPriorityQueue(); const s2Heap = new MinPriorityQueue(); for(let c of s1) { s1Heap.enqueue(c.charCodeAt(0)); } for(let c of s2) { s2Heap.enqueue(c.charCodeAt(0)); } while(s2Heap.size()) { const s1Lea...
Check If a String Can Break Another String
There is a function signFunc(x) that returns: 1 if x is positive. -1 if x is negative. 0 if x is equal to 0. You are given an integer array nums. Let product be the product of all values in the array nums. Return signFunc(product). &nbsp; Example 1: Input: nums = [-1,-2,-3,-4,3,2,1] Output: 1 Explanation: The...
class Solution: def arraySign(self, nums: List[int]) -> int: return 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1
class Solution { public int arraySign(int[] nums) { int prod=1; for(int i=0;i<nums.length;i++){ int val=signFunc(nums[i]); prod*=val; } return prod; } private int signFunc(int x){ if(x<0) return -1; else if(x>0) return 1; r...
class Solution { public: int arraySign(vector<int>& nums) { int res = 1; for(auto x : nums) { if(x < 0) res *= -1; else if(x == 0) return 0; } return res; } };
var arraySign = function(nums) { // use filter to find total negative numbers in the array let negativeCount = nums.filter(n => n<0).length; // check if the nums array has zero. If it does, then return 0 if(nums.includes(0)) return 0; // If negativeCount variable is even answer is 1 else -1 re...
Sign of the Product of an Array
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example,...
class Solution: def flipMatchVoyage(self, root, voyage): # ------------------------------ def dfs(root): if not root: # base case aka stop condition # empty node or empty tree return True ...
class Solution { private int i = 0; public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) { List<Integer> list = new ArrayList<>(); flipMatchVoyage(root,voyage,list); return list; } private void flipMatchVoyage(TreeNode root, int[] voyage,List<Integer> list)...
class Solution { public: bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){ if(root == NULL || ind == voyage.size()){ ind--; return true; } // Not possible to create if(root->val != voyage[ind]){ ans.clear(); ...
var flipMatchVoyage = function(root, voyage) { const output = [] let idx = 0; function run(node) { if(!node) return true; if(voyage[idx] !== node.val) return false; idx++; if(node.left && node.left.val !== voyage[idx]) { output.push(node.val); ...
Flip Binary Tree To Match Preorder Traversal
You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater...
class Solution: def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]: stack = [] ans = [] node = head i = 0 while node is not None: while stack and stack[-1][0] < node.val: ans[stack[-1][1]] = node.val stack.pop...
class Solution { public int[] nextLargerNodes(ListNode head) { ListNode length=head; int l=0; while(length!=null) { length=length.next; l++; } int[] res=new int[l]; int i=0; ListNode temp=head; while(temp!=null) ...
class Solution { public: vector<int> nextLargerNodes(ListNode* head) { vector<int> ans; ListNode* curr = head; if(head->next == NULL){ ans.push_back(0); return ans; } while(curr != NULL){ ListNode* next = curr->next; while(next...
var nextLargerNodes = function(head) { let arr = []; while(head){ arr.push(head.val); head = head.next } return nextGreaterElement(arr) }; function nextGreaterElement(arr){ let temp = []; let n = arr.length; let stack = []; for(let i=n-1; i>=0; i--){ while(s...
Next Greater Node In Linked List
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array. &nbsp; Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th&nbsp;missing ...
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: arr = set(arr) i = 0 missed = 0 while missed != k: i += 1 if i not in arr: missed += 1 return i
class Solution { public int findKthPositive(int[] arr, int k) { if(arr[0] > k) { return k; } for(int i=0; i<arr.length; i++) { if(arr[i] <= k) { k++; }else { break; } } return k; } }
class Solution { public: int findKthPositive(vector<int>& arr, int k) { int n=arr.size(); if(arr[n-1]==n) return n+k; else { int start=0; int end=n-1; int ans; while(start<=end) { int mid=start+(end-start)/2; if((arr[mid]-(mid+...
var findKthPositive = function(arr, k) { let newArr = []; for(let i=0,j=1; j<=arr.length+k; j++){ arr[i]!=j?newArr.push(j):i++; } return newArr[k-1]; };
Kth Missing Positive Number
Given an integer array nums, reorder it such that nums[0] &lt; nums[1] &gt; nums[2] &lt; nums[3].... You may assume the input array always has a valid answer. &nbsp; Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: Input: nums = [1,3,2,2,3,1] Out...
class Heap: def __init__(self): self.q = [] def push(self,data): i = len(self.q) self.q.append(data) while i>0: if self.q[i] > self.q[(i-1)//2]: self.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i] i = (i-1)//2 else: return def pop(self): if len(self.q)==0:return self.q[0] = self.q[-1...
class Solution { public void wiggleSort(int[] nums) { int a[]=nums.clone(); Arrays.sort(a); int left=(nums.length-1)/2; int right=nums.length-1; for(int i=0;i<nums.length;i++){ if(i%2==0){ nums[i]=a[left]; left--; } ...
class Solution { public: void wiggleSort(vector<int>& nums) { priority_queue<int> pq; for(auto &i : nums) pq.push(i); for(int i = 1; i < nums.size(); i += 2) nums[i] = pq.top(), pq.pop(); for(int i = 0; i < nums.size(); i += 2) nums[i] = pq.top(...
var wiggleSort = function(nums) { nums.sort((a,b) => a - b); let temp = [...nums]; let low = Math.floor((nums.length-1)/2), high = nums.length-1; for(let i=0; i < nums.length; i++){ if(i % 2 === 0){ nums[i] = temp[low]; low--; }else{ nums[i] = temp[...
Wiggle Sort II
Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel&nbsp;('a', 'e', 'i', 'o', 'u') Each vowel&nbsp;'a' may only be followed by an 'e'. Each vowel&nbsp;'e' may only be followed by an 'a'&nbsp;or an 'i'. Each vowel&nbsp...
class Solution: def countVowelPermutation(self, n: int) -> int: # dp[i][j] means the number of strings of length i that ends with the j-th vowel. dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)] moduler = math.pow(10, 9) + 7 for i in range(1, n): # For vowel a ...
class Solution { private long[][] dp; private int mod = (int)1e9 + 7; public int countVowelPermutation(int n) { dp = new long[6][n+1]; if(n == 1) return 5; for(int i = 0; i < 5; i++) dp[i][0] = 1; helper(n,'z'); return (int)dp[5][n]; } private ...
class Solution { public: int countVowelPermutation(int n) { long a = 1, e = 1, i = 1, o = 1, u = 1, mod = pow(10, 9)+7; long a2, e2, i2, o2, u2; for (int j = 2; j <= n; j++) { a2 = (e + i + u) % mod; e2 = (a + i) % mod; i2 = (e + o) % mod; o2 ...
var countVowelPermutation = function(n) { let a = 1, e = 1, i = 1, o = 1, u = 1, mod = 1000000007 while(n-- > 1){ let new_a = a % mod, new_e = e % mod, new_i = i % mod, new_o = o % mod, new_u = u % mod a = new_e + new_i + new_u e = new_a + new_i i = new_e + new_o o = new_...
Count Vowels Permutation
We are given n different types of stickers. Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of ...
from functools import lru_cache from collections import Counter class Solution(object): def minStickers(self, stickers, target): counter = [Counter(sticker) for sticker in stickers] n = len(counter) @lru_cache(None) def dfs(target): if not target: return 0 ta...
class Solution { HashMap<String,HashMap<Character,Integer>>map; public int minStickers(String[] stickers, String target) { map = new HashMap<>(); for(String sticker:stickers){ HashMap<Character,Integer> temp = new HashMap<>(); for(char ch:sticker.toCharArray()) ...
class Solution { public: int dp[50][1<<15] ; int solve(int ind, int mask, vector<string>& stickers, string& target) { if (mask == 0) return 0 ; if (ind == stickers.size()) return 1e8 ; if (dp[ind][mask] != -1) return dp[ind][mask] ; vector<...
/** * @param {string[]} stickers * @param {string} target * @return {number} */ // Backtracking var minStickers = function(stickers, target) { //* Inits *// let dp = new Map(); //* Helpers *// const getStringDiff = (str1, str2) => { for(let c of str2) { if(str1.includes(c)) str...
Stickers to Spell Word
You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string. &nbsp; Example 1: Input: num = "4321", k = 4 Output: "1342" Explanation: The steps t...
from sortedcontainers import SortedList class Solution: def minInteger(self, num: str, k: int) -> str: sz, window = len(num), SortedList() remainedIndices, poppedIndices = SortedList(range(sz)), [] while k > 0: while len(window) < k + 1 and len(window) < len(remainedIndices): ...
class Solution { public String minInteger(String num, int k) { //pqs stores the location of each digit. List<Queue<Integer>> pqs = new ArrayList<>(); for (int i = 0; i <= 9; ++i) { pqs.add(new LinkedList<>()); } for (int i = 0; i < num.length(); ++i) { ...
/* Time: O(nlogn) Space: O(n) Tag: Segment Tree, Greedy (put the possible feasible smallest index in place of cur index), Queue Difficulty: H (Both Logic and Implementation) */ class SegmentTree { vector<int> tree; public: SegmentTree(int size) { tree.resize(4 * size + 1, 0); } ...
/** * @param {string} num * @param {number} k * @return {string} Idea is based on bubble sorting with limited steps k */ var minInteger = function(num, k) { if (num.length == 1) return num; let nums = num.split(''); let i = 0, j = 0; while (k && i < num.length-1) { // ...
Minimum Possible Integer After at Most K Adjacent Swaps On Digits
You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: The number of "bulls", which are digits in the guess that are in the correct position. The number of ...
class Solution: def getHint(self, secret: str, guess: str) -> str: # Setup counts for bulls and cows bulls = cows = 0 # Copy secret and guess into lists that are easier to work with secretCopy = list(secret) guessCopy = list(guess) # In a fo...
class Solution { public String getHint(String secret, String guess) { int arr[] = new int[10], bulls = 0, cows = 0; for (int i = 0; i < secret.length(); i++) { char sec = secret.charAt(i); char gue = guess.charAt(i); if (sec == gue) bulls++; else { ...
class Solution { public: string getHint(string secret, string guess) { int bulls = 0; vector<int> v1(10, 0); vector<int> v2(10, 0); for (int i = 0; i < secret.size(); ++i) { if (secret[i] == guess[i]) { ++bulls; } ...
var getHint = function(secret, guess) { let ACount = 0, BCount = 0; const secretMap = new Map(), guessMap = new Map(); for(let i = 0; i < secret.length; i++) { if(secret[i] == guess[i]) { ACount++; } else { if(secretMap.has(secret[i])) { secret...
Bulls and Cows
Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise. &nb...
class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: a = '' for i in words: a += i if a == s: return True if not s.startswith(a): break ret...
class Solution { public boolean isPrefixString(String s, String[] words) { StringBuilder res = new StringBuilder (""); for (String word : words) { res.append (word); if (s.equals (res.toString())) return true; if (s.indexOf (res.toString()) == -1) ...
class Solution { public: bool isPrefixString(string s, vector<string>& words) { string n=""; for(string str:words){ for(char ch:str){ n+=ch; } if(n==s){ return true; } } return false; } };
var isPrefixString = function(s, words) { let str = words[0]; if(s === words[0]){ return true; } for(let i=1; i < words.length; i++){ if(s === str){ return true; } if( s.startsWith(str)){ str += words[i]; continue; }else{ ...
Check If String Is a Prefix of Array
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. For example, the sentence...
class Solution: def sortSentence(self, s: str) -> str: x = s.split() dic = {} for i in x : dic[i[-1]] = i[:-1] return ' '.join([dic[j] for j in sorted(dic)])
class Solution { public String sortSentence(String s) { String []res=new String[s.split(" ").length]; for(String st:s.split(" ")){ res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1); } return String.join(" ",res); } }
class Solution { public: string sortSentence(string s) { stringstream words(s); string word; pair<int, string> m; vector<pair<int, string> > sent; //SECTION 1 while(words>>word) { int len = word.size(); int i = int(word[l...
var sortSentence = function(s) { let sortingS = s.split(' ').sort((a,b) => a.substr(-1) - b.substr(-1)); slicingS = sortingS.map(word => word.slice(0, -1)); return slicingS.join(' '); };
Sorting the Sentence
Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last leve...
class Solution: # @param {TreeNode} root # @return {integer} def countNodes(self, root): if not root: return 0 leftDepth = self.getDepth(root.left) rightDepth = self.getDepth(root.right) if leftDepth == rightDepth: r...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solutio...
class Solution { public: int countNodes(TreeNode* root) { if(root==nullptr) return 0; int left = countNodes(root->left); int right = countNodes(root->right); return 1+left+right; } };
var countNodes = function(root) { return root === null ? 0 : countNodes(root.left) + countNodes(root.right) + 1; }
Count Complete Tree Nodes
There is a strange printer with the following two special properties: The printer can only print a sequence of the same character each time. At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. Given a string s, return the minimu...
class Solution(object): def strangePrinter(self, s): """ :type s: str :rtype: int """ # remove duplicate letters from s. tmp = [] for c in s: if len(tmp) == 0 or tmp[-1] != c: tmp.append(c) s = "".join(tmp) _m = {} ...
class Solution { public int strangePrinter(String s) { if (s.equals("")) return 0; int len = s.length(); int[][] dp = new int[len][len]; for (int i = 0; i < len; i++) dp[i][i] = 1; for (int l = 2; l <= len; l++) { for (int i = 0; i < len && l + i - 1 < len; i++) { int j ...
class Solution { public: int dp[101][101]; int solve(string s,int i,int j) { if(i>j) return 0; if(dp[i][j]!=-1) return dp[i][j]; int ans=0; while(i<j && s[i+1]==s[i]) i++; while(i<j && s[j]==s[j-1]) { j--; ...
var strangePrinter = function(s) { if(!s) return 0; const N = s.length; const state = Array.from({length:N}, () => Array.from({length:N})); for(let i = 0; i < N; i++) { // Printing one character always takes one attempt state[i][i] = 1; } const search = (i,j) => { ...
Strange Printer
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker c...
class Solution: #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn) #Space-Complexity: O(n) def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: #Approach: First of all, linearly traverse each and every corresponding index #position of...
class Solution { public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(b[1]-a[1])); for(int i=0;i<profit.length;i++) { pq.add(new int[]{difficulty[i],profit[i]}); } Arrays.sort(worker); ...
class Solution { public: static bool cmp(pair<int,int>a, pair<int,int>b){ if(a.first == b.first){ return a.second<b.second; } return a.first>b.first; } int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) { int ans = 0; ...
var maxProfitAssignment = function(difficulty, profit, worker) { const data = []; for (let i = 0; i < difficulty.length; i++) { data.push({ difficulty: difficulty[i], profit: profit[i] }); } data.sort((a, b) => a.difficulty - b.difficulty); let maxProfit = 0; for (let i = 0; i < data...
Most Profit Assigning Work
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. &nbsp; Example 1: Input: word1 = "abc", word2 = "pqr" Output: "apb...
class Solution(object): def mergeAlternately(self, word1, word2): i=0 j=0 st=[] while i<len(word1) and j<len(word2): st.append(word1[i]) st.append(word2[j]) i+=1 j+=1 while j<len(word2): st.append(word2[j]) ...
class Solution { public String mergeAlternately(String word1, String word2) { StringBuilder sb = new StringBuilder(); int lenmax = Math.max(word1.length(),word2.length()); for(int i=0;i<=lenmax-1;i++) { if(i<word1.length()) sb.append(word1.charAt(i)); if(i<wor...
class Solution { public: string mergeAlternately(string word1, string word2) { string final=""; int p=word1.size(); int q=word2.size(); int n=max(p,q); for(int i=0;i<n;i++){ if(p){ final=final+word1[i]; p--; } ...
/** * @param {string} word1 * @param {string} word2 * @return {string} */ var mergeAlternately = function(word1, word2) { let length = Math.max(word1.length, word2.length), s = ''; for(let i = 0; i < length; i++){ s+= word1[i] || ''; s+= word2[i] || ''; } return s; };
Merge Strings Alternately
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our...
class Solution: def projectionArea(self, grid: List[List[int]]) -> int: total = 0 # top total += sum([1 for i in grid for j in i if j > 0]) # front total += sum([max(col) for col in zip(*grid)]) # side total += sum([max(row) for row in grid]) ...
class Solution { public int projectionArea(int[][] grid) { int totalArea = 0; for(int[] row : grid){ int max = row[0]; for(int c : row){ if(max < c){ max = c; }if(c != 0){ totalArea += 1...
class Solution { public: int projectionArea(vector<vector<int>>& grid) { int res=0; // X-Y ( top ) for(int i=0;i<grid.size();i++) { for(int j=0;j<grid[0].size();j++) { if(grid[i][j]) // if some cubes are present it is seen as of area 1 from top...
var projectionArea = function(grid) { let maxs = new Array(grid.length).fill(0); grid.forEach(row => row.forEach((val, idx) => { if (maxs[idx] < val) maxs[idx] = val; })) const z = grid.reduce((prev, curr) => prev + curr.filter(val => val !== 0).length, 0); const y = grid.reduce((prev,...
Projection Area of 3D Shapes
You are given row x col grid representing a map where grid[i][j] = 1 represents&nbsp;land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The is...
class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: perimeter = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: perimeter += 4 if i != 0 and grid[i-1][j] == 1: ...
class Solution { public int islandPerimeter(int[][] grid) { if(grid == null || grid.length == 0) return 0; int row=grid.length,col=grid[0].length; int perimeter=0; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(grid[i][j]==1){ pe...
////** hindi me samjho ab// // agar mje left or right or bottom or top me 1 mila to me aaga badunga agar nahi //mila mtlb ya to wo boundary hai uske baad 0 ara hai agar esa hai to cnt+=1 //kardo kuki wo hi to meri boundary banegi . note : agar boundary hai mtlb //i <0 or j<0 or i>=n or j>=m to cnt+=1 kardo or ag...
var islandPerimeter = function(grid) { let perimeter = 0 let row = grid.length let col = grid[0].length for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 1) { if (i === 0 || i > 0 && grid[i-1][j] === 0) perimete...
Island Perimeter
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow...
class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: def getRange(left, right, array): if left > right: right, left = left, right return sum((array[i] for i in range(left,right+1))) ...
class Solution { public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) { int total = 0; // if home is to the down of start move, down till there if(homePos[0]>startPos[0]){ int i = startPos[0]+1; while(i<=homePos[0]){ ...
// This is Straightforward Question becuase you need to travel at least one time the incoming rows and column in path. // So why you need to complicate the path just traverse staright and to homePos Row and homePos column and you will get the ans... // This Question would have become really tough when negative values a...
var minCost = function(startPos, homePos, rowCosts, colCosts) { let totCosts = 0; let rowDir = startPos[0] <= homePos[0] ? 1 : -1; let colDir = startPos[1] <= homePos[1] ? 1 : -1; let row = startPos[0]; while (row != homePos[0]) { row += rowDir; totCosts += rowCosts[row]; ...
Minimum Cost Homecoming of a Robot in a Grid
No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n, return a list of two integers [A, B] where: A and B are No-Zero integers. A + B = n The test cases are generated so that there is at least one valid solution. If there are many valid solutions you...
class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: for i in range(1,n//2+1): first = str(i) second = str(n-i) if "0" not in first and "0" not in second: return [i, n-i]
class Solution { public int[] getNoZeroIntegers(int n) { int B; for (int A = 1; A < n; ++A) { B = n - A; if (!(A + "").contains("0") && !(B + "").contains("0")) return new int[] {A, B}; } return new int[]{}; } }
class Solution { public: int has0(int x) { while (x){ if (x % 10 == 0) return 1; x /= 10; } return 0; } vector<int> getNoZeroIntegers(int n) { for(int i=1;i<=n;i++){ if(has0(i)==false && has0(n-i)==false){ return {i,n-i}; } ...
var getNoZeroIntegers = function(n) { for(let i=1;i<=n;i++){ if(!haveZero(i) && !haveZero(n-i)){ return [i,n-i] } } }; const haveZero = (n) =>{ let copy = n; while(copy>0){ if(copy%10===0){ return true } copy=Math.floor(copy/10) } retur...
Convert Integer to the Sum of Two No-Zero Integers
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. &nbsp; Example 1: Input: heights = [2,1,5,6,2,3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle ...
class Solution: def largestRectangleArea(self, heights: List[int]) -> int: maxArea = 0 stack = [] # (index, height) for i, h in enumerate(heights): startIndex = i while stack and stack[-1][1] > h: index, height = stack.pop() ma...
class Solution { public int largestRectangleArea(int[] heights) { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); int n = heights.length; int[] left = new int[n]; int[] right = new int[n]; int[] width = new int[n]; for(in...
class Solution { private: vector<int> nextSmallerElement(vector<int>& arr, int n){ stack<int> s; s.push(-1); vector<int> ans(n); for(int i = n-1; i>=0 ; i--){ int curr = arr[i]; while(s.top()!=-1 && arr[s.top()]>=curr){ ...
var largestRectangleArea = function (heights) { let maxArea = 0; let stack = []; // [[index, height]] for (let i = 0; i < heights.length; i++) { let start = i; while (stack.length != 0 && stack[stack.length - 1][1] > heights[i]) { let [index, height] = stack.pop(); m...
Largest Rectangle in Histogram
You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i &lt; j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. &nbsp; Example...
class Solution: def minimumDeletions(self, s: str) -> int: preSum = [0] * (len(s) + 1) sufSum = [0] * (len(s) + 1) for i in range(len(s)): if s[i] == "a": preSum[i] += 1 + preSum[i-1] else: preSum[i] = preSum[i-1] if s[len(s)-i-1] == "b": sufSum[len(s)-i-1] += 1 + sufSum[len(s)-i] els...
class Solution { public int minimumDeletions(String s) { //ideal case : bbbbbbbbb int[] dp = new int[s.length()+1]; int idx =1; int bCount=0; for(int i =0 ;i<s.length();i++) { if(s.charAt(i)=='a') { dp[idx] = Math.min(dp[idx-1]+1,...
class Solution { public: int minimumDeletions(string s){ vector<int> deletions(s.size()+1, 0); int b_count = 0; for(int i = 0; i<s.size(); i++){ if(s[i]=='a'){ // Either Delete this 'a' or Delete all previous 'b's. deletions[i+1] = min(de...
var minimumDeletions = function(s) { const dpA = []; let counter = 0; for (let i = 0; i < s.length; i++) { dpA[i] = counter; if (s[i] === 'b') { counter++; } } counter = 0; const dpB = []; for (let i = s.length - 1; i >= 0; i--) { dpB[i] = cou...
Minimum Deletions to Make String Balanced
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 &lt;= x &lt; ai and 0 &lt;= y &lt; bi. Count and return the number of maximum integers in the matrix after performing all the operations. &nbsp; Example...
class Solution: def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: if not ops: return m*n else: x,y = zip(*ops) return min(x) * min(y)
class Solution { public int maxCount(int m, int n, int[][] ops) { int minRow=m,minCol=n; for(int[] op:ops){ minRow=Math.min(minRow,op[0]); minCol=Math.min(minCol,op[1]); } return minRow*minCol; } }
class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { int mn_i = m, mn_j = n; for(auto &i : ops) mn_i = min(mn_i, i[0]), mn_j = min(mn_j, i[1]); return mn_i * mn_j; } };
var maxCount = function(m, n, ops) { if( ops.length === 0 ) return m*n let min_a = m , min_b = n for( let [x,y] of ops ){ if( x < min_a ) min_a = x if( y < min_b ) min_b = y } return min_a * min_b };
Range Addition II
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei &lt;= d &lt;= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend. &nbsp; Examp...
class Solution(object): def maxEvents(self, events): """ :type events: List[List[int]] :rtype: int """ events = sorted(events, key=lambda x: x[0]) current_day = 0 min_heap = [] event_id = 0 total_number_of_days = max(end for start, end in event...
class Solution { public int maxEvents(int[][] events) { Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]); // here sorting the array on ths basis of last day because we want to finish the events which happens first,fist. TreeSet<Integer> set =new TreeSet<>(); for(int i =1;i...
class Solution { public: int maxEvents(vector<vector<int>>& events) { int res=0; int m=0; for(auto x:events) m=max(m,x[1]); sort(events.begin(),events.end()); int j=0; priority_queue<int,vector<int>,greater<int>> pq; for(int i=1;i<=m;i++) ...
/** * O(nlogn) */ var maxEvents = function(events) { // sort events by their start time events.sort((a,b) => a[0]-b[0]); // create priority queue to sort events by end time, the events that have saem start time let minHeap = new PriorityQueue((a, b) => a - b); let i = 0, len = events.length, res =...
Maximum Number of Events That Can Be Attended
Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values&nbsp;{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. &nbsp; Example 1: Input:...
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5 DAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWE...
class Solution { public String dayOfTheWeek(int day, int month, int year) { String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; year--; int total = (year/4)*366+(year-year/4)*365; int[] months = {31,28,31,30,31,30,31,31,30,31,30,31}; ...
class Solution { public: int daysOfMonth[2][12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; string weekName[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; bool isleapyear(int year) { ...
/** * @param {number} day * @param {number} month * @param {number} year * @return {string} */ var dayOfTheWeek = function(day, month, year) { var map = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday" ...
Day of the Week
Given the head of a linked list, remove the nth node from the end of the list and return its head. &nbsp; Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] &nbsp; Constraints: The number of nodes in...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: if head == None: return None slow = head fast = h...
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode temp = head; int len=0; if(head==null || head.next==null) return null; while(temp!=null){ temp=temp.next; len++; } if(len==n) return h...
* 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* removeNthFromEn...
var removeNthFromEnd = function(head, n) { let start = new ListNode(0, head); let slow = start, fast = start; for (let i =1; i <= n; i++) { fast = fast.next; } while(fast && fast.next) { slow = slow.next; fast = fast.next; } let nthNode = slow.next slow.next = ...
Remove Nth Node From End of List
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in&nbsp;O(n)&nbsp;time and uses only constant extra space. &nbsp; Example 1: Input: nums ...
class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: res = [] hm = {} # adding entries in hashmap to check frequency for i, v in enumerate(nums): if v not in hm: hm[v] = 1 else: hm[v] += 1 # checking f...
class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> ans = new ArrayList<>(); for(int i=0;i<nums.length;i++){ int ind = Math.abs(nums[i])-1; if(nums[ind]<0){ ans.add(Math.abs(nums[i])); } else{ ...
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int n=nums.size(); vector<int> a; vector<int> arr(n+1,0); for(int i=0;i<nums.size();i++) arr[nums[i]]++; for(int j=0;j<=n;j++) if(arr[j]==2) a.push_back(j); return a; ...
// Approach : Mark Visited Elements in the Input Array itself var findDuplicates = function(nums) { let result = []; for(let i = 0; i < nums.length; i++) { let id = Math.abs(nums[i]) - 1; if(nums[id] < 0) result.push(id + 1); else nums[id] = - Math.abs(nums[id]); } return result;...
Find All Duplicates in an Array
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she...
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def check(x): return sum(ceil(ele/x) for ele in piles) <= h l = 1 r = max(piles) while l < r: mid = (l+r) >> 1 if not check(mid): l=mid+1 else: ...
class Solution { public int minEatingSpeed(int[] piles, int h) { int max=0; int ans=0; for(int i=0;i<piles.length;i++) { max=Math.max(piles[i],max); } if(piles.length==h) return max; int left=1; int right=max; while(left...
class Solution { public: int minEatingSpeed(vector<int>& piles, int h) { int mx=1000000001; int st=1; while(mx>st) { int k = ((mx+st)/2); int sum=0; for(int i =0 ;i...
var minEatingSpeed = function(piles, h) { /*The range of bananas that Koko can eat is k = 1 to Max(piles)*/ let startk = 1; let endk = Math.max(...piles); while(startk <= endk){ let midk = Math.floor(startk + (endk - startk)/2); /*midk are the count of bananas that koko decide to ea...
Koko Eating Bananas
You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multi...
class Solution: def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: ret = [0] * k # UAM store user_acts = {} # User minutes store # Adding user minutes to hash table for log in logs: if user_acts.get(log[0], 0): user_acts[...
class Solution { public int[] findingUsersActiveMinutes(int[][] logs, int k) { HashMap<Integer, HashSet<Integer>> usersMap = new HashMap(); for(int[] log : logs){ int user = log[0]; int min = log[1]; //add current user mapping, if not exist ...
class Solution { public: vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) { vector<int>ans(k,0); unordered_map<int,unordered_set<int>>m; for(int i = 0; i<logs.size(); i++) { m[logs[i][0]].insert(logs[i][1]); } for(auto x : m) ...
var findingUsersActiveMinutes = function(logs, k) { const map = new Map(); for (const [userID, minute] of logs) { if (!map.has(userID)) map.set(userID, new Set()); map.get(userID).add(minute); } const count = new Array(k).fill(0); for (const actions of map.values()) { coun...
Finding the Users Active Minutes
You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the uppe...
class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) q = [(0, 0, 0)] dist = [[float('inf') for _ in range(n)] for _ in range(m)] while q: size = len(q) for _ in range(size): obs, x, y = heapq...
class Solution { int [][]grid; int n,m; boolean [][]seen; int []dx = new int[]{0,0,1,-1}; int []dy = new int[]{1,-1,0,0}; int [][]dp; int finalres; private boolean isValid(int i, int j) { return Math.min(i,j)>=0 && i<n && j<m && !seen[i][j]; } private int solve(int i...
class Solution { public: int minimumObstacles(vector<vector<int>>& grid) { int m=grid.size(), n=grid[0].size(); vector<int> dir={0,1,0,-1,0}; vector<vector<int>> dist(m, vector<int> (n,INT_MAX)); vector<vector<bool>> vis(m, vector<bool>(n,0)); deque<pair<int,int>>q; dis...
/** * @param {number[][]} grid * @return {number} */ var minimumObstacles = function(grid) { let dx=[[0,1],[0,-1],[1,0],[-1,0]]; let distance=[]; for(let i=0;i<grid.length;i++){ distance[i]=[]; for(let j=0;j<grid[i].length;j++){ distance[i][j]=Number.MAX_SAFE_INTEGER; ...
Minimum Obstacle Removal to Reach Corner
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two ...
class Solution: def rob(self, root: Optional[TreeNode]) -> int: hashMap = {} def helper(root: Optional[TreeNode]) -> int: if not root: return 0 if root in hashMap: return hashMap[root] ansOption1 = root.val if r...
/** * 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> dp(TreeNode* root) { vector<int> ans(2,0); //dp[0]: maximal money you can get by robbing current node. dp[1]: maximal money you can get when not rob this node if(root==NULL) return ans; vector<int> left=dp(root->left); vector<int> right=dp(roo...
var rob = function(root) { const dfs = (node = root) => { if (!node || node.val === null) return [0, 0]; const { val, left, right } = node; const [robL, notRobL] = dfs(left); const [robR, notRobR] = dfs(right); const rob = val + notRobL + notRobR; const notRob = Math....
House Robber III
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. &nbsp; Example 1: Input: num1 =...
class Solution: def addStrings(self, num1: str, num2: str) -> str: def func(n): value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9} result = 0 for digit in n: result = 10 * result + value[digit] return result ...
import java.math.BigInteger; class Solution { public String addStrings(String num1, String num2) { return new BigInteger(num1).add(new BigInteger(num2)).toString(); } }
class Solution { public: string ans=""; int carry=0; string addStrings(string num1, string num2) { while(num1.size() && num2.size()){ int sum= (num1.back() -'0' + num2.back() -'0' + carry) ; ans = (char)((sum%10) + '0') + ans; carry= sum/10; num1.pop_b...
var addStrings = function(num1, num2) { let i = num1.length - 1; let j = num2.length - 1; let carry = 0; let sum = ''; for (;i >= 0 || j >= 0 || carry > 0;i--, j--) { const digit1 = i < 0 ? 0 : num1.charAt(i) - '0'; const digit2 = j < 0 ? 0 : num2.charAt(j) - '0'; const...
Add Strings
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order. &nbsp; Example 1: Input: n = 4, k = 2 Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unor...
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: return itertools.combinations(range(1, n+1), k)
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> subsets=new ArrayList<>(); generatesubsets(1,n,new ArrayList(),subsets,k); return subsets; } void generatesubsets(int start,int n,List<Integer> current,List<List<Integer>> subsets,int k){ ...
class Solution { public: void solve(vector<int> arr,vector<vector<int>> &ans,vector<int> &temp,int k,int x){ if(temp.size()==k){ ans.push_back(temp); return; } if(x>=arr.size()) return ; for(int i = x;i<arr.size();i++){ temp.push_back(arr[i]); ...
var combine = function(n, k) { function helper (start, end, combo, subset, answer) { if (combo==0) { answer.push([...subset]) return; } if (end - start + 1 < combo) { return; } if (start > end) { return; } subse...
Combinations
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you ca...
class Solution(object): def longestPalindrome(self, words): wc = collections.Counter(words) aa = 0 # count how many words contain only two identical letters like 'aa' center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2 abba...
class Solution { public int longestPalindrome(String[] words) { int[][] freq = new int[26][26];//array for all alphabet combinations for (String word : words) freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word int left = 0;//to store freq counts ...
class Solution { public: int longestPalindrome(vector<string>& words) { int count[26][26] = {}; int ans =0; for(auto w : words){ int a = w[0] - 'a'; int b = w[1] - 'a'; if(count[b][a]){ ans+= 4; coun...
var longestPalindrome = function(words) { const n = words.length; const map = new Map(); let len = 0; for (const word of words) { const backward = word.split("").reverse().join(""); if (map.has(backward)) { len += (word.length * 2); map.set(backward, map.get(b...
Longest Palindrome by Concatenating Two Letter Words