algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2   Constraints: The number of nodes in the tree is in the range [0, 104]. -100 <= Node.val <= 100
class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ result = 0 depths = [] self.handler(root, result, depths) return max(depths) def handler(self, root, result, depths): if root: result += 1 self.handler(root.left, result, depths) self.handler(root.right, result, depths) else: depths.append(result)
class Solution { public int maxDepth(TreeNode root) { // Base Condition if(root == null) return 0; // Hypothesis int left = maxDepth(root.left); int right = maxDepth(root.right); // Induction return Math.max(left, right) + 1; } }
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return max(left, right) + 1; } };
var maxDepth = function(root) { if(root == null) return 0 let leftDepth = maxDepth(root.left) let rightDepth = maxDepth(root.right) let ans = Math.max(leftDepth,rightDepth) + 1 return ans };
Maximum Depth of Binary Tree
Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.   Example 1: Input: nums = [2,3,4,6] Output: 8 Explanation: There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) Example 2: Input: nums = [1,2,4,5,10] Output: 16 Explanation: There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 104 All elements in nums are distinct.
class Solution: def tupleSameProduct(self, nums: List[int]) -> int: from itertools import combinations mydict=defaultdict(int) ans=0 for a,b in combinations(nums,2): mydict[a*b]+=1 for i,j in mydict.items(): if j>1: ans+=(j*(j-1)//2)*8 return ans
class Solution { public int tupleSameProduct(int[] nums) { if(nums.length < 4){ return 0; } int res = 0; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length - 1; i++){ for(int j = i + 1; j < nums.length; j++){ int val = nums[i] * nums[j]; map.put(val, map.getOrDefault(val, 0) + 1); } } for(int key : map.keySet()){ int val = map.get(key); if(val > 1){ res += val * (val - 1) * 4; // (val * (val - 1) / 2) * 8 } } return res; } }
class Solution { public: int tupleSameProduct(vector<int>& nums) { int n = nums.size(); unordered_map<int,int> map; int res = 0; for(int i = 0 ; i < n ; i++){ for(int j = i+1 ; j < n ; j++){ int prod = nums[i] * nums[j]; map[prod]++;//store product of each possible pair } } for(pair<int,int> m:map){ int n=m.second; res += (n*(n-1))/2; //no. of tuple } return res*8; //Every tuple has 8 permutations } };
var tupleSameProduct = function(nums) { let tupleCount = 0; let products = {}; // we'll keep track of how many times we've seen a given product before for (let a = 0; a < nums.length; a++) { for (let b = a + 1; b < nums.length; b++) { let product = nums[a] * nums[b]; if (products[product]) { // we've seen at least one other pair of numbers with the same product already tupleCount += 8 * products[product]; // multiply by 8 because for any 4 numbers there are 8 permutations products[product] += 1; // increment the count, if we see this product again there are even more possible tuple combinations } else { products[product] = 1; // mark as seen once } } } return tupleCount; };
Tuple with Same Product
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat. &nbsp; Example 1: Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] Output: 7 Explanation: You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. Example 2: Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] Output: 5 Explanation: You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. &nbsp; Constraints: n == apples.length == days.length 1 &lt;= n &lt;= 2 * 104 0 &lt;= apples[i], days[i] &lt;= 2 * 104 days[i] = 0 if and only if apples[i] = 0.
import heapq class Solution(object): def eatenApples(self, apples, days): """ :type apples: List[int] :type days: List[int] :rtype: int """ heap = [(days[0], apples[0])] heapq.heapify(heap) day = 0 rtn = 0 while heap or day < len(days): # print(heap, day) apple = 0 if heap : cnt, apple = heapq.heappop(heap) while heap and cnt <= day and apple > 0: cnt, apple = heapq.heappop(heap) if apple > 0 and cnt > day : rtn +=1 day +=1 if apple > 1 and cnt > day: heapq.heappush(heap, (cnt, apple-1)) if day < len(days) and apples[day] > 0 : heapq.heappush(heap, (day +days[day], apples[day])) return rtn
class Solution { public int eatenApples(int[] apples, int[] days) { PriorityQueue<Apple> minHeap = new PriorityQueue<Apple>((a, b) -> (a.validDay - b.validDay)); //start from day 1 int currentDay = 1; int eatenAppleCount = 0; for(int i = 0; i < apples.length; i++){ //add apple count and their valid day if(apples[i] > 0 && days[i] > 0) { //current day is included int validDay = currentDay + days[i] - 1; minHeap.add(new Apple(apples[i], validDay)); } //check for eatable apple while(!minHeap.isEmpty()){ //get that applen, with minimum valid date (going to expiry soon) Apple apple = minHeap.remove(); if(apple.validDay >= currentDay){ //eat 1 apple apple.count--; //increment count eatenAppleCount++; //add remaiing apple, if not gonna expiry current day if(apple.count > 0 && apple.validDay > currentDay){ minHeap.add(apple); } break; } } //move to the next day currentDay++; } //eat stored apple while(!minHeap.isEmpty()){ Apple apple = minHeap.remove(); if(apple.validDay >= currentDay){ //eat 1 apple apple.count--; //increment count eatenAppleCount++; //add remaiing apple, if not gonna expiry current day if(apple.count > 0 && apple.validDay > currentDay){ minHeap.add(apple); } //apple is eaten in current day, now move to next day currentDay++; } } return eatenAppleCount; } } class Apple { int count; int validDay; public Apple(int count, int validDay){ this.count = count; this.validDay = validDay; } }
class Solution { public: int eatenApples(vector<int>& apples, vector<int>& days) { ios_base::sync_with_stdio(0);cin.tie(0); priority_queue<int,vector<int>,greater<int>>p; unordered_map<int,int>m; int ans=0; int i=0; while(p.size() || i<days.size()){ if(i<days.size() && apples[i]!=0 && days[i]!=0){ m[days[i]+i]=apples[i]; p.push(days[i]+i); } while(p.size()){ if(m[p.top()]!=0 && p.top()>i) break; p.pop(); } if(p.size()){ ans++; m[p.top()]--; } ++i; } return ans; } };
var eatenApples = function(apples, days) { const heap = new MinPriorityQueue({priority: x => x[0]}); let totalApple = 0; for(let i = 0; i < apples.length; i++) { heap.enqueue([i + days[i], apples[i]]); while(!heap.isEmpty()) { const [expire, count] = heap.front().element; if(!count || expire <= i) heap.dequeue(); else break; } if(heap.isEmpty()) continue; totalApple++; heap.front().element[1]--; } let i = apples.length; while(!heap.isEmpty()) { const [expire, count] = heap.dequeue().element; if(!count || expire <= i) continue; totalApple += Math.min(count, expire - i); i = Math.min(expire, i + count); } return totalApple; };
Maximum Number of Eaten Apples
You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1. &nbsp; Example 1: Input: cards = [3,4,2,3,4,7] Output: 4 Explanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal. Example 2: Input: cards = [1,0,5,3] Output: -1 Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards. &nbsp; Constraints: 1 &lt;= cards.length &lt;= 105 0 &lt;= cards[i] &lt;= 106
class Solution: def minimumCardPickup(self, cards: List[int]) -> int: d={} x=[] for i in range(len(cards)): if cards[i] not in d: d[cards[i]]=i else: x.append(i-d[cards[i]]) d[cards[i]]=i if len(x)<=0: return -1 return min(x)+1
class Solution { public int minimumCardPickup(int[] cards) { Map<Integer,Integer> map = new HashMap<>(); int min = Integer.MAX_VALUE; for(int i = 0; i < cards.length; i++) { if(map.containsKey(cards[i])) min = Math.min(i-map.get(cards[i])+1,min); // Check if the difference in indices is smaller than minimum map.put(cards[i],i); // Update the last found index of the card } return min == Integer.MAX_VALUE?-1:min; // Repetition found or not } }
class Solution { public: int minimumCardPickup(vector<int>& cards) { int res (INT_MAX), n(size(cards)); unordered_map<int, int> m; for (auto i=0; i<n; i++) { // number of consecutive cards you have to pick up to have a pair of matching cards == (Diference between 2 indexes of same card) + 1 if (m.count(cards[i])) res = min(res, i-m[cards[i]]+1); m[cards[i]] = i; } return (res == INT_MAX) ? -1 : res; } };
var minimumCardPickup = function(cards) { let cardsSeen = {}; let minPicks = Infinity; for (let i = 0; i < cards.length; i++) { if (!(cards[i] in cardsSeen)) { cardsSeen[cards[i]] = i; } else { const temp = i - cardsSeen[cards[i]] + 1; minPicks = Math.min(minPicks, temp); cardsSeen[cards[i]] = i; } } return minPicks === Infinity ? -1 : minPicks; };
Minimum Consecutive Cards to Pick Up
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1. For each index i, where 0 &lt;= i &lt;&nbsp;n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator. Replace the array nums with newNums. Repeat the entire process starting from step 1. Return the triangular sum of nums. &nbsp; Example 1: Input: nums = [1,2,3,4,5] Output: 8 Explanation: The above diagram depicts the process from which we obtain the triangular sum of the array. Example 2: Input: nums = [5] Output: 5 Explanation: Since there is only one element in nums, the triangular sum is the value of that element itself. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt;= 9
class Solution(object): def triangularSum(self, nums): while len(nums) > 1: arr = [] for i in range(len(nums)-1): arr.append((nums[i] + nums[i+1]) % 10) nums = arr return nums[0]
class Solution { public int triangularSum(int[] nums) { return find(nums,nums.length); } public int find(int[] a, int n){ if(n == 1) return a[0]; for(int i=0;i<n-1;i++){ a[i] = (a[i] + a[i+1])%10; } return find(a,n-1); } }
class Solution { public: int triangularSum(vector<int>& nums) { int n=nums.size(); for(int i=n-1;i>=1;i--){ for(int j=0;j<i;j++){ nums[j]=(nums[j]+nums[j+1])%10; } } return nums[0]; } };
var triangularSum = function(nums) { while(nums.length > 1){ let arr = [] for(let i=0; i<nums.length-1; i++){ arr.push((nums[i] + nums[i+1]) % 10) } nums = arr } return nums[0] };
Find Triangular Sum of an Array
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. &nbsp; Example 1: Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 2: Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 3: Input: root = [9] Output: 1 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 105]. 1 &lt;= Node.val &lt;= 9
# 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 dfs(self, node, path): if not node: return if not node.left and not node.right: path += [node.val] d = {} for i in path.copy(): if i in d: del d[i] else: d[i] = 1 #print(d.items()) self.ans += 1 if len(d) <= 1 else 0 return self.dfs(node.left, path+[node.val]) self.dfs(node.right, path+[node.val]) def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int: self.ans = 0 self.dfs(root, []) return self.ans
class Solution { public int pseudoPalindromicPaths (TreeNode root) { return helper(root, 0); } public int helper(TreeNode node, int freq) { if (node == null) return 0; freq = freq ^ (1 << node.val); if (node.left == null && node.right == null) { return (freq & (freq - 1)) == 0 ? 1 : 0; // return Integer.bitCount(freq) <= 1 ? 1 : 0; } return helper(node.left, freq) + helper(node.right, freq); } }
class Solution { private: void dfs(TreeNode* root,int &ans,unordered_map<int,int> &m){ if(!root) return; m[root -> val]++; if(!root -> left and !root -> right){ int oddCnt = 0; for(auto it : m){ if(it.second % 2 != 0) oddCnt++; } if(oddCnt <= 1) ans++; } dfs(root -> left,ans,m); dfs(root -> right,ans,m); m[root -> val]--; } public: int pseudoPalindromicPaths (TreeNode* root) { if(root == NULL) return 0; int ans = 0; unordered_map<int,int> m; dfs(root,ans,m); return ans; } };
var pseudoPalindromicPaths = function(root) { if(!root) return 0; // if even it's zero or it's power of two when odd const ways = (r = root, d = 0) => { if(!r) return 0; d = d ^ (1 << r.val); // leaf if(r.left == r.right && r.left == null) { const hasAllEven = d == 0; const hasOneOdd = (d ^ (d & -d)) == 0; return Number(hasEven || hasOneOdd); } return ways(r.left, d) + ways(r.right, d); } return ways(); };
Pseudo-Palindromic Paths in a Binary Tree
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. &nbsp; Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4 Example 2: Input: matrix = [["0","1"],["1","0"]] Output: 1 Example 3: Input: matrix = [["0"]] Output: 0 &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 300 matrix[i][j] is '0' or '1'.
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[-1]) dp = [[0] * n for _ in range(m)] max_area = 0 for i in range(m): for j in range(n): if i - 1 < 0 or j - 1 < 0: if matrix[i][j] == '1': dp[i][j] = 1 else: if matrix[i][j] == '1': dp[i][j] = 1 + min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) max_area = max(max_area, dp[i][j] ** 2) return max_area
class Solution { public int maximalSquare(char[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[][] dp = new int[m][n]; int max = 0; for (int i = 0; i < m; i++) { dp[i][0] = matrix[i][0] - 48; if (matrix[i][0] == '1') max = 1; } for (int i = 0; i < n; i++) { dp[0][i] = matrix[0][i] - 48; if (matrix[0][i] == '1') max = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j] == '1') { dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1; if (dp[i][j] > max) { max = dp[i][j]; } } } } return max * max; } }
class Solution { public: int dp[305][305]; int ans; int getMax(vector<vector<char>>& mat, int i, int j){ int n=mat.size(), m=mat[0].size(); if(i>=n || j>=m) return 0; if(dp[i][j] != -1) return dp[i][j]; // getting min of the perfect squares formed by left adjacent, right adjacent, cross adjacent // +1 for including current dp[i][j] = min({getMax(mat, i, j+1), getMax(mat, i+1, j), getMax(mat, i+1, j+1)}) + 1; // There are no perfect squares if mat[i][j] is zero if(mat[i][j] == '0') dp[i][j] = 0; // final ans = max(ans, current_max); ans = max(ans, dp[i][j]); return dp[i][j]; } int maximalSquare(vector<vector<char>>& matrix) { memset(dp, -1, sizeof(dp)); ans = 0; getMax(matrix, 0, 0); return ans*ans; } };
var maximalSquare = function(matrix) { let max = 0; const height = matrix.length-1; const width = matrix[0].length-1; for (let i=height; i>=0; i--) { for (let j=width; j>=0; j--) { const right = j < width ? Number(matrix[i][j+1]) : 0; const diag = i < height && j < width ? Number(matrix[i+1][j+1]) : 0 const bottom = i < height ? Number(matrix[i+1][j]) : 0; matrix[i][j] = matrix[i][j] === '0' ? 0 : Math.min(right, diag, bottom) + 1; max = Math.max(max, matrix[i][j] * matrix[i][j]); } } return max; };
Maximal Square
A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '. A token is a valid word if all three of the following are true: It only contains lowercase letters, hyphens, and/or punctuation (no digits). There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid). There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid). Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!". Given a string sentence, return the number of valid words in sentence. &nbsp; Example 1: Input: sentence = "cat and dog" Output: 3 Explanation: The valid words in the sentence are "cat", "and", and "dog". Example 2: Input: sentence = "!this 1-s b8d!" Output: 0 Explanation: There are no valid words in the sentence. "!this" is invalid because it starts with a punctuation mark. "1-s" and "b8d" are invalid because they contain digits. Example 3: Input: sentence = "alice and bob are playing stone-game10" Output: 5 Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing". "stone-game10" is invalid because it contains digits. &nbsp; Constraints: 1 &lt;= sentence.length &lt;= 1000 sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','. There will be at least&nbsp;1 token.
import re class Solution: def countValidWords(self, sentence: str) -> int: # parse and get each word from sentence words = sentence.split() # regular expression pattern for valid words pattern = re.compile( r'^([a-z]+\-?[a-z]+[!\.,]?)$|^([a-z]*[!\.,]?)$' ) # valid word count count = 0 # scan each word from word pool for word in words: # judge whether current word is valid or not match = re.match(pattern, word) if match: count+=1 return count
class Solution { public int countValidWords(String sentence) { String regex = "^([a-z]+(-?[a-z]+)?)?(!|\\.|,)?$"; String r2 = "[^0-9]+"; String[] arr = sentence.split("\\s+"); int ans = 0; for(String s: arr) { if(s.matches(regex) && s.matches(r2)) { ans++; //System.out.println(s); } } return ans; } }
#include <regex> class Solution { public: int countValidWords(string sentence) { int count = 0; // Defining the regex pattern regex valid_word("[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?"); // splitting the sentence to words stringstream s(sentence); string word; while(getline(s, word, ' ')) { // Checking if the word matches the regex pattern if(word != "" && regex_match(word, valid_word)){ ++count; } } return count; } };
/** * @param {string} sentence * @return {number} */ var countValidWords = function(sentence) { let list = sentence.split(' ') let filtered = list.filter(s => { if (/\d/.test(s) || s === '') return false //removes anything with numbers or is blank if (/^[!,.]$/.test(s)) return true //punctuation only if (/^\w+[!,.]?$/.test(s)) return true //word + optional punctuation if (/^\w+[-]?\w+[!,.]?$/.test(s)) return true //word + optional hypen + word + optional punctuation return false }) return filtered.length };
Number of Valid Words in a Sentence
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) &lt;= k. &nbsp; Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2,3,1,2,3], k = 2 Output: false &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -109 &lt;= nums[i] &lt;= 109 0 &lt;= k &lt;= 105
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for i, n in enumerate(nums): if n in seen and i - seen[n] <= k: return True seen[n] = i return False
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) { return true; } map.put(nums[i], i); } return false; } }
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> m; for(int i=0;i<nums.size();i++){ if(m.count(nums[i]) && i-m[nums[i]]<=k) return true; m[nums[i]]=i; } return false; } };
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function(nums, k) { const duplicateCheck = {}; let isValid = false; for(var indexI=0; indexI<nums.length;indexI++){ if(duplicateCheck[nums[indexI]] > -1) { if(Math.abs(duplicateCheck[nums[indexI]] - indexI) <= k) { isValid = true; break; } } duplicateCheck[nums[indexI]] = indexI; } return isValid; };
Contains Duplicate II
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1. &nbsp; Example 1: Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] Example 2: Input: nums = [1,1,1] Output: 0 &nbsp; Constraints: n == nums.length 1 &lt;= nums.length &lt;= 105 -109 &lt;= nums[i] &lt;= 109 The answer is guaranteed to fit in a 32-bit integer.
class Solution: def minMoves(self, nums: List[int]) -> int: return sum(nums)-min(nums)*len(nums)
class Solution { public int minMoves(int[] nums) { int min=Integer.MAX_VALUE; int count=0; for(int i:nums) min=Math.min(i,min); for(int i=0;i<nums.length;i++) { count+=nums[i]-min; } return count; } }
class Solution { public: int minMoves(vector<int>& nums) { // sorting the array to get min at the first sort(nums.begin(), nums.end()); int cnt = 0, n = nums.size(); // Now we have to make min equal to every number and keep adding the count for(int i = 1; i < n; i++) cnt += nums[i] - nums[0]; return cnt; } };
var minMoves = function(nums) { let minElm = Math.min(...nums); let ans = 0; for(let i=0; i<nums.length; i++){ ans += (nums[i]-minElm) } return ans };
Minimum Moves to Equal Array Elements
A password is said to be strong if it satisfies all the following criteria: It has at least 8 characters. It contains at least one lowercase letter. It contains at least one uppercase letter. It contains at least one digit. It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&amp;*()-+". It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not). Given a string password, return true if it is a strong password. Otherwise, return false. &nbsp; Example 1: Input: password = "IloveLe3tcode!" Output: true Explanation: The password meets all the requirements. Therefore, we return true. Example 2: Input: password = "Me+You--IsMyDream" Output: false Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false. Example 3: Input: password = "1aB!" Output: false Explanation: The password does not meet the length requirement. Therefore, we return false. &nbsp; Constraints: 1 &lt;= password.length &lt;= 100 password consists of letters, digits, and special characters: "!@#$%^&amp;*()-+".
class Solution: def strongPasswordCheckerII(self, pwd: str) -> bool: return ( len(pwd) > 7 and max(len(list(p[1])) for p in groupby(pwd)) == 1 and reduce( lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0 ) == 15 )
class Solution { public boolean strongPasswordCheckerII(String password) { HashSet<Integer> intAscii = new HashSet<>(); String specialCharacters = "!@#$%^&*()-+"; for (int i = 0; i < specialCharacters.length(); i++) { int ascii = specialCharacters.charAt(i); intAscii.add(ascii); } if(password.length() < 8){ return false; } boolean small = false; boolean large = false; boolean numbers = false; boolean specialChars = false; for(int i = 0 ; i < password.length() ; i++){ int ascii = (int)(password.charAt(i)); if(ascii <= 90 && ascii>=65){ large = true; } if(ascii <= 122 && ascii>=97){ small = true; } if(ascii <=57 && ascii >=48){ numbers = true; } if(intAscii.contains(ascii)){ specialChars = true; } if(i> 0 && password.charAt(i)== password.charAt(i-1)){ return false; } } if(large == false || small == false || numbers == false || specialChars ==false){ return false; } return true; } }
class Solution { public: bool strongPasswordCheckerII(string password) { if(password.size() < 8) //8 char length return false; bool lower = 0, upper = 0; bool digit = 0, special = 0; for(int i=0; i<password.size(); i++){ //check rest conditions if(i>0 && password[i] == password[i-1]) //check duplicate return false; if(password[i] >=65 && password[i] <=90) upper = 1; //uppercase else if(password[i] >=97 && password[i] <=122) lower = 1; //lowercase else if(password[i] >=48 && password[i] <=57) digit = 1; //digit else //special char special = 1; } if(upper && lower && digit && special) return true; return false; } };
const checkLen = (password) => password.length >= 8; const checkSmallLetter = (password) => { for(let i=0;i<password.length;i++){ const ind = password.charCodeAt(i); if(ind > 96 && ind < 123){ return true; } } return false; } const checkCapitalLetter = (password) => { for(let i=0;i<password.length;i++){ const ind = password.charCodeAt(i); if(ind > 64 && ind < 91){ return true; } } return false; } const checkDigit = (password) => { for(let i=0;i<password.length;i++){ const ind = password.charCodeAt(i); if(ind > 47 && ind < 58){ return true; } } return false; } const checkSpecialChar = (password) => { const str = "!@#$%^&*()-+"; for(let i=0;i<str.length;i++){ if(password.includes(str[i])) return true; } return false; } const checkAdjacentMatches = (password) => { for(let i=1;i<password.length;i++){ if(password[i] === password[i-1]) return false; } return true; } var strongPasswordCheckerII = function(password) { const lenValidity = checkLen(password); const smallLetterValidity = checkSmallLetter(password); const capitalLetterValidity = checkCapitalLetter(password); const digitValidity = checkDigit(password); const specialCharValidity = checkSpecialChar(password); const adjacentMatchesValidity = checkAdjacentMatches(password); const passwordIsStrong = lenValidity && smallLetterValidity && capitalLetterValidity && digitValidity && specialCharValidity && adjacentMatchesValidity; return passwordIsStrong; };
Strong Password Checker II
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph. &nbsp; Example 1: Input: nums = [4,6,15,35] Output: 4 Example 2: Input: nums = [20,50,9,63] Output: 2 Example 3: Input: nums = [2,3,6,7,4,12,21,39] Output: 8 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 1 &lt;= nums[i] &lt;= 105 All the values of nums are unique.
class Solution: def largestComponentSize(self, nums: List[int]) -> int: def find(node): if parent[node] == -1: return node else: parent[node] = find(parent[node]) return parent[node] def union(idx1,idx2): par1,par2 = find(idx1),find(idx2) if par1!=par2: if rank[par1] > rank[par2]: parent[par2] = par1 elif rank[par2] > rank[par1]: parent[par1] = par2 else: parent[par2] = par1 rank[par1] += 1 n = len(nums) parent = defaultdict(lambda:-1) rank = defaultdict(lambda:0) for i in range(n): limit = int(nums[i]**0.5) for j in range(2,limit+1): if nums[i] % j == 0: union(nums[i],j) union(nums[i],nums[i]//j) count = defaultdict(lambda:0) best = -1 for num in nums: par = find(num) tmp = count[par] + 1 if tmp > best: best = tmp count[par] = tmp return best
class Solution { public int largestComponentSize(int[] nums) { int maxNum = getMaxNum(nums); Map<Integer, Integer> numToFirstPrimeFactor = new HashMap<>(); DisjointSet ds = new DisjointSet(maxNum + 1); for (int num : nums) { if (num == 1) { continue; } List<Integer> primeFactors = getPrimeFactors(num); int firstPrimeFactor = primeFactors.get(0); numToFirstPrimeFactor.put(num, firstPrimeFactor); for (int i = 1; i < primeFactors.size(); i++) { ds.union(primeFactors.get(i-1), primeFactors.get(i)); } } Map<Integer, Integer> componentToSize = new HashMap<>(); int maxSize = 0; for (int num : nums) { if (num == 1) { continue; } int firstPrimeFactor = numToFirstPrimeFactor.get(num); int component = ds.find(firstPrimeFactor); int size = componentToSize.getOrDefault(component, 0); componentToSize.put(component, ++size); maxSize = Math.max(maxSize, size); } return maxSize; } public int getMaxNum(int[] nums) { int maxNum = 0; for (int num : nums) { maxNum = Math.max(maxNum, num); } return maxNum; } public List<Integer> getPrimeFactors(int num) { List<Integer> primeFactors = new ArrayList<>(); // even prime factor i.e. 2 if((num & 1) == 0){ primeFactors.add(2); do{ num >>= 1; }while((num & 1) == 0); } // odd prime factors int primeFactor = 3; while(num != 1 && primeFactor*primeFactor <= num){ if(num % primeFactor == 0){ primeFactors.add(primeFactor); do{ num /= primeFactor; }while(num % primeFactor == 0); } primeFactor += 2; } // num is prime if(num != 1){ primeFactors.add(num); } return primeFactors; } } class DisjointSet { int[] root; int[] rank; public DisjointSet(int size) { root = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { root[i] = i; rank[i] = 1; } } public int find(int x) { while (x != root[x]) { root[x] = root[root[x]]; x = root[x]; } return x; } public void union(int x, int y) { int rootX = find(x); int rootY = find(y); if (rootX == rootY) { return; } if (rank[rootX] > rank[rootY]) { root[rootY] = rootX; } else if (rank[rootX] < rank[rootY]) { root[rootX] = rootY; } else { root[rootY] = rootX; rank[rootX]++; } } }
class Solution { private: vector<bool> sieve(int n) { vector<bool> prime(n + 1); for (int i = 0; i <= n; i++) prime[i] = 1; for (int p = 2; p * p <= n; p++) { if (prime[p] == 1) { for (int i = p * p; i <= n; i += p) prime[i] = 0; } } prime[1] = prime[0] = 0; return prime; } vector<int> factors(int n, vector<int> &primelist) { vector<int> facs; for (int i = 0; primelist[i] * primelist[i] <= n && i < primelist.size(); i++) { if (n % primelist[i] == 0) { facs.push_back(primelist[i]); while (n % primelist[i] == 0) { n /= primelist[i]; } } } if (n > 1) facs.push_back(n); return facs; } void dfs(vector<vector<int>> &gr, int node, vector<int> &vis, int &compSize) { if(vis[node]) return; vis[node] = 1; compSize++; for(auto x : gr[node]) { dfs(gr, x, vis, compSize); } } public: int largestComponentSize(vector<int>& nums) { int n = nums.size(); vector<vector<int>> gr(n); vector<bool> prime = sieve(1e5 + 6); vector<int> primelist; // Getting all the primes till 10^5 as maximum value of nums[i] is 10^5 for (int i = 2; i <= 1e5 + 5; i++) if (prime[i]) primelist.push_back(i); unordered_map<int, int> m; // to store the index of the node with prime factor x for(int i = 0; i < n; i++) { vector<int> facs = factors(nums[i], primelist); for(auto j : facs) { if(m.find(j) == m.end()) { // prime factor had not occured before m[j] = i; // j is the prime factor and its index is i } else { // prime factor has already been seen before in a previous number and nums[i] is connected to that number gr[i].push_back(m[j]); gr[m[j]].push_back(i); } } } int ans = 0; vector<int> vis(n); for(int i = 0; i < n; i++) { // running a simple dfs to calculate the maximum component size if(!vis[i]) { int compSize = 0; dfs(gr, i, vis, compSize); ans = max(ans, compSize); } } return ans; } };
var largestComponentSize = function(nums) { const rootByFactor = new Map(); const parents = new Array(nums.length); function addFactor(i, factor) { if (rootByFactor.has(factor)) { let r = rootByFactor.get(factor); while (parents[i] != i) i = parents[i]; while (parents[r] != r) r = parents[r]; parents[i] = r; } rootByFactor.set(factor, parents[i]); } for (const [i, num] of nums.entries()) { parents[i] = i; addFactor(i, num); for (let factor = 2; factor * factor <= num; ++factor) { if (num % factor == 0) { addFactor(i, factor); addFactor(i, num / factor); } } } let largest = 0; const sums = new Array(nums.length).fill(0); for (let r of parents) { while (parents[r] != r) r = parents[r]; largest = Math.max(largest, ++sums[r]); } return largest; };
Largest Component Size by Common Factor
A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "". Note that the strings are considered in the order in which they appear in the array. &nbsp; Example 1: Input: arr = ["d","b","c","b","c","a"], k = 2 Output: "a" Explanation: The only distinct strings in arr are "d" and "a". "d" appears 1st, so it is the 1st distinct string. "a" appears 2nd, so it is the 2nd distinct string. Since k == 2, "a" is returned. Example 2: Input: arr = ["aaa","aa","a"], k = 1 Output: "aaa" Explanation: All strings in arr are distinct, so the 1st string "aaa" is returned. Example 3: Input: arr = ["a","b","a"], k = 3 Output: "" Explanation: The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "". &nbsp; Constraints: 1 &lt;= k &lt;= arr.length &lt;= 1000 1 &lt;= arr[i].length &lt;= 5 arr[i] consists of lowercase English letters.
class Solution: def kthDistinct(self, arr: List[str], k: int) -> str: hash_map = {} for string in arr: hash_map[string] = hash_map.get(string, 0) + 1 for string in arr: if hash_map[string] == 1: k -= 1 if k == 0: return string return ""
class Solution { public String kthDistinct(String[] arr, int k) { Map<String,Integer> map=new HashMap<>(); for(String s:arr){ if(map.containsKey(s)) map.put(s,map.get(s)+1); else map.put(s,1); } int i=0; for(String s:arr){ if(map.get(s)==1 && ++i==k){ return s; } } return ""; } }
class Solution { public: string kthDistinct(vector<string>& arr, int k) { unordered_map<string,int>m; for(int i=0;i<arr.size();i++) { m[arr[i]]++; } for(int i=0;i<arr.size();i++) { if(m[arr[i]]==1) { k--; } if(k==0 && m[arr[i]]==1) { return arr[i]; } } return ""; } };
var kthDistinct = function(arr, k) { const map = {} // used for arr occurences const distinctArr = [] // store the distinct values (only appearing once) // increment the occurence to the map arr.forEach(letter => map[letter] = map[letter] + 1 || 1) // store all the distinct values in order for (let [key, val] of Object.entries(map)) if (val == 1) distinctArr.push(key) // return the key or empty string return distinctArr[k-1] || "" }; ~``
Kth Distinct String in an Array
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. &nbsp; Example 1: Input: matrix = [ &nbsp; [0,1,1,1], &nbsp; [1,1,1,1], &nbsp; [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7. &nbsp; Constraints: 1 &lt;= arr.length&nbsp;&lt;= 300 1 &lt;= arr[0].length&nbsp;&lt;= 300 0 &lt;= arr[i][j] &lt;= 1
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m = len(matrix) n = len(matrix[0]) dp = [[0 for _ in range(n)] for _ in range(m)] total = 0 for i in range(m): for j in range(n): if i == 0: dp[i][j] = matrix[0][j] elif j == 0: dp[i][j] = matrix[i][0] else: if matrix[i][j] == 1: dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j]) total += dp[i][j] return total
class Solution { public int countSquares(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[][] res = new int[m][n]; for(int j=0; j<n; j++) res[0][j] = matrix[0][j]; for(int i=0; i<m; i++) res[i][0] = matrix[i][0]; for(int i=1; i<m; i++){ for(int j=1; j<n; j++){ if(matrix[i][j] == 1){ res[i][j] = Math.min(res[i-1][j], Math.min(res[i][j-1], res[i-1][j-1])) + 1; } else res[i][j] = 0; } } int sum = 0; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ sum += res[i][j]; } } return sum; } }
class Solution { public: int solve( vector<vector<int>>&mat , int n , int m , vector<vector<int>>&dp){ if(n<0 or m<0 or mat[n][m] == 0 ) return 0; if(dp[n][m] != -1 ) return dp[n][m]; return dp[n][m] = ( 1 + min({ solve( mat , n-1 , m , dp ), solve(mat , n-1 , m-1 , dp ), solve(mat , n , m-1 , dp ) })); } int countSquares(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); int ans = 0 ; // vector<vector<int>>dp(n , vector<int>(m,-1)); // for(int i = 0 ; i<n ; ++i ){ // for(int j= 0 ; j<m ; ++j ){ // ans += solve( matrix,i , j , dp ); // } // } vector<vector<int>>dp(n , vector<int>(m, 0)); for(int i = 0 ; i<n ; ++i ){ for(int j = 0 ; j<m ; ++j ){ if(i==0 || j ==0 ){ dp[i][j] = matrix[i][j]; } else{ if(matrix[i][j]) dp[i][j] = 1 + min({dp[i-1][j] , dp[i-1][j-1] , dp[i][j-1]}); } } } for(auto x : dp ){ for(auto y : x ) ans += y; } return ans ; } };
/** * @param {number[][]} matrix * @return {number} */ var countSquares = function(matrix) { let count = 0; for (let i = 0; i < matrix.length; ++i) { for (let j = 0; j < matrix[0].length; ++j) { if (matrix[i][j] === 0) continue; if (i > 0 && j > 0) { matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]); } count += matrix[i][j]; } } return count; };
Count Square Submatrices with All Ones
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". &nbsp; Example 1: Input: s = "aabca" Output: 3 Explanation: The 3 palindromic subsequences of length 3 are: - "aba" (subsequence of "aabca") - "aaa" (subsequence of "aabca") - "aca" (subsequence of "aabca") Example 2: Input: s = "adc" Output: 0 Explanation: There are no palindromic subsequences of length 3 in "adc". Example 3: Input: s = "bbcbaba" Output: 4 Explanation: The 4 palindromic subsequences of length 3 are: - "bbb" (subsequence of "bbcbaba") - "bcb" (subsequence of "bbcbaba") - "bab" (subsequence of "bbcbaba") - "aba" (subsequence of "bbcbaba") &nbsp; Constraints: 3 &lt;= s.length &lt;= 105 s consists of only lowercase English letters.
class Solution(object): def countPalindromicSubsequence(self, s): d=defaultdict(list) for i,c in enumerate(s): d[c].append(i) ans=0 for el in d: if len(d[el])<2: continue a=d[el][0] b=d[el][-1] ans+=len(set(s[a+1:b])) return(ans)
class Solution { public int countPalindromicSubsequence(String s) { int n = s.length(); char[] chArr = s.toCharArray(); int[] firstOcc = new int[26]; int[] lastOcc = new int[26]; Arrays.fill(firstOcc, -1); Arrays.fill(lastOcc, -1); for(int i = 0; i < n; i++){ char ch = chArr[i]; if(firstOcc[ch - 'a'] == -1){ firstOcc[ch - 'a'] = i; } lastOcc[ch - 'a'] = i; } int ans = 0, count = 0; boolean[] visited; // check for each character ( start or end of palindrome ) for(int i = 0; i < 26; i++){ int si = firstOcc[i]; // si - starting index int ei = lastOcc[i]; // ei - ending index visited = new boolean[26]; count = 0; // check for unique charcters ( middle of palindrome ) for(int j = si + 1; j < ei; j++){ if(!visited[chArr[j] - 'a']){ visited[chArr[j] - 'a'] = true; count++; } } ans += count; } return ans; } }
class Solution { public: int countPalindromicSubsequence(string s) { vector<pair<int, int> > v(26, {-1, -1} ); //to store first occurance and last occurance of every alphabet. int n = s.length(); //size of the string for (int i = 0 ; i< n ;i++ ){ if (v[s[i] - 'a'].first == -1 ) v[s[i] - 'a'].first = i; // storing when alphabet appered first time. else v[s[i] - 'a'].second = i; // else whenever it appears again. So that the last occurrence will be stored at last. } int ans = 0 ; for (int i = 0 ; i <26 ;i++ ){ //traversing over all alphabets. if (v[i].second != -1 ){ //only if alphabet occured second time. unordered_set<char> st; //using set to keep only unique elements between the range. for (int x = v[i].first + 1 ; x < v[i].second ; x++ ) st.insert(s[x]); // set keeps only unique elemets. ans += ((int)st.size()); // adding number of unique elements to the answer. } } return ans; } };
var countPalindromicSubsequence = function(s) { const charToIndices = {}; for (let i = 0; i < s.length; i++) { const char = s[i]; if (charToIndices[char]) { charToIndices[char].push(i); } else { charToIndices[char] = [i]; } } let count = 0; for (const currChar in charToIndices) { if (charToIndices[currChar].length < 2) continue; const currCharIndices = charToIndices[currChar]; const firstIndex = currCharIndices[0]; const lastIndex = currCharIndices[currCharIndices.length - 1]; for (const char in charToIndices) { const indices = charToIndices[char]; let lo = 0; let hi = indices.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (indices[mid] <= firstIndex) { lo = mid + 1; } else { hi = mid; } } if (indices[lo] && indices[lo] < lastIndex) { count++; } } } return count; };
Unique Length-3 Palindromic Subsequences
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group. For the last group, if the string does not have k characters remaining, a character fill is used to complete the group. Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure. &nbsp; Example 1: Input: s = "abcdefghi", k = 3, fill = "x" Output: ["abc","def","ghi"] Explanation: The first 3 characters "abc" form the first group. The next 3 characters "def" form the second group. The last 3 characters "ghi" form the third group. Since all groups can be completely filled by characters from the string, we do not need to use fill. Thus, the groups formed are "abc", "def", and "ghi". Example 2: Input: s = "abcdefghij", k = 3, fill = "x" Output: ["abc","def","ghi","jxx"] Explanation: Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi". For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice. Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx". &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s consists of lowercase English letters only. 1 &lt;= k &lt;= 100 fill is a lowercase English letter.
class Solution: def divideString(self, s: str, k: int, fill: str) -> List[str]: l, i, N = [], 0, len(s) while i<N: l.append(s[i:i+k]) i += k last = l[-1] if(len(last)<k): l[-1] += fill*(k-len(last)) return l
class Solution { public String[] divideString(String s, int k, char fill) { int rem = 0; if( s.length() % k != 0){ rem = k - s.length() % k; //counting the total positions where we have to fill the char "fill". } for(int i = 0; i < rem; i++){ s = s+fill; //appending the char to the String } String[] strs = new String[s.length()/k]; //the length will be String length / K because we are making pair of k length Strings. int index = 0; //index for array. for(int i = 0; i < s.length(); i+=k){ strs[index] = s.substring(i, i+k); //substing of current element to Kth element. index++; } return strs; } }
class Solution { public: vector<string> divideString(string s, int k, char fill) { vector<string> v; for(int i=0;i<s.size();i=i+k) { string t=s.substr(i,k); // make substring of size atmost k if(t.size()==k) // if size if k then push { v.push_back(t); continue; } int l=t.size(); // if it is the last group and size if less than k for(int j=0;j<(k-l);j++) // add fill char to t to make size k t+=fill; v.push_back(t); } return v; } };
/** * @param {string} s * @param {number} k * @param {character} fill * @return {string[]} */ var divideString = function(s, k, fill) { var ans=[]; for(let i=0;i<s.length;i+=k) { ans.push(s.substring(i,i+k)); } let str=ans[ans.length-1]; if(str.length==k) { return ans; } for(let i=str.length;i<k;i++) { ans[ans.length-1]+=fill; } return ans; };
Divide a String Into Groups of Size k
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Complete the next task from tasks, or Take a break. Return the minimum number of days needed to complete all tasks. &nbsp; Example 1: Input: tasks = [1,2,1,2,3,1], space = 3 Output: 9 Explanation: One way to complete all tasks in 9 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. Day 7: Take a break. Day 8: Complete the 4th task. Day 9: Complete the 5th task. It can be shown that the tasks cannot be completed in less than 9 days. Example 2: Input: tasks = [5,8,8,5], space = 2 Output: 6 Explanation: One way to complete all tasks in 6 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. It can be shown that the tasks cannot be completed in less than 6 days. &nbsp; Constraints: 1 &lt;= tasks.length &lt;= 105 1 &lt;= tasks[i] &lt;= 109 1 &lt;= space &lt;= tasks.length
import math class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: count_dict = {} total_days = 0 for task in tasks: if task not in count_dict: count_dict[task] = -math.inf total_days = max(total_days + 1, count_dict[task] + space + 1) count_dict[task] = total_days return total_days
class Solution { public long taskSchedulerII(int[] tasks, int space) { HashMap<Integer, Long> map = new HashMap<>(); long day = 0; for (int item : tasks) { if (map.containsKey(item) && map.get(item) > day) day = map.get(item); day++; map.put(item, day + space); } return day; } }
class Solution { public: long long taskSchedulerII(vector<int>& tasks, int space) { unordered_map<int,long long int> hash; long long int curday=0; for(int i=0;i<tasks.size();i++){ if(hash.count(tasks[i])) curday=max(curday,hash[tasks[i]]); hash[tasks[i]]=curday+space+1; curday+=1; } return curday; } };
var taskSchedulerII = function(tasks, n) { const config = {}; let totalIteration = 0; let currentTime = 0; for (const iterator of tasks) { currentTime++; if (!config[iterator]) { config[iterator] = 0; } else { if (config[iterator] > currentTime) { let difference = config[iterator] - currentTime; totalIteration += difference; currentTime += difference; } } config[iterator] = currentTime + n + 1; totalIteration++; } return totalIteration; };
Task Scheduler II
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard. &nbsp; Example 1: Input: text = "hello world", brokenLetters = "ad" Output: 1 Explanation: We cannot type "world" because the 'd' key is broken. Example 2: Input: text = "leet code", brokenLetters = "lt" Output: 1 Explanation: We cannot type "leet" because the 'l' and 't' keys are broken. Example 3: Input: text = "leet code", brokenLetters = "e" Output: 0 Explanation: We cannot type either word because the 'e' key is broken. &nbsp; Constraints: 1 &lt;= text.length &lt;= 104 0 &lt;= brokenLetters.length &lt;= 26 text consists of words separated by a single space without any leading or trailing spaces. Each word only consists of lowercase English letters. brokenLetters consists of distinct lowercase English letters.
class Solution: def canBeTypedWords(self, text: str, brokenLetters: str) -> int: text = text.split() length = len(text) brokenLetters = set(brokenLetters) for word in text: for char in word: if char in brokenLetters: length -= 1 break return length
class Solution { public int canBeTypedWords(String text, String brokenLetters) { int count = 1; boolean isBad = false; for (char c : text.toCharArray()) { if (c == ' ') { isBad = false; count++; } else { if (!isBad && brokenLetters.indexOf(c) != -1) { isBad = true; count--; } } } return count; } }
class Solution { public: int canBeTypedWords(string text, string brokenLetters) { vector<int> ch(26,0); // store the broken letters in ch vector for(char c: brokenLetters){ ch[c-'a']=1; } int cnt=0,ans=0; //traversing the text string for(int i=0;i<text.length();i++){ //if char is ' ' means that we got a new word if(text[i]==' '){ // cnt remain 0 means that there is no broken letter in this word if(cnt==0) ans++; cnt=0; //reinitialize cnt to 0 as new word start from here }else if(ch[text[i]-'a']==1){ //if char is present in ch then just increment the cnt cnt++; } } //for last word in string if(cnt==0) ans++; return ans; } };
var canBeTypedWords = function(text, brokenLetters) { let regexp="["+brokenLetters+"]\+" let word=text.split(" "), count=0; for(let i=0; i<word.length; i++){ let work=true; // if matches, means word[i] contains malfunction letters. if(word[i].match(regexp)){work=false}; if(work){count++}; } return count; };
Maximum Number of Words You Can Type
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. &nbsp; Example 1: Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] Explanation:&nbsp;The input board is shown above and the only valid solution is shown below: &nbsp; Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution.
class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ full = set('123456789') # lets keep rows, columns and boxes sets in hashmaps rows = [set() for _ in range(9)] cols = [set() for _ in range(9)] boxes = [[set() for _ in range(3)] for _ in range(3)] # and remember empty cell to fill them in empty = set() for i in range(9): for j in range(9): if board[i][j] == '.': empty.add((i,j)) continue rows[i].add(board[i][j]) cols[j].add(board[i][j]) boxes[i//3][j//3].add(board[i][j]) def options(i, j): """returns possible options for i,j intersecting options from row, col and box""" return ( (full - rows[i]) & (full - cols[j]) & (full - boxes[i//3][j//3]) ) psingle = True # did we have single option decisions in previos traverse while empty: single = False # for single option decisions in this traverse for i, j in deepcopy(empty): opts = options(i, j) if len(opts) == 0: # we've made a wrong assumption - sudoku is unsolvable return None, None elif len(opts) == 2 and not psingle: # we have no single-option decisions so have to take an assumption board1 = deepcopy(board) board1[i][j] = opts.pop() board1, empty1 = self.solveSudoku(board1) if board1 != None: # if solved - we're done empty = empty1 for i, b1 in enumerate(board1): board[i] = b1 # have to modify initial list, not just replace the reference return board, empty if len(opts) == 1: # hey, we have a predetermined choice. nice single = True board[i][j] = opts.pop() empty.remove((i, j)) rows[i].add(board[i][j]) cols[j].add(board[i][j]) boxes[i//3][j//3].add(board[i][j]) psingle = single return board, empty ```
class Solution { public void solveSudoku(char[][] board) { solve(board); } boolean solve(char board[][]){ for(int i = 0; i<board.length; i++){ for(int j = 0; j<board[0].length; j++){ if(board[i][j] == '.') { for(char c = '1'; c<='9'; c++){ if(isValid(board, c, i, j) == true){ board[i][j] = c; if(solve(board) == true) return true; else board[i][j] = '.'; } } return false; } } } return true; } boolean isValid(char board[][], char c, int row, int col){ for(int i = 0; i<9; i++){ if(board[row][i] == c) return false; if(board[i][col] == c) return false; if(board[3 * (row/3) + (i/3)][3 * (col/3) + (i % 3)] == c) return false; } return true; } }
class Solution { public: bool issafe(vector<vector<char>> &board,int row,int col,char c) { for(int i=0;i<9;i++) { if(board[row][i]==c) return 0; if(board[i][col]==c) return 0; if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c) return 0; } return 1; } bool solve(vector<vector<char>> & board) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(board[i][j]=='.') { for(char c='1';c<='9';c++) { if(issafe(board,i,j,c)) { board[i][j]=c; if(solve(board)==1) return 1; else board[i][j]='.'; } } return 0; } } } return 1; } void solveSudoku(vector<vector<char>>& board) { solve(board); } };
var solveSudoku = function(board) { let intBoard = convertBoardToInteger(board); let y = 0, x = 0; while (y <= 8){ x = 0; while (x <= 8){ if (isFreeIndex(board, x, y)){ intBoard[y][x]++; while (!isPossibleValue(intBoard, x, y) && intBoard[y][x] < 10){ intBoard[y][x]++; }; if (intBoard[y][x] > 9){ intBoard[y][x] = 0; let a = retraceBoard(board, x, y); x = a[0], y = a[1]; x--; } } x++; } y++; } convertIntBoardToString(intBoard, board); } var isFreeIndex = function(board, x, y){ return (board[y][x] == '.'); } var isPossibleValue = function(intBoard, x, y){ return (isUniqueInColumn(intBoard, x, y) && isUniqueOnRow(intBoard, x, y) && isUniqueInBox(intBoard, x, y)) } var isUniqueOnRow = function(intBoard, x, y){ for (let i = 0;i<9;i++){ if (intBoard[i][x] == intBoard[y][x] && i != y){ return false; } } return true; } var isUniqueInColumn = function(intBoard, x, y){ for (let i = 0;i<9;i++){ if (intBoard[y][i] == intBoard[y][x] && i != x){ return false; } } return true; } var isUniqueInBox = function(intBoard, x, y){ let startX = x - (x % 3); let startY = y - (y % 3); for (let i = startX; i < startX+3; i++){ for (let j = startY; j < startY+3; j++){ if (intBoard[j][i] == intBoard[y][x] && (i != x || j != y)){ return false; } } } return true; } var retraceBoard = function(board, x, y){ do { if (x > 0){ x--; } else { x = 8; y--; } } while (board[y][x] != '.'); return [x,y]; } var convertBoardToInteger = function(board){ let intBoard = new Array(8); for (let y = 0;y<9;y++){ intBoard[y] = new Array(8); for (let x = 0;x < 9;x++){ intBoard[y][x] = parseInt(board[y][x]); if (!intBoard[y][x]) intBoard[y][x] = 0; } } return intBoard; } var convertIntBoardToString = function(intBoard, board){ for (let y = 0;y<9;y++){ for (let x = 0;x < 9;x++){ board[y][x] = intBoard[y][x].toString(); } } return board; }
Sudoku Solver
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times. &nbsp; Example 1: Input: answerKey = "TTFF", k = 2 Output: 4 Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". There are four consecutive 'T's. Example 2: Input: answerKey = "TFFT", k = 1 Output: 3 Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". In both cases, there are three consecutive 'F's. Example 3: Input: answerKey = "TTFTTFTT", k = 1 Output: 5 Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". In both cases, there are five consecutive 'T's. &nbsp; Constraints: n == answerKey.length 1 &lt;= n &lt;= 5 * 104 answerKey[i] is either 'T' or 'F' 1 &lt;= k &lt;= n
class Solution: def maxConsecutiveAnswers(self, string: str, k: int) -> int: result = 0 j = 0 count1 = k for i in range(len(string)): if count1 == 0 and string[i] == "F": while string[j] != "F": j+=1 count1+=1 j+=1 if string[i] == "F": if count1 > 0: count1-=1 if i - j + 1 > result: result = i - j + 1 j = 0 count2 = k for i in range(len(string)): if count2 == 0 and string[i] == "T": while string[j] != "T": j+=1 count2+=1 j+=1 if string[i] == "T": if count2 > 0: count2-=1 if i - j + 1 > result: result = i - j + 1 return result
class Solution { // Binary Search + Sliding Window fixed public int maxConsecutiveAnswers(String answerKey, int k) { int start = 1 ; int end = answerKey.length(); int max_length = 0 ; while(start <= end) { int mid = start+(end-start)/2 ; if(isMax(answerKey , k , mid)) { max_length = mid ; start = mid+1 ; }else { end = mid-1 ; } } return max_length ; } public boolean isMax(String answerKey , int k , int max_val) { int T_count = 0 ; int F_count = 0 ; int i = 0 ; int j = 0 ; while(j < answerKey.length()) { if(answerKey.charAt(j) == 'T') { T_count++ ; }else { F_count++ ; } if(j-i+1 == max_val) { if(Math.max(T_count, F_count)+k >= max_val) { return true ; } if(answerKey.charAt(i) == 'T') { T_count-- ; }else { F_count-- ; } i++ ; } j++ ; } return false ; } }
class Solution { public: int maxConsecutiveAnswers(string answerKey, int k) { return max(helper(answerKey,k,'T'),helper(answerKey,k,'F')); } int helper(string answerKey, int k,char c){ int start = 0; int end = 0; int count = 0; int ans = 0; while(end<answerKey.length()){ if(answerKey[end]==c)count++; while(count>k){ if(answerKey[start]==c)count--; start++; } ans = max(ans,end-start+1); end++; } return ans; } };
var maxConsecutiveAnswers = function(answerKey, k) { let [left, right, numOfTrue, numOfFalse, max] = new Array(5).fill(0); const moreChanges = () => numOfTrue > k && numOfFalse > k; while (right < answerKey.length) { if(answerKey[right] === 'T') numOfTrue++; if(answerKey[right] === 'F') numOfFalse++; while(moreChanges()) { if(answerKey[left] === 'T') numOfTrue--; if(answerKey[left] === 'F') numOfFalse--; left++; } max = Math.max(max, right - left + 1); right++; } return max; };
Maximize the Confusion of an Exam
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 &lt;= i &lt; j &lt; n and nums[i] &lt; nums[j]. Return the maximum difference. If no such i and j exists, return -1. &nbsp; Example 1: Input: nums = [7,1,5,4] Output: 4 Explanation: The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4. Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i &gt; j, so it is not valid. Example 2: Input: nums = [9,4,3,2] Output: -1 Explanation: There is no i and j such that i &lt; j and nums[i] &lt; nums[j]. Example 3: Input: nums = [1,5,2,10] Output: 9 Explanation: The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9. &nbsp; Constraints: n == nums.length 2 &lt;= n &lt;= 1000 1 &lt;= nums[i] &lt;= 109
class Solution: def maximumDifference(self, nums: List[int]) -> int: curmin = nums[0] diff = 0 for num in nums: diff = max(diff, num - curmin) curmin = min(curmin, num) return diff or -1
class Solution { public int maximumDifference(int[] nums) { if(nums.length < 2) return -1; int result = Integer.MIN_VALUE; int minValue = nums[0]; for(int i = 1; i < nums.length; i++) { if(nums[i] > minValue) result = Math.max(result, nums[i] - minValue); minValue = Math.min(minValue, nums[i]); } return result == Integer.MIN_VALUE ? -1 : result; } }
class Solution { public: int maximumDifference(vector<int>& nums) { int mn = nums[0], res = 0; for (int i = 1; i < nums.size(); i++) { res = max(res, nums[i] - mn); mn = min(mn, nums[i]); } return res == 0 ? -1 : res; } };
var maximumDifference = function(nums) { var diff=-1 for(let i=0;i<nums.length;i++){ for(let j=i+1;j<nums.length;j++){ if (nums[j]> nums[i]) diff=Math.max(nums[j]-nums[i],diff) } } return diff };
Maximum Difference Between Increasing Elements
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. &nbsp; Example 1: Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Example 2: Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]] &nbsp; Constraints: m == mat.length n == mat[i].length 1 &lt;= m, n &lt;= 100 1 &lt;= mat[i][j] &lt;= 100
class Solution: def diagonalSort(self, A: List[List[int]]) -> List[List[int]]: n, m, d = len(A), len(A[0]), defaultdict(list) any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m)) any(d[sum_].sort(reverse=1) for sum_ in d) return [[d[i-j].pop() for j in range(m)] for i in range(n)]
class Solution { public int[][] diagonalSort(int[][] mat) { int n = mat.length; int m = mat[0].length; for(int i=0;i<m;i++){ give(0,i,mat,n,m); } for(int i=1;i<n;i++){ give(i,0,mat,n,m); } return mat; } public void give(int i,int j,int[][] mat,int n,int m){ int[] dig = new int[Math.min(m-j,n-i)]; int r = i; int c = j; int k = 0; while(r<n && c<m){ dig[k] = mat[r][c]; r++; c++; k++; } Arrays.sort(dig); k = 0; while(i<n && j<m){ mat[i][j] = dig[k]; i++; j++; k++; } } }
class Solution { public: void sortmat(int i,int j,vector<vector<int>>& mat,int m,int n,vector<int>& temp){ if(i>=m || j>=n){ sort(temp.begin(),temp.end()); return ; } temp.push_back(mat[i][j]); sortmat(i+1,j+1,mat,m,n,temp); mat[i][j]=temp.back(); temp.pop_back(); } vector<vector<int>> diagonalSort(vector<vector<int>>& mat) { int m=mat.size(); int n=mat[0].size(); vector<int>temp; // For column for(int j=0;j<n;j++) sortmat(0,j,mat,m,n,temp); // For Row for(int i=1;i<m;i++) sortmat(i,0,mat,m,n,temp); return mat; } };
/** * @param {number[][]} mat * @return {number[][]} */ var diagonalSort = function(mat) { const res=new Array(mat.length); for(let i=0;i<mat.length;i++) res[i]=new Array(mat[i].length); for(let i=0;i<mat.length;i++){ for(let j=0;j<mat[i].length;j++){ if(i===0 || j===0){ const scale= i-j; let val=[],index=[]; for(let i=0;i<mat.length;i++){ for(let j=0;j<mat[i].length;j++){ if(scale===i-j){ val.push(mat[i][j]); index.push([i,j]); } } } val=val.sort((a,b)=>a-b); index.forEach(([x,y],id)=>res[x][y]=val[id]); } } } return res; };
Sort the Matrix Diagonally
A cell (r, c) of an excel sheet is represented as a string "&lt;col&gt;&lt;row&gt;" where: &lt;col&gt; denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. &lt;row&gt; is the row number r of the cell. The rth row is represented by the integer r. You are given a string s&nbsp;in&nbsp;the format "&lt;col1&gt;&lt;row1&gt;:&lt;col2&gt;&lt;row2&gt;", where &lt;col1&gt; represents the column c1, &lt;row1&gt; represents the row r1, &lt;col2&gt; represents the column c2, and &lt;row2&gt; represents the row r2, such that r1 &lt;= r2 and c1 &lt;= c2. Return the list of cells (x, y) such that r1 &lt;= x &lt;= r2 and c1 &lt;= y &lt;= c2. The cells should be represented as&nbsp;strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. &nbsp; Example 1: Input: s = "K1:L2" Output: ["K1","K2","L1","L2"] Explanation: The above diagram shows the cells which should be present in the list. The red arrows denote the order in which the cells should be presented. Example 2: Input: s = "A1:F1" Output: ["A1","B1","C1","D1","E1","F1"] Explanation: The above diagram shows the cells which should be present in the list. The red arrow denotes the order in which the cells should be presented. &nbsp; Constraints: s.length == 5 'A' &lt;= s[0] &lt;= s[3] &lt;= 'Z' '1' &lt;= s[1] &lt;= s[4] &lt;= '9' s consists of uppercase English letters, digits and ':'.
class Solution: def cellsInRange(self, s: str) -> List[str]: start, end = s.split(':') start_letter, start_num = start[0], int(start[-1]) end_letter, end_num = end[0], int(end[1]) alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') alphabet_slice = \ alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1] res = list() for el in alphabet_slice: res += [el + str(num) for num in range(start_num, end_num + 1)] return res
class Solution { public List<String> cellsInRange(String s) { char sc = s.charAt(0), ec = s.charAt(3); char sr = s.charAt(1), er = s.charAt(4); List<String> res = new ArrayList<>(); for (char i = sc; i <= ec; ++i){ for (char j = sr; j <= er; ++j){ res.add(new String(new char[]{i, j})); } } return res; } }
class Solution { public: vector<string> cellsInRange(string s) { vector<string>ans; for(char ch=s[0];ch<=s[3];ch++) { for(int i=s[1]-'0';i<=s[4]-'0';i++) { string res=""; res+=ch; res+=to_string(i); ans.push_back(res); } } return ans; } };
const toCharCode = (char) => char.charCodeAt() var cellsInRange = function(s) { const result = [] for(let i = toCharCode(s[0]) ; i <= toCharCode(s[3]) ; i++){ for(let j = s[1] ; j <= s[4] ; j++){ result.push(String.fromCharCode(i) +j) } } return result };
Cells in a Range on an Excel Sheet
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children. &nbsp; Example 1: Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. &nbsp; Constraints: n == ratings.length 1 &lt;= n &lt;= 2 * 104 0 &lt;= ratings[i] &lt;= 2 * 104
class Solution: def candy(self, ratings: List[int]) -> int: n=len(ratings) temp = [1]*n for i in range(1,n): if(ratings[i]>ratings[i-1]): temp[i]=temp[i-1]+1 if(n>1): if(ratings[0]>ratings[1]): temp[0]=2 for i in range(n-2,-1,-1): if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]): temp[i]=temp[i+1]+1 return sum(temp)
class Solution { public int candy(int[] ratings) { int[] left = new int[ratings.length]; Arrays.fill(left, 1); // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy for(int i = 0; i<ratings.length-1; i++){ if(ratings[i] < ratings[i+1]) left[i+1] = left[i]+1; } int[] right = new int[ratings.length]; Arrays.fill(right, 1); //we are checking from right to left if the element after than our current element is greater or not , if yes then we are also checking their candies if greater rating has less number of candies then increasing their candy for(int i = ratings.length -2; i>=0; i--){ if(ratings[i+1] < ratings[i] && right[i] <= right[i+1]) right[i] = right[i+1]+1; } int sum = 0; for(int i = 0; i<right.length; i++){ sum += Math.max(right[i], left[i]); } return sum;} }
class Solution { public: int candy(vector<int>& ratings) { ios_base::sync_with_stdio(false); cin.tie(NULL); int ans = 0, i; vector<int> store(ratings.size(), 1); for (i = 0; i < ratings.size()-1; i++) if(ratings[i+1] > ratings[i]) store[i+1] = store[i]+1; for (i = ratings.size()-1; i > 0; i--) if(ratings[i-1] > ratings[i]) store[i-1] = max(store[i-1], store[i]+1); for (auto i:store) ans += i; return ans; } };
/** * @param {number[]} ratings * @return {number} */ var candy = function(ratings) { const n = ratings.length; let candies = [...Array(n)].fill(1); let index = 0; let copy = [ratings[0]]; let isDecreasing = true; for(let i = 1; i < n; i++) { if (ratings[i] > ratings[i - 1]) { isDecreasing = false; break; } /* In case of decreasing sequence, make a copy of the current rating, but in inverted format */ copy.unshift(ratings[i]); } if (isDecreasing) { ratings = copy; } else { copy = []; } while(index >= 0) { if (index >= n) { break; } if (ratings[index] > ratings[index + 1] && candies[index + 1] >= candies[index]) { candies[index] = candies[index] + 1; index = Math.max(-1, index - 2); } else if (ratings[index] > ratings[index - 1] && candies[index - 1] >= candies[index]) { candies[index] = candies[index - 1] + 1; } index++; } return candies.reduce((sum, candy) => sum + candy, 0); }
Candy
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x &lt;= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0. &nbsp; Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. Example 2: Input: stones = [1] Output: 1 &nbsp; Constraints: 1 &lt;= stones.length &lt;= 30 1 &lt;= stones[i] &lt;= 1000
class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones = [-x for x in stones] heapq.heapify(stones) while len(stones) > 1: mx1 = -heapq.heappop(stones) mx2 = -heapq.heappop(stones) if mx1 - mx2: heapq.heappush(stones, -(mx1 - mx2)) if len(stones): return -heapq.heappop(stones) return 0
class Solution { public int lastStoneWeight(int[] stones) { PriorityQueue<Integer> pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x)); for (int i = 0; i < stones.length; i++) { pq.add(stones[i]); } while (pq.size() > 1) { int r1 = pq.poll(); int r2 = pq.poll(); if (r1 != r2) pq.add(r1 - r2); } return (pq.isEmpty()) ? 0 : pq.poll(); } }
class Solution { public: int lastStoneWeight(vector<int>& stones) { while(stones.size()>1){ sort(stones.begin(), stones.end(), greater<int>()); stones[1] = (stones[0]-stones[1]); stones.erase(stones.begin()); } return stones[0]; } };
var lastStoneWeight = function(stones) { let first = 0, second = 0; stones.sort((a,b) => a - b); while(stones.length > 1) { first = stones.pop(); second = stones.pop(); stones.push(first - second); stones.sort((a,b) => a - b); } return stones[0]; };
Last Stone Weight
Given n points on a 2D plane where points[i] = [xi, yi], Return&nbsp;the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. &nbsp; Example 1: ​ Input: points = [[8,7],[9,9],[7,4],[9,7]] Output: 1 Explanation: Both the red and the blue area are optimal. Example 2: Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]] Output: 3 &nbsp; Constraints: n == points.length 2 &lt;= n &lt;= 105 points[i].length == 2 0 &lt;= xi, yi&nbsp;&lt;= 109
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: # only taking x-axis point as it's relevant arr = [i[0] for i in points] arr.sort() diff = -1 for i in range(1, len(arr)): diff = max(diff, arr[i] - arr[i - 1]) return diff
class Solution { public int maxWidthOfVerticalArea(int[][] points) { int L = points.length; // y-coordinate of a point does not matter in width int arr[] = new int[L]; for(int i=0;i<L;i++){ arr[i]=points[i][0]; } Arrays.sort(arr); int diff = Integer.MIN_VALUE; for(int i=1;i<L;i++){ if((arr[i]-arr[i-1])>diff){ diff=arr[i]-arr[i-1]; } } return diff; } }
class Solution { public: int maxWidthOfVerticalArea(vector<vector<int>>& points) { sort(begin(points),end(points)); int n=points.size(); int m=0; for(int i=0;i<n-1;i++) m=max(points[i+1][0]-points[i][0],m); return m; } };
var maxWidthOfVerticalArea = function(points) { let ans = 0; points = points.map(item => item[0]).sort((a, b) => a - b); for(let i = 1; i < points.length; i++){ ans = Math.max(ans, points[i] - points[i-1]); } return ans; };
Widest Vertical Area Between Two Points Containing No Points
Given an array arr,&nbsp;replace every element in that array with the greatest element among the elements to its&nbsp;right, and replace the last element with -1. After doing so, return the array. &nbsp; Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Explanation: - index 0 --&gt; the greatest element to the right of index 0 is index 1 (18). - index 1 --&gt; the greatest element to the right of index 1 is index 4 (6). - index 2 --&gt; the greatest element to the right of index 2 is index 4 (6). - index 3 --&gt; the greatest element to the right of index 3 is index 4 (6). - index 4 --&gt; the greatest element to the right of index 4 is index 5 (1). - index 5 --&gt; there are no elements to the right of index 5, so we put -1. Example 2: Input: arr = [400] Output: [-1] Explanation: There are no elements to the right of index 0. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 104 1 &lt;= arr[i] &lt;= 105
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: maxright = arr[-1] for i in range(len(arr) -1,-1,-1): temp = arr[i] arr[i] = maxright if temp > maxright: maxright = temp arr[-1] = -1 return arr
class Solution { public int[] replaceElements(int[] arr) { int greatElement = -1; for(int i = arr.length-1; i >= 0; i--) { int temp = arr[i]; arr[i] = greatElement; greatElement = Math.max(temp, greatElement); } return arr; } }
class Solution { public: vector<int> replaceElements(vector<int>& arr) { int n=arr.size(); //taking last index as greatest for now int g=arr[n-1]; //setting last index as -1 arr[n-1]=-1; for(int i=n-2;i>=0;i--) { //storing last index value to be changed to comapare with the greatest value till now int h=arr[i]; //assigning greatest till now from right arr[i]=g; //checking if current is greater than the previous indices if(h>g) { g=h; } } //returning the value return arr; } };
* @param {number[]} arr * @return {number[]} */ var replaceElements = function(arr) { let max = arr[arr.length -1] for(let j=arr.length - 2; j>=0; --j){ let curr = arr[j]; arr[j] = max max = Math.max(max,curr) } arr[arr.length -1] = -1; return arr; };
Replace Elements with Greatest Element on Right Side
You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i]. The following are the types of poker hands you can make from best to worst: "Flush": Five cards of the same suit. "Three of a Kind": Three cards of the same rank. "Pair": Two cards of the same rank. "High Card": Any single card. Return a string representing the best type of poker hand you can make with the given cards. Note that the return values are case-sensitive. &nbsp; Example 1: Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"] Output: "Flush" Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush". Example 2: Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"] Output: "Three of a Kind" Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind". Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand. Also note that other cards could be used to make the "Three of a Kind" hand. Example 3: Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"] Output: "Pair" Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair". Note that we cannot make a "Flush" or a "Three of a Kind". &nbsp; Constraints: ranks.length == suits.length == 5 1 &lt;= ranks[i] &lt;= 13 'a' &lt;= suits[i] &lt;= 'd' No two cards have the same rank and suit.
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: s={} for i in suits: if i in s: s[i]+=1 if s[i]==5: return 'Flush' else: s[i]=1 r={} max_ = 0 for i in ranks: if i in r: r[i]+=1 max_=max(max_,r[i]) else: r[i]=1 if max_>=3: return "Three of a Kind" elif max_==2: return "Pair" else: return "High Card"
class Solution { public String bestHand(int[] ranks, char[] suits) { int max = 0; int card = 0; char ch = suits[0]; int[] arr = new int[14]; for(int i = 0; i < 5; i++){ arr[ranks[i]]++; max = Math.max(max,arr[ranks[i]]); if(suits[i] == ch) card++; } if(card == 5) return "Flush"; return max >= 3 ? "Three of a Kind":(max == 2 ? "Pair" : "High Card"); } }
class Solution { public: string bestHand(vector<int>& ranks, vector<char>& suits) { map<int, int> m1; int mn = INT_MIN; int all_same = count(begin(suits), end(suits), suits[0]); int n = ranks.size(); for (int i = 0; i < n; i++) { m1[ranks[i]]++; mn = max(mn, m1[ranks[i]]); } if (all_same == n) return "Flush"; if (mn >= 3) return "Three of a Kind"; if (mn == 2) return "Pair"; return "High Card"; } };
var bestHand = function(ranks, suits) { let suitsMap = {} for (let i=0; i<suits.length; i++) { if (suitsMap[suits[i]]) { suitsMap[suits[i]]++; } else { suitsMap[suits[i]] = 1; } } if (Object.keys(suitsMap).length === 1) return "Flush"; let pair = false; let ranksMap = {}; for (let i=0; i<ranks.length; i++) { if (ranksMap[ranks[i]]) { ranksMap[ranks[i]]++; if (ranksMap[ranks[i]] >= 3) return "Three of a Kind"; } else { ranksMap[ranks[i]] = 1; } } if (Object.keys(ranksMap).length === 5) return "High Card"; return "Pair"; };
Best Poker Hand
Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. &nbsp; Example 1: Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Example 2: Input: root = [] Output: [] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 6000]. -100 &lt;= Node.val &lt;= 100 &nbsp; Follow-up: You may only use constant extra space. The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
""" # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def findRightMost(self, root, level, requiredLevel): if not root: return root if level == requiredLevel: return root right = self.findRightMost(root.right, level + 1, requiredLevel) if right: return right return self.findRightMost(root.left, level + 1, requiredLevel) def findLeftMost(self, root, level, requiredLevel): if not root: return root if level == requiredLevel: return root left = self.findLeftMost(root.left, level + 1, requiredLevel) if left: return left return self.findLeftMost(root.right, level + 1, requiredLevel) def findRightMostFromRoot(self, rootLevelInfo, requiredLevel, currentRight): if currentRight: if currentRight.right: return currentRight.right if currentRight.left: return currentRight.left root, rootlevel = rootLevelInfo rightMost = self.findRightMost(root, rootlevel, requiredLevel) while not rightMost and root: root = root.right if root.right else root.left rootlevel += 1 rightMost = self.findRightMost(root, rootlevel, requiredLevel) if rightMost: rootLevelInfo[-1] = rootlevel rootLevelInfo[0] = root return rightMost def findLeftMostFromRoot(self, rootLevelInfo, requiredLevel, currentLeft): if currentLeft: if currentLeft.left: return currentLeft.left if currentLeft.right: return currentLeft.right root, rootlevel = rootLevelInfo leftMost = self.findLeftMost(root, rootlevel, requiredLevel) while not leftMost and root: root = root.left if root.left else root.right rootlevel += 1 leftMost = self.findLeftMost(root, rootlevel, requiredLevel) if leftMost: rootLevelInfo[-1] = rootlevel rootLevelInfo[0] = root return leftMost def stitch(self, root): if not root: return leftRootStart = [root.left, 1] rightRootStart = [root.right, 1] connectLevel = 1 currentLeft = self.findLeftMostFromRoot(rightRootStart, 1, None) currentRight = self.findRightMostFromRoot(leftRootStart, 1, None) while currentLeft and currentRight: currentRight.next = currentLeft connectLevel += 1 currentLeft = self.findLeftMostFromRoot(rightRootStart, connectLevel, currentLeft) currentRight = self.findRightMostFromRoot(leftRootStart, connectLevel, currentRight) self.stitch(root.left) self.stitch(root.right) def connect(self, root): """ :type root: Node :rtype: Node """ if not root: return root self.stitch(root) return root
class Solution { public Node connect(Node root) { if (root == null) { return root; } Node head = null; //the start node of next level, the first left of next level Node prev = null; //the next pointer Node curr = root; while (curr != null) { //traverse the whole current level, left -> right, until we meet a null pointer while (curr != null) { if (curr.left != null) { if (head == null) { head = curr.left; prev = curr.left; } else { prev.next = curr.left; prev = prev.next; } } if (curr.right != null) { if (head == null) { head = curr.right; prev = curr.right; } else { prev.next = curr.right; prev = prev.next; } } curr = curr.next; } curr = head; prev = null; head = null; } return root; } }
// method-1 class Solution { public: Node* connect(Node* root) { if(!root) return NULL; queue<Node*> q; q.push(root); root->next=NULL; while(!q.empty()){ int size=q.size(); Node* prev=NULL; for(int i=0;i<size;i++){ Node* temp=q.front(); q.pop(); if(prev) prev->next=temp; if(i==size-1){ temp->next=NULL; } if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); prev=temp; } } return root; } };
var connect = function(root) { let curr = root; while (curr != null) { let start = null; // (1) let prev = null; while (curr != null) { // (2) if (start == null) { // (3) if (curr.left) start = curr.left; else if (curr.right) start = curr.right; prev = start; // (4) } if (prev != null) { if (curr.left && prev != curr.left) { prev = prev.next = curr.left; // (5) } if (curr.right && prev != curr.right) { prev = prev.next = curr.right; } } curr = curr.next; // (6) } curr = start; // (7) } return root; };
Populating Next Right Pointers in Each Node II
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: The two devices are located on two different rows: r1 and r2, where r1 &lt; r2. For each row i where r1 &lt; i &lt; r2, there are no security devices in the ith row. Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank. &nbsp; Example 1: Input: bank = ["011001","000000","010100","001000"] Output: 8 Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: * bank[0][1] -- bank[2][1] * bank[0][1] -- bank[2][3] * bank[0][2] -- bank[2][1] * bank[0][2] -- bank[2][3] * bank[0][5] -- bank[2][1] * bank[0][5] -- bank[2][3] * bank[2][1] -- bank[3][2] * bank[2][3] -- bank[3][2] Note that there is no beam between any device on the 0th row with any on the 3rd row. This is because the 2nd row contains security devices, which breaks the second condition. Example 2: Input: bank = ["000","111","000"] Output: 0 Explanation: There does not exist two devices located on two different rows. &nbsp; Constraints: m == bank.length n == bank[i].length 1 &lt;= m, n &lt;= 500 bank[i][j] is either '0' or '1'.
class Solution(object): def numberOfBeams(self, bank): ans, pre = 0, 0 for s in bank: n = s.count('1') if n == 0: continue ans += pre * n pre = n return ans
class Solution { public int numberOfBeams(String[] bank) { int ans = 0, pre = 0; for (int i = 0;i < bank.length; i ++) { int n = 0; for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++; if (n == 0) continue; ans += pre * n;; pre = n; } return ans; } }
class Solution { public: int numberOfBeams(vector<string>& bank) { int rowLaserCount=0,totalLaserCount=0,prevCount=0; for(int i=0;i<bank.size();i++) { rowLaserCount=0; for(char j:bank[i]) { if(j=='1') rowLaserCount++; }totalLaserCount+=(prevCount*rowLaserCount); if(rowLaserCount)prevCount=rowLaserCount; } return totalLaserCount; } };
var numberOfBeams = function(bank) { let totalBeams = 0; const maximumSecurityDevicePerRow = bank.map(row => (row.match(/1/g) || []).length).filter(Boolean) for (let index = 0; index < maximumSecurityDevicePerRow.length - 1; index++) totalBeams+= maximumSecurityDevicePerRow[index] * maximumSecurityDevicePerRow[index + 1]; return totalBeams; };
Number of Laser Beams in a Bank
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 &lt; j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. All three parts have equal binary values. If it is not possible, return [-1, -1]. Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value. &nbsp; Example 1: Input: arr = [1,0,1,0,1] Output: [0,3] Example 2: Input: arr = [1,1,0,1,1] Output: [-1,-1] Example 3: Input: arr = [1,1,0,0,1] Output: [0,2] &nbsp; Constraints: 3 &lt;= arr.length &lt;= 3 * 104 arr[i] is 0 or 1
class Solution: def threeEqualParts(self, arr: List[int]) -> List[int]: n = len(arr) count_one = arr.count(1) if count_one == 0: return [0,n-1] if count_one % 3!= 0: return [-1,-1] target_ones = count_one // 3 breaks = [] one_count = 0 for i , bit in enumerate(arr): if bit ==1 : one_count +=1 if one_count in [1,target_ones+1,2*target_ones+1]:breaks.append(i) if one_count in [target_ones,2*target_ones,3*target_ones]:breaks.append(i) i1,j1,i2,j2,i3,j3 = breaks if not arr[i1:j1+1] == arr[i2:j2+1] == arr[i3:j3+1]:return [-1,-1] trailing_zeroes_left = i2 - j1 - 1 trailing_zeroes_mid = i3 - j2 - 1 trailing_zeroes_right = n - j3 - 1 if trailing_zeroes_right > min(trailing_zeroes_left,trailing_zeroes_mid):return [-1,-1] j1 += trailing_zeroes_right j2 += trailing_zeroes_right return [j1,j2+1]
class Solution { public int[] threeEqualParts(int[] arr) { List<Integer> ones = new ArrayList<>(); for (int i = 0; i < arr.length; i++){ if (arr[i]==1){ ones.add(i); } } if (ones.size()==0){ // edge case return new int[]{0,2}; } int[] ans = new int[2]; int each = ones.size()/3; for (int i = 0; i < 2 && ones.size()%3==0; i++){ // for the first 2 partitions for (int j = 0; j < each-1; j++){ // compare gaps if (ones.get(j+1+i*each)-ones.get(j+i*each)!=ones.get(j+2*each+1)-ones.get(j+2*each)) return new int[]{-1, -1}; } ans[i]=ones.get((i+1)*each-1)+i+(arr.length - 1 - ones.get(ones.size()-1)); // cut point } return ones.size()%3>0||ans[0]>=ones.get(each)||ans[1]>ones.get(2*each)? new int[]{-1, -1} : ans; } }
class Solution { public: vector<int> threeEqualParts(vector<int>& v) { vector<int> one; int n=v.size(); for(int i=0;i<n;i++){ if(v[i]==1) one.push_back(i+1); } if(one.size()==0){ return {0,2}; } if(one.size()%3) return {-1,-1}; int ext=n-one.back(),sz=one.size(); int gap1=one[sz/3]-one[sz/3-1]-1,gap2=one[2*sz/3]-one[2*sz/3-1]-1; // cout<<gap1<<" "<<gap2<<endl; if(gap1<ext || gap2<ext) return {-1,-1}; string s1,s2,s3; for(int i=0;i<=one[sz/3-1]+ext-1;i++){ if(s1.length()>0 || v[i]) s1+=to_string(v[i]); } for(int i=one[sz/3-1]+ext;i<=one[2*sz/3-1]+ext-1;i++){ if(s2.length()>0 || v[i]) s2+=to_string(v[i]); } for(int i=one[2*sz/3-1]+ext;i<=n-1;i++){ if(s3.length()>0 || v[i]) s3+=to_string(v[i]); } //All 3 Numbers in vector v :- // num1={0,one[sz/3-1]+ext-1}; // num2={one[sz/3-1]+ext,one[2*sz/3-1]+ext-1} // num3={one[2*sz/3-1]+ext,n-1}; if(s1==s2 && s2==s3) return {one[sz/3-1]+ext-1,one[2*sz/3-1]+ext}; return {-1,-1}; } };
/** * @param {number[]} arr * @return {number[]} */ var threeEqualParts = function(arr) { const ones = arr.reduce((s, n) => s + n, 0); if (ones === 0) return [0, 2]; if (ones % 3 !== 0) return [-1, -1]; let onesToFind = ones / 3; let k = arr.length; while (onesToFind > 0) if (arr[--k] === 1) --onesToFind; const iter = arr.length - k; const firstOne = arr.indexOf(1); const secondOne = arr.indexOf(1, firstOne + iter); for (let i = 0; i < iter; i++) if (arr[i + firstOne] !== arr[k + i] || arr[i + secondOne] !== arr[k + i]) return [-1, -1]; return [firstOne + iter - 1, secondOne + iter]; };
Three Equal Parts
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. &nbsp; Example 1: Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1] Example 2: Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] Output: [0,1,-1] &nbsp; Constraints: 1 &lt;= n &lt;= 100 0 &lt;= redEdges.length,&nbsp;blueEdges.length &lt;= 400 redEdges[i].length == blueEdges[j].length == 2 0 &lt;= ai, bi, uj, vj &lt; n
class Solution: def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]: g = [[[] for _ in range(2)] for _ in range(n)] for i,j in redEdges: g[i][0] += [j] for i,j in blueEdges: g[i][1] += [j] distance = [float("inf") for _ in range(n)] distance[0] = 0 q = queue.Queue() q.put((0,0,False)) q.put((0,0,True)) redS = set([0]) blueS = set([0]) while not q.empty(): node,dist,red = q.get() if red: neighbours = g[node][0] redS.add(node) curr = blueS else: neighbours = g[node][1] blueS.add(node) curr = redS for neighbour in neighbours: if dist + 1 < distance[neighbour]: distance[neighbour] = dist + 1 q.put((neighbour,dist + 1,not red)) if not (neighbour in curr): q.put((neighbour,dist + 1,not red)) for i in range(n): if distance[i] == float("inf"): distance[i] = -1 return distance
class Solution { // g1-> graph with red edges // g2-> graph with blue edges List<Integer> g1[], g2[]; int[] dist1, dist2, ans; int MX = (int) 2e9; public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { dist1 = new int[n]; dist2 = new int[n]; g1=new ArrayList[n]; g2=new ArrayList[n]; ans=new int[n]; for (int i=0;i<n;i++){ g1[i]=new ArrayList<>(); g2[i]=new ArrayList<>(); dist1[i]=MX; dist2[i]=MX; ans[i]=MX; } for (int i=0;i<redEdges.length;i++){ int u=redEdges[i][0]; int v=redEdges[i][1]; g1[u].add(v); } for (int i=0;i<blueEdges.length;i++){ int u=blueEdges[i][0]; int v=blueEdges[i][1]; g2[u].add(v); } dist1[0]=0; dist2[0]=0; dfs(0,true); dfs(0,false); for (int i=0;i<n;i++){ ans[i]=Math.min(dist1[i], dist2[i]); if (ans[i]==MX) ans[i]=-1; } return ans; } public void dfs(int u, boolean flag) { if (flag) { for (int v: g1[u]) { if (dist1[v]>dist2[u]+1){ dist1[v]=dist2[u]+1; dfs(v,!flag); } } } else { for (int v: g2[u]) { if (dist2[v]>dist1[u]+1){ dist2[v]=dist1[u]+1; dfs(v,!flag); } } } } }
#define red 1 #define blue 2 class Solution { public: vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) { vector<vector<pair<int,int>>> graph(n); vector<vector<int>> visited(n, vector<int>(3, false)); for(int i = 0;i<redEdges.size();i++) { graph[redEdges[i][0]].push_back({redEdges[i][1], red}); } for(int i = 0;i<blueEdges.size();i++) { graph[blueEdges[i][0]].push_back({blueEdges[i][1], blue}); } queue<tuple<int, int,int>> q; q.push({0, 0, 0}); vector<int> res(n, INT_MAX); while(!q.empty()) { auto top = q.front(); q.pop(); int parent = get<0>(top); int step = get<1>(top); int color = get<2> (top); res[parent] = min(res[parent], step); if(visited[parent][color]) continue; visited[parent][color] = true; for(auto child:graph[parent]) { if(color == child.second) continue; q.push(make_tuple(child.first, step+1, child.second)); } } for(int i = 0;i<res.size();i++) { if(res[i]==INT_MAX) res[i] = -1; } return res; } };
const RED = "red"; const BLUE = "blue"; function mapAllEdges(edges) { const map = new Map(); for(let edge of edges) { if(!map.has(edge[0])) { map.set(edge[0], []); } map.get(edge[0]).push(edge[1]) } return map; } function bfs(color, redNodeMap, blueNodeMap, result) { const queue = [0]; let length = 0; let currentColor = color; while(queue.length > 0) { const size = queue.length; for(let i = 0; i < size; i++) { const node = queue.shift(); if(result[node] === -1 || length < result[node] ) { result[node] = length; } const map = RED === currentColor ? redNodeMap : blueNodeMap; if(map.has(node)) { const edges = map.get(node); map.delete(node); queue.push(...edges) } } length++; currentColor = RED === currentColor ? BLUE : RED; } return result; } function shortestPath(redEdges, blueEdges, color, result) { const redNodeMap = mapAllEdges(redEdges); const blueNodeMap = mapAllEdges(blueEdges); bfs(color, redNodeMap, blueNodeMap, result); } /** * @param {number} n * @param {number[][]} redEdges * @param {number[][]} blueEdges * @return {number[]} */ var shortestAlternatingPaths = function(n, redEdges, blueEdges) { const result = new Array(n).fill(-1); shortestPath(redEdges, blueEdges, RED, result); shortestPath(redEdges, blueEdges, BLUE, result); return result };
Shortest Path with Alternating Colors
You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. &nbsp; Example 1: Input: n = 7 Output: 6 Explanation: Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. Example 2: Input: n = 14 Output: 13 Explanation: Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. &nbsp; Constraints: 1 &lt;= n &lt;= 200
class Solution: def numberOfMatches(self, n: int) -> int: return n - 1
class Solution { public int numberOfMatches(int n) { // This is the problem's base case; we know that if n == 1, // the number of matches played must be 0, since the last team left // can't play a match against themselves. if (n == 1) return 0; // We declare an int to hold our recursive solution. int res; // We initialize res using a recursive call, reducing n // as described in the problem. if (n % 2 == 0) { res = numberOfMatches(n / 2); // After the recursive call is executed, we add the appropriate value to // our solution variable. res += n / 2; } else { res = numberOfMatches((n - 1) / 2 + 1); res += (n - 1) / 2; } // Our initial call to numberOfMatches() // will return the total number of matches // added to res in each recursive call. return res; } }
class Solution { public: int numberOfMatches(int n) { int count=0; while(n>1) { if(n%2==0) { int a=n/2; n=n/2; count=count+a;} else { int a=(n-1)/2; n=a+1; count=count+a; } } return count; } };
/** * @param {number} n * @return {number} */ var numberOfMatches = function(n) { let matches = 0,current = n; while(current > 1){ if(current % 2 === 0){ matches += current/2; current = current/2 }else{ matches += (current-1)/2; current = (current-1)/2 + 1 ; } } return matches; };
Count of Matches in Tournament
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums&nbsp;should hold the final result. It does not matter what you leave beyond the first&nbsp;k&nbsp;elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted. &nbsp; Example 1: Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3,_] Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0,0,1,1,1,1,2,3,3] Output: 7, nums = [0,0,1,1,2,3,3,_,_] Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). &nbsp; Constraints: 1 &lt;= nums.length &lt;= 3 * 104 -104 &lt;= nums[i] &lt;= 104 nums is sorted in non-decreasing order.
class Solution(object): def removeDuplicates(self, nums): n=len(nums) if n==2: return 2 if n==0: return 0 if n==1: return 1 same=0 start=-1 end=-1 i=0 while i<n-1: if nums[i]==nums[i+1] and same==0: same=1 start=i+2 i+=1 continue while i<n-1 and nums[i]==nums[i+1] and same==1: end=i+1 i+=1 i+=1 if start!=-1 and end!=-1: no_of_shifts=end-start+1 while i<n: nums[i-no_of_shifts]=nums[i] i+=1 n=n-no_of_shifts i=start start=-1 end=-1 same=0 return n ```
class Solution { public int removeDuplicates(int[] nums) { int index = 1; int count = 0; for(int i = 1;i<nums.length;i++){ if(nums[i] == nums[i-1]){ count++; } else{ count = 0; } if(count <= 1){ nums[index] = nums[i]; index++; } } return index; } }
class Solution { public: int removeDuplicates(vector<int>& nums) { int l = 1; int last_selected = nums[0]; int count = 1; int n = nums.size(); for(int i = 1;i<n;i++) { if(nums[i]!=last_selected){ count = 1; last_selected = nums[i]; nums[l] = nums[i]; l++; } else if(count == 2){ continue; } else{ nums[l] = nums[i]; l++; count++; } } return (l); } };
var removeDuplicates = function(nums) { let i = 0; let count = 0; for(let num of nums) { (num == nums[i - 1]) ? count++ : count = 1; if(i == 0 || (num >= nums[i - 1] && count <= 2)) nums[i++] = num; } return i; };
Remove Duplicates from Sorted Array II
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order. &nbsp; Example 1: Input: land = [[1,0,0],[0,1,1],[0,1,1]] Output: [[0,0,0,0],[1,1,2,2]] Explanation: The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0]. The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2]. Example 2: Input: land = [[1,1],[1,1]] Output: [[0,0,1,1]] Explanation: The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]. Example 3: Input: land = [[0]] Output: [] Explanation: There are no groups of farmland. &nbsp; Constraints: m == land.length n == land[i].length 1 &lt;= m, n &lt;= 300 land consists of only 0's and 1's. Groups of farmland are rectangular in shape.
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: n = len(land) m = len(land[0]) groups = [] visited = set() for y in range(n): for x in range(m): if land[y][x] == 0: continue if (y, x) in visited: continue q = collections.deque() q.append((y, x)) visited.add((y, x)) while q: cy, cx = q.popleft() for dy, dx in ((0, 1), (1, 0)): if (cy + dy, cx + dx) in visited: continue if 0 <= cy + dy < n and 0 <= cx + dx < m: if land[cy + dy][cx + dx] == 1: q.append((cy + dy, cx + dx)) visited.add((cy + dy, cx + dx)) groups.append([y, x, cy, cx]) return groups
class Solution { int[] arr; public int[][] findFarmland(int[][] land) { List<int[]> res = new ArrayList<>(); for(int i=0;i<land.length;i++) for(int j=0;j<land[0].length;j++){ if(land[i][j] == 1){ arr = new int[]{i,j,0,0}; dfs(land,i,j); res.add(arr); } } return res.stream().map(i->i).toArray(int[][] :: new); } public void dfs(int[][] land, int i,int j){ if(i<0 || j<0 || i>=land.length || j>= land[0].length || land[i][j] == 0) return; arr[2] = Math.max(i,arr[2]); arr[3] = Math.max(j,arr[3]); land[i][j] = 0; dfs(land,i-1,j); dfs(land,i,j+1); dfs(land,i+1,j); dfs(land,i,j-1); } }
class Solution { public: vector<vector<int>> nbrs = {{0,1},{1,0},{-1,0},{0,-1}}; pair<int, int> dfs(vector<vector<int>> &land, int i, int j, vector<vector<bool>> &visited) { visited[i][j] = true; pair<int, int> res = make_pair(i, j); for(auto &nbr: nbrs) { int x = i + nbr[0]; int y = j + nbr[1]; if(x < 0 || y < 0 || x >= land.size() || y >= land[0].size() || visited[x][y] || land[x][y] != 1) continue; pair<int, int> ans = dfs(land, x, y, visited); res.first = max(res.first, ans.first); res.second = max(res.second, ans.second); } return res; } vector<vector<int>> findFarmland(vector<vector<int>>& land) { int m = land.size(); int n = land[0].size(); vector<vector<bool>> visited(m, vector<bool>(n, false)); vector<vector<int>> ans; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(!visited[i][j] && land[i][j] == 1) { pair<int, int> p = dfs(land, i, j, visited); vector<int> res; res.push_back(i); res.push_back(j); res.push_back(p.first); res.push_back(p.second); ans.push_back(res); cout << 1 << endl; } } } return ans; } };
var findFarmland = function(land) { let height = land.length; let width = land[0].length; let results = []; let endRow = 0; let endCol = 0; let go = (i, j) => { if (i < 0 || j < 0 || i >= height || j >= width || land[i][j] === 0) { return; } endRow = Math.max(endRow, i); endCol = Math.max(endCol, j); land[i][j] = 0; // reset everything to 0 go(i + 1, j); go(i - 1, j); go(i, j + 1); go(i, j - 1); } for (let i = 0; i < height; i++) { for (let j = 0; j < width; j++) { if (land[i][j] === 1) { endRow = 0; endCol = 0; go(i, j); results.push([i, j, endRow, endCol]); } } } return results; };
Find All Groups of Farmland
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain. &nbsp; Example 1: Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. Example 2: Input: cardPoints = [2,2,2], k = 2 Output: 4 Explanation: Regardless of which two cards you take, your score will always be 4. Example 3: Input: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55 Explanation: You have to take all the cards. Your score is the sum of points of all cards. &nbsp; Constraints: 1 &lt;= cardPoints.length &lt;= 105 1 &lt;= cardPoints[i] &lt;= 104 1 &lt;= k &lt;= cardPoints.length
class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: total_cards = len(cardPoints) total = sum(cardPoints) window_size = total_cards - k window_total = 0 if total_cards == k: return total for i in range(total_cards - k): window_total += cardPoints[i] max_diff = total - window_total for i in range((total_cards - k), total_cards): window_total += cardPoints[i] window_total -= cardPoints[i-window_size] if total - window_total > max_diff: max_diff = total - window_total return max_diff
class Solution { public int maxScore(int[] cardPoints, int k) { int n = cardPoints.length; int[] totalSum = new int[n]; int sum = 0; for(int i=0;i<n;i++){ sum += cardPoints[i]; totalSum[i] = sum; } if(n==k){ return sum; } int score =0; for(int i=0;i<=k;i++){ int j = i+n-k-1; int subsum = 0; if(i==0){ subsum = totalSum[j]; } else{ subsum = totalSum[j]-totalSum[i-1]; } score = Math.max(score,sum-subsum); } return score; } }
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int max_s = 0, left =0, right = 0, n = cardPoints.size(); //getting sum of k right elements for(int i = 0; i<k; i++){ right += cardPoints[n-i-1]; } // Assumming max as sum of k right elements max_s = right; for(int i = 0; i<k; i++){ left += cardPoints[i]; right -= cardPoints[n-k+i]; max_s = max(max_s, left+right); } return max_s; } };
/** * @param {number[]} cardPoints * @param {number} k * @return {number} */ // Obtaining k cards from the beginning or end of the row for the largest sum, meaning leaving the // array with n-k adjacent cards with the min sum // therefore, this transform the problem to finding the minSum of subarray of length n-k // we use slide window to calculate the minSubArraySum var maxScore = function(cardPoints, k) { const n = cardPoints.length, d = n-k // d is the window length let sum = 0 for (let i = 0; i < d; i++) { sum += cardPoints[i] } let minWindowSum = sum, totalSum = sum console.log(sum) for (let i = d; i < n; i++) { // the sum of the next window will the the sum of previous window + the next card (the end card of the next window) - the beginning card of the previous window sum += cardPoints[i] - cardPoints[i-d] minWindowSum = Math.min(minWindowSum, sum) totalSum += cardPoints[i] } // the ans will be the sum of all cards - the sum of min subArray return totalSum - minWindowSum };
Maximum Points You Can Obtain from Cards
There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction. &nbsp; Example 1: Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] Output: 35 Explanation: The building heights are shown in the center of the above image. The skylines when viewed from each cardinal direction are drawn in red. The grid after increasing the height of buildings without affecting skylines is: gridNew = [ [8, 4, 8, 7], [7, 4, 7, 7], [9, 4, 8, 7], [3, 3, 3, 3] ] Example 2: Input: grid = [[0,0,0],[0,0,0],[0,0,0]] Output: 0 Explanation: Increasing the height of any building will result in the skyline changing. &nbsp; Constraints: n == grid.length n == grid[r].length 2 &lt;= n &lt;= 50 0 &lt;= grid[r][c] &lt;= 100
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: mxr = [max(i) for i in grid] mxc = [0 for _ in range(len(grid[0]))] for i in range(len(grid)): for j in range(len(grid[0])): mxc[j] = max(grid[i][j],mxc[j]) ans =0 for i in range(len(grid)): for j in range(len(grid)): ans+=(min(mxr[i],mxc[j]) - grid[i][j]) return ans
class Solution { public int maxIncreaseKeepingSkyline(int[][] grid) { int n = grid.length; int[] row = new int[n]; int[] col = new int[n]; int ans = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ row[i] = Math.max(row[i],grid[i][j]); col[i] = Math.max(col[i],grid[j][i]); } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ ans += Math.min(row[i],col[j])-grid[i][j]; } } return ans; } }
class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int n=grid.size(); //get max for every Column vector<int> maxfromcol(n,INT_MIN); for(int j=0;j<n;j++){ for(int i=0;i<n;i++){ maxfromcol[j]=max(maxfromcol[j],grid[i][j]); } } int cost=0; for(int i=0;i<n;i++){ //find maximum in ithrow int mx=INT_MIN; for(int j=0;j<n;j++){ mx=max(mx,grid[i][j]); } cout<<mx<<endl; //update every element in ith row with min of max of ith row and max of jth col for(int j=0;j<n;j++){ int temp=grid[i][j]; grid[i][j]=min(mx,maxfromcol[j]); cost+=grid[i][j]-temp; } } return cost; } };
/** * @param {number[][]} grid * @return {number} */ var maxIncreaseKeepingSkyline = function(grid) { let n = grid.length; let sum = 0; let cache = []; for (let i = 0; i < n; i++) { const rowMax = Math.max(...grid[i]); for (let j = 0; j < n; j++) { let colMax = cache[j]; if (!colMax) { let max = Number.MIN_SAFE_INTEGER; for (let c = 0; c < n; c++) { max = Math.max(max, grid[c][j]); } cache[j] = max; colMax = max; } sum += Math.min(rowMax, colMax) - grid[i][j]; } } return sum; };
Max Increase to Keep City Skyline
Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'. In C++, there are two types of comments, line comments, and block comments. The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored. The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning. The first effective comment takes precedence over others. For example, if the string "//" occurs in a block comment, it is ignored. Similarly, if the string "/*" occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format. &nbsp; Example 1: Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] Explanation: The line by line code is visualized as below: /*Test program */ int main() { // variable declaration int a, b, c; /* This is a test multiline comment for testing */ a = b + c; } The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments. The line by line output code is visualized as below: int main() { int a, b, c; a = b + c; } Example 2: Input: source = ["a/*comment", "line", "more_comment*/b"] Output: ["ab"] Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"]. &nbsp; Constraints: 1 &lt;= source.length &lt;= 100 0 &lt;= source[i].length &lt;= 80 source[i] consists of printable ASCII characters. Every open block comment is eventually closed. There are no single-quote or&nbsp;double-quote in the input.
class Solution: def removeComments(self, source: List[str]) -> List[str]: ans, inComment = [], False new_str = "" for c in source: if not inComment: new_str = "" i, n = 0, len(c) # inComment, we find */ while i < n: if inComment: if c[i:i + 2] == '*/' and i + 1 < n: i += 2 inComment = False continue i += 1 # not in Comment, we find /* // and common character else: if c[i:i + 2] == '/*' and i + 1 < n: i += 2 inComment = True continue if c[i:i + 2] == '//' and i + 1 < n: break new_str += c[i] i += 1 if new_str and not inComment: ans.append(new_str) return ans
class Solution { public List<String> removeComments(String[] source) { boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. //It is initally set to false since we haven't read anything until now. List<String> result = new ArrayList<String>(); StringBuilder builder = new StringBuilder(); //Read every line from the source input. for(String line: source){ // Each time we move on to reading a new line, we check if it is a part of a block comment. //If it is already part of a block comment, it means we should skip the implicit newline characters as mentioned in the problem description. //For example if Line 1 was "int a /*Block comment Started" and Line 2 was "Block comment ends here */ b;", and Line 3 was "int c;" //we want our output to be "int ab", "int c" instead of "int a", "b;", "int c;" if(!blockActive){ builder = new StringBuilder(); } for(int i=0; i<line.length(); i++){ //Read every character of line char c = line.charAt(i); if(!blockActive){ //If we aren't currently in a block if(c=='/'){ //We check if we encounter the start of a regular comment //If so, then we need to check if the next character makes it a regular comment, a block comment, or neither of those two. if(i<line.length()-1 && line.charAt(i+1)=='/'){ //Checking if it's a regular comment break; //If it's a regular comment, we can simply skip everything else //until the end of the line, so we break from the loop and move on to the next line. } else if(i<line.length()-1 && line.charAt(i+1)=='*'){ //Or a block comment i++; //Since we verified it's a block comment, we simply increment i so that we don't re-read the '*' again, //and mark that we are now part of a block comment. blockActive = true; } else{ // If the second character is neither a / or *, it indicates that a first character must be a valid operator //(probably a mathematical operator such as multiplication or division, and not part of any comment, //so simply append it to the builder) builder.append(c); } } else { //Append all other characters directly to the builder. builder.append(c); } } else { //We skip all other characters in a block comment, and check for the closing block comment. //Once we find it, we mark the blockActive variable as false to indicate that it isn't part of the block anymore. if(c=='*'){ if(i<line.length()-1 && line.charAt(i+1)=='/'){ blockActive = false; i++; } } } } //We append to the result when we aren't part of a block any more, and the builder contains 1 or more characters. if(!blockActive && builder.length()!=0){ result.add(builder.toString()); } } return result; } }
class Solution { public: vector<string> removeComments(vector<string>& source) { bool commentStart = false; vector<string> res; bool multiComment = false; // are we having a multi-line comment? for (string &eachS : source) { if (!multiComment) { res.emplace_back(); } for (int i = 0; i < eachS.size(); i++) { if (!multiComment && eachS[i] == '/') { i++; if (eachS[i] == '/') { break; } else if (eachS[i] == '*') { multiComment = true; } else { res.back() += '/'; res.back() += eachS[i]; } } else if (multiComment && eachS[i] == '*') { if (i + 1 < eachS.size() && eachS[i + 1] == '/') { i++; multiComment = false; } } else { if (!multiComment) { res.back() += eachS[i]; } } } if (!multiComment && res.back().empty()) { res.pop_back(); } } return res; } };
var removeComments = function(source) { let result = []; let multi_line_comment = false; let str = ""; source.forEach(line => { for(let idx=0; idx < line.length; ++idx) { // if /* is not ongoing, check for start of a comment or not if(!multi_line_comment) { // if comment is //, ignore the rest of the line if(line[idx] + line[idx+1] === '//') { break; } // if comment if /*, set multi-line flag and move to next index else if(line[idx] + line[idx+1] === '/*') { multi_line_comment = true; ++idx; } // if not a comment start, add to string to be added to result else { str += line[idx]; } } // if /* comment is ongoing else { // if closing comment */ is encountered, set multi-line flag off and move to next index if(line[idx] + line[idx+1] === '*/') { multi_line_comment = false; ++idx; } } } // if /* comment is not ongoing and str is not empty, add to result as one code line if(str.length && !multi_line_comment) { result.push(str); str = ""; //reset the str } }) return result; }
Remove Comments
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. (An integer could be positive or negative.) A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr. An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2. A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2. For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names. Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope. &nbsp; Example 1: Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))" Output: 14 Explanation: In the expression (add x y), when checking for the value of the variable x, we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate. Since x = 3 is found first, the value of x is 3. Example 2: Input: expression = "(let x 3 x 2 x)" Output: 2 Explanation: Assignment in let statements is processed sequentially. Example 3: Input: expression = "(let x 1 y 2 x (add x y) (add x y))" Output: 5 Explanation: The first (add x y) evaluates as 3, and is assigned to x. The second (add x y) evaluates as 3+2 = 5. &nbsp; Constraints: 1 &lt;= expression.length &lt;= 2000 There are no leading or trailing spaces in expression. All tokens are separated by a single space in expression. The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer. The expression is guaranteed to be legal and evaluate to an integer.
class Solution: def evaluate(self, expression: str) -> int: loc = {} stack = [] for i, x in enumerate(expression): if x == "(": stack.append(i) elif x == ")": loc[stack.pop()] = i def fn(lo, hi, mp): """Return value of given expression.""" if expression[lo] == "(": return fn(lo+1, hi-1, mp) i = lo vals = [] while i < hi: if expression[i:i+3] in ("let", "add"): op = expression[i:i+3] i += 3 elif expression[i:i+4] == "mult": op = "mult" i += 4 elif expression[i].isalpha(): x = "" while i < hi and expression[i].isalnum(): x += expression[i] i += 1 if op in ("add", "mult"): vals.append(mp[x]) elif expression[i].isdigit() or expression[i] == "-": v = "" while i < hi and (expression[i].isdigit() or expression[i] == "-"): v += expression[i] i += 1 if op == "let": mp[x] = int(v) else: vals.append(int(v)) elif expression[i] == "(": v = fn(i+1, loc[i], mp.copy()) i = loc[i] + 1 if op == "let": mp[x] = v else: vals.append(v) else: i += 1 if op == "let": return int(v) elif op == "add": return sum(vals) else: return reduce(mul, vals) return fn(0, len(expression), {})
class Solution { String expression; int index; HashMap<String,Deque<Integer>> scope; //variable may be assigned many times, we use the peek value public int evaluate(String expression) { this.expression=expression; index=0; scope=new HashMap<>(); return evaluate(); } private int evaluate(){ if(expression.charAt(index)=='('){ //this is an expression index++; //skip '(' char begin=expression.charAt(index); int ret; if(begin=='l'){ //let index += 4; //skip let and a blank space ArrayList<String> vars=new ArrayList<>(); while(true){ if(!Character.isLowerCase(expression.charAt(index))){ ret=evaluate(); break; } String var=parseVar(); if(expression.charAt(index)==')'){ ret=scope.get(var).peek(); break; } vars.add(var); index++; int e=evaluate(); scope.putIfAbsent(var, new LinkedList<>()); scope.get(var).push(e); //assign a new value index++; } for (String var : vars) { scope.get(var).pop(); // remove all values of this scope } } else if(begin=='a') { //add index += 4; int v1 = evaluate(); index++; int v2 = evaluate(); ret = v1+v2; } else { //multi index += 5; int v1 = evaluate(); index++; int v2 = evaluate(); ret = v1*v2; } index++; // skip ')' return ret; } else { //this is not a expression, this is an integer or a variable if(Character.isLowerCase(expression.charAt(index))){ //this is a variable, the current value is peek value String var=parseVar(); return scope.get(var).peek(); } else { //this is an integer return parseInt(); } } } //read an integer private int parseInt(){ boolean negative=false; if(expression.charAt(index)=='-'){ negative=true; index++; } int ret=0; while(Character.isDigit(expression.charAt(index))){ ret*=10; ret+=expression.charAt(index)-'0'; index++; } if(negative) return -ret; return ret; } //read a variable private String parseVar(){ StringBuilder sb=new StringBuilder(); char c=expression.charAt(index); while(c!=' ' && c!=')'){ sb.append(c); c=expression.charAt(++index); } return sb.toString(); } }
class Context { unordered_map<string_view, int> _map; const Context *_parent{}; public: Context(const Context *parent) : _parent{parent} { ; } const Context* Parent() const { return _parent; } int GetValue(const string_view &key) const { auto it = _map.find(key); if (it != _map.end()) return it->second; if (_parent) return _parent->GetValue(key); assert(0); return numeric_limits<int>::min(); } void AddValue(const string_view &key, int val) { auto [it, isInserted] = _map.emplace(key, val); if (!isInserted) it->second = val; } }; class Solution { string_view symbol(string_view &expr) { string_view ret; if (expr.empty() || !isalpha(expr[0])) { return ret; } auto pos = expr.find_first_of(" )"); assert(pos != string_view::npos); ret = expr.substr(0, pos); expr.remove_prefix(pos); return ret; } int evaluate(string_view &expr, Context *context) { assert(!expr.empty()); if (expr[0] == '(') { assert(expr.length() >= 4); if (expr.substr(0, 4) == "(add") { assert(expr.length() > 4); expr.remove_prefix(4); assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); int l = evaluate(expr, context); assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); int r = evaluate(expr, context); assert(!expr.empty() && expr[0] == ')'); expr.remove_prefix(1); return l + r; } if (expr.substr(0, 4) == "(mul") { assert(expr.length() > 5); expr.remove_prefix(5); assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); int l = evaluate(expr, context); assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); int r = evaluate(expr, context); assert(!expr.empty() && expr[0] == ')'); expr.remove_prefix(1); return l * r; } if (expr.substr(0, 4) == "(let") { assert(expr.length() > 4); expr.remove_prefix(4); Context nc(context); while (1) { assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); string_view sym = symbol(expr); assert(!expr.empty()); if (sym.empty() || expr[0] == ')') { int ret{}; if (sym.empty()) { ret = evaluate(expr, &nc); } else { ret = nc.GetValue(sym); } assert(!expr.empty() && expr[0] == ')'); expr.remove_prefix(1); return ret; } assert(!expr.empty() && expr[0] == ' '); expr.remove_prefix(1); int value = evaluate(expr, &nc); nc.AddValue(sym, value); } assert(0); } } if (isdigit(expr[0]) || expr[0] == '-') { auto pos = expr.find_first_not_of("-0123456789"); auto len = min(expr.length(), pos); int num; if (auto [ptr, ec] = from_chars(expr.data(), expr.data()+len, num); ec == errc()) { expr.remove_prefix(len); } else { assert(0); } return num; } if (isalpha(expr[0])) { string_view sym = symbol(expr); assert(!expr.empty() && (expr[0] == ' ' || expr[0] == ')')); return context->GetValue(sym); } assert(0); return numeric_limits<int>::min(); } public: int evaluate(string expression) { string_view expr(expression); Context context(nullptr); return evaluate(expr, &context); } };
/** * @param {string} expression * @return {number} */ var evaluate = function(expression) { return helper(expression); }; const helper = (expr, map = {}) => { if (expr[0] !== '(') return /[0-9]|-/.test(expr[0]) ? +expr : map[expr]; map = Object.assign({}, map); const start = expr[1] === 'm' ? 6 : 5; const tokens = parse(expr.slice(start, expr.length - 1)); if (expr.startsWith('(m')) return helper(tokens[0], map) * helper(tokens[1], map); if (expr.startsWith('(a')) return helper(tokens[0], map) + helper(tokens[1], map); for (let i = 0; i < tokens.length - 2; i += 2) map[tokens[i]] = helper(tokens[i + 1], map); return helper(tokens.at(-1), map); } const parse = expr => { const tokens = []; let [builder, par] = ['', 0]; for (let ch of expr) { if (ch === '(') par++; if (ch === ')') par--; if (!par && ch === ' ') { tokens.push(builder); builder = ''; } else builder += ch; } return builder ? [...tokens, builder] : tokens; }
Parse Lisp Expression
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string. &nbsp; Example 1: Input: s = "YazaAay" Output: "aAa" Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa" is the longest nice substring. Example 2: Input: s = "Bb" Output: "Bb" Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring. Example 3: Input: s = "c" Output: "" Explanation: There are no nice substrings. &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s consists of uppercase and lowercase English letters.
class Solution: def longestNiceSubstring(self, s: str) -> str: def divcon(s): # string with length 1 or less arent considered nice if len(s) < 2: return "" pivot = [] # get every character that is not nice for i, ch in enumerate(s): if ch.isupper() and ch.lower() not in s: pivot.append(i) if ch.islower() and ch.upper() not in s: pivot.append(i) # if no such character return the string if not pivot: return s # divide the string in half excluding the char that makes the string not nice else: mid = (len(pivot)) // 2 return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len) return divcon(s)
class Solution { public String longestNiceSubstring(String s) { String result = ""; // take first index, go from 0 to length-1 of the string for (int i = 0;i<s.length(); i++){ // take second index, this should go up to the length of the string <= for (int j = i+1;j<=s.length(); j++){ //get the substring for the index range from i to j String temp = s.substring(i, j); // if length of the substring should be greater than 1 // if the length should be greater that the previous computed result // if the substring is valid Nice String // then update the result with the current substring from range i and j if (temp.length() > 1 && result.length() < temp.length() && checkNice(temp)) result = temp; } } return result; } //validate Nice String check public boolean checkNice(String temp){ //add substring to the set Set<Character> s = new HashSet<>(); for (char ch : temp.toCharArray()) s.add(ch); // return false If you do not find both lower case and upper case in the sub string //for e.g 'aAa' substring added to set will have both a and A in the substring which is valid // 'azaA' substring will fail for 'z' // 'aaaaaaaa' will return "" as result //make sure that the substring contains both lower and upper case for (char ch : s) if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch))) return false; return true; } }
class Solution { public: string longestNiceSubstring(string s) { int arr1[26]={}; int arr2[26]={}; if(s.length()<2) return ""; for(char ch:s) { if(ch>='A' && ch<='Z') arr1[(ch|32)-'a']++; else arr2[ch-'a']++; } vector<int> index; index.push_back(-1); for(int i=0;i<s.length();i++) { if((arr1[(s[i]|32)-'a']>=1 && arr2[(s[i]|32)-'a']==0) || (arr1[(s[i]|32)-'a']==0 && arr2[(s[i]|32)-'a']>=1)) index.push_back(i); } //index.push_back(2); index.push_back(s.length()); if(index.size()==2) return s; string minn=""; for(int i=0;i<index.size()-1;i++) { string temp = longestNiceSubstring(s.substr(index[i]+1,index[i+1]-index[i]-1)); minn = temp.length()>minn.length()?temp:minn; } return minn; } };
const swapCase = (str) => str.split('').map((c) => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()).join(''); var longestNiceSubstring = function(s) { let ans = ""; for (let i = 0; i < s.length; i++) { for (let ii = i + 1; ii < s.length + 1; ii++) { let substring = s.slice(i, ii); // we take a substring let invertedCaseChars = [...substring].map(swapCase); // we create an array of chars from the substring and invert case of this chars if (invertedCaseChars.every(char => substring.includes(char))) { // we check that substring includes every case inverted char (see the illustration above) ans = substring.length > ans.length ? substring : ans; // we select the longest substring which satisfies our condition } } } return ans };
Longest Nice Substring
Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y. &nbsp; Example 1: Input: nums = [0,1,2] Output: 0 Explanation: i=0: 0 mod 10 = 0 == nums[0]. i=1: 1 mod 10 = 1 == nums[1]. i=2: 2 mod 10 = 2 == nums[2]. All indices have i mod 10 == nums[i], so we return the smallest index 0. Example 2: Input: nums = [4,3,2,1] Output: 2 Explanation: i=0: 0 mod 10 = 0 != nums[0]. i=1: 1 mod 10 = 1 != nums[1]. i=2: 2 mod 10 = 2 == nums[2]. i=3: 3 mod 10 = 3 != nums[3]. 2 is the only index which has i mod 10 == nums[i]. Example 3: Input: nums = [1,2,3,4,5,6,7,8,9,0] Output: -1 Explanation: No index satisfies i mod 10 == nums[i]. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 0 &lt;= nums[i] &lt;= 9
class Solution: def smallestEqual(self, nums: List[int]) -> int: for idx, n in enumerate(nums): if idx%10==n: return idx return -1
class Solution { public int smallestEqual(int[] nums) { int index = 0; for (int i = 0 ; i < nums.length; i++) { if (index == nums[i]) { return i; } if (++index== 10) { index = 0; } } return -1; } }
class Solution { public: int smallestEqual(vector<int>& nums) { int i = 0; while (i < nums.size() && i % 10 != nums[i]) i++; return i >= nums.size() ? -1 : i; } };
/** * @param {number[]} nums * @return {number} */ var smallestEqual = function(nums) { return nums.findIndex((n, i) => i % 10 === n) };
Smallest Index With Equal Value
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]: lefti is the x coordinate of the left edge of the ith building. righti is the x coordinate of the right edge of the ith building. heighti is the height of the ith building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] &nbsp; Example 1: Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] Explanation: Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. Example 2: Input: buildings = [[0,2,3],[2,5,3]] Output: [[0,3],[5,0]] &nbsp; Constraints: 1 &lt;= buildings.length &lt;= 104 0 &lt;= lefti &lt; righti &lt;= 231 - 1 1 &lt;= heighti &lt;= 231 - 1 buildings is sorted by lefti in&nbsp;non-decreasing order.
class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: d = collections.defaultdict(list) for i,(start, end, height) in enumerate(buildings): d[start].append(height) d[end].append(-height) l = list(d.keys()) l.sort() result = [] active = [] for key in l: o = d[key] o.sort(reverse=True) for j in o: if j > 0: if not result or not active: result.append([key, j]) active.append(j) else: if j > active[-1]: result.append([key, j]) active.append(j) else: active.insert(bisect_left(active, j), j) else: idx = active.index(-j) if idx == len(active) - 1: active.pop() if active: result.append([key, active[-1]]) else: result.append([key, 0]) else: active.pop(idx) return result
class height implements Comparable<height>{ int val = -1; int pos = -1; boolean isStart = false; height(int a, int b, boolean c){ val = a; pos = b; isStart = c; } public int compareTo(height h){ if(this.pos != h.pos) return this.pos-h.pos; if(isStart) return -1; if(h.isStart) return 1; return this.val-h.val; } } class Solution { public List<List<Integer>> getSkyline(int[][] buildings) { PriorityQueue<height> mQ = new PriorityQueue<>(); int len = buildings.length; for(int[] b: buildings) { mQ.add(new height(b[2],b[0],true)); mQ.add(new height(b[2],b[1],false)); } PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder()); heap.add(0); int prevHeight = 0; List<List<Integer>> res = new ArrayList<>(); List<Integer> lst; while(mQ.size()>0) { height h = mQ.poll(); if(h.isStart){ heap.offer(h.val); } else { heap.remove(h.val); } if(prevHeight != heap.peek()){ lst = new ArrayList<>(); lst.add(h.pos); if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){ lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1))); res.remove(res.size()-1); } else lst.add(heap.peek()); res.add(lst); prevHeight = heap.peek(); } } return res; } }
/* 1.mark the starting and ending pt of each building -> let height of starting pt be negative and ending pt be positive [2,4,10] -> [[2,-10],[4,10]] 2.mark all consecutive building ->store every pair of x and y in pair sort it acc to x 3.get max y for all x values ->use heap-->(multiset) to store all buildings, insert new height of building else erase buiding height 4.remove pts of same height and store ans in results */ class Solution { public: vector<vector<int>> getSkyline(vector<vector<int>>& buildings) { //step1 vector<pair<int,int>> coordinate; for(auto building: buildings){ coordinate.push_back({building[0],-building[2]}); coordinate.push_back({building[1],building[2]}); } //step2 sort(coordinate.begin(), coordinate.end()); //step3 multiset<int,greater<int>> pq = {0}; vector<vector<int>> result; int prev = 0; for(auto p: coordinate){ if (p.second<0) pq.insert(-p.second); else pq.erase(pq.find(p.second)); int cur=*pq.begin(); if (prev!=cur) { result.push_back({p.first,cur}); prev=cur; } } return result; } };
var getSkyline = function(buildings) { let results = []; let points = []; for (let building of buildings) { points.push([building[0],building[2]]) points.push([building[1],-building[2]]) } let heights = []; points.sort((a,b)=>(b[1]-a[1])) points.sort((a,b)=>(a[0]-b[0])) for (let point of points) { if(point[1] >0) { heights.push(point[1]) } else { heights.splice(heights.indexOf(-point[1]),1) } let curHeight = (heights.length == 0?0:Math.max(...heights)) if(results.length == 0 || results[results.length-1][1] != curHeight) results.push([point[0], curHeight]); } return results; };
The Skyline Problem
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. &nbsp; Example 1: Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. Example 2: Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. Example 3: Input: intervals = [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. &nbsp; Constraints: 1 &lt;= intervals.length &lt;= 105 intervals[i].length == 2 -5 * 104 &lt;= starti &lt; endi &lt;= 5 * 104
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1) intervals.sort() res = 0 prevEnd = intervals[0][1] for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval else: # Overlapping when new interval starts in between or from the previous one res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2] prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last return res
// |-------| // |--| // |-------| //. |-------| // |-------| //. |-------| class Solution { public int eraseOverlapIntervals(int[][] intervals) { Arrays.sort(intervals, (a,b) -> a[0] - b[0]); int start = intervals[0][0]; int end = intervals[0][1]; int res = 0; for (int i = 1; i < intervals.length; i++){ int[] interval = intervals[i]; if(interval[0] >= start && interval[0] < end){ res++; if (interval[1] >= end) continue; } start = interval[0]; end = interval[1]; } return res; } }
class Solution { void solve(priority_queue <pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> &pq,int e,int &cnt){ while(!pq.empty() && pq.top().first<e){ e = min(e,pq.top().second); pq.pop(); cnt++; } } public: int eraseOverlapIntervals(vector<vector<int>>& grid) { priority_queue <pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > pq; for(int i =0; i<grid.size(); i++){ pq.push({grid[i][0],grid[i][1]}); } int cnt =0; while(!pq.empty()){ int e = pq.top().second; pq.pop(); solve(pq,e,cnt); } return cnt; } };
var eraseOverlapIntervals = function(intervals) { // sort by end's small to big intervals.sort((a, b) => a[1] - b[1]); let total = 1; let maxEnd = intervals[0][1]; for (let i = 1; i < intervals.length; i++) { let [start, end] = intervals[i]; if (start >= maxEnd) { total++; maxEnd = end } } return intervals.length - total; };
Non-overlapping Intervals
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order. &nbsp; Example 1: Input: changed = [1,3,4,2,6,8] Output: [1,3,4] Explanation: One possible original array could be [1,3,4]: - Twice the value of 1 is 1 * 2 = 2. - Twice the value of 3 is 3 * 2 = 6. - Twice the value of 4 is 4 * 2 = 8. Other original arrays could be [4,3,1] or [3,1,4]. Example 2: Input: changed = [6,3,0,1] Output: [] Explanation: changed is not a doubled array. Example 3: Input: changed = [1] Output: [] Explanation: changed is not a doubled array. &nbsp; Constraints: 1 &lt;= changed.length &lt;= 105 0 &lt;= changed[i] &lt;= 105
class Solution: def findOriginalArray(self, changed: List[int]) -> List[int]: counter = collections.Counter(changed) res = [] for k in counter.keys(): if k == 0: # handle zero as special case if counter[k] % 2 > 0: return [] res += [0] * (counter[k] // 2) elif counter[k] > 0: x = k # walk down the chain while x % 2 == 0 and x // 2 in counter: x = x // 2 # walk up and process all numbers within the chain. mark the counts as 0 while x in counter: if counter[x] > 0: res += [x] * counter[x] if counter[x+x] < counter[x]: return [] counter[x+x] -= counter[x] counter[x] = 0 x += x return res
class Solution { public int[] findOriginalArray(int[] changed) { Arrays.sort(changed); if(changed.length%2!=0) return new int[0]; int mid = changed.length/2; int[] res = new int[mid]; int[] freq = new int[100001]; for(int no : changed) freq[no]++; int idx=0; for(int no: changed){ if(freq[no] > 0 && no*2 <= 100000 && freq[no*2]>0){ freq[no]--; freq[no*2]--; res[idx++] = no; } } for(int i=0; i<freq.length; i++){ if(freq[i]!=0) return new int[0]; } return res; } }
class Solution { public: vector<int> findOriginalArray(vector<int>& changed) { unordered_map<int, int> freq; for (auto num : changed) freq[num]++; sort(changed.begin(), changed.end()); vector<int> res; for (auto num : changed) { if (freq[num] && freq[num*2]) { freq[num]--; freq[num*2]--; res.push_back(num); } } for (auto [a, b] : freq) if (b) return {}; return res; } };
// Idea is to sort the input array first then start traversing the array // now if we saw half of the current element before and that half is unmatched then // match both of them otherwise note the occurence of current element inorder // to match it with its double element in the future // Time -> O(nlogn) due to sorting // Space -> O(n) due to map /** * @param {number[]} changed * @return {number[]} */ var findOriginalArray = function(changed) { const n = changed.length if(n%2 === 1) return [] let original = [] let map = new Map() changed.sort((a,b) => { return a-b }) for(let ele of changed) { const half = ele/2 if(map.has(half) && map.get(half) > 0) { original.push(half) map.set(half, map.get(half)-1) } else { map.set(ele, map.has(ele) ? map.get(ele)+1: 1) } } if(original.length !== n/2) return [] return original };
Find Original Array From Doubled Array
You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 &lt;= i &lt; n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'. Return the minimum number of operations needed to make s equal to target. &nbsp; Example 1: Input: target = "10111" Output: 3 Explanation: Initially, s = "00000". Choose index i = 2: "00000" -&gt; "00111" Choose index i = 0: "00111" -&gt; "11000" Choose index i = 1: "11000" -&gt; "10111" We need at least 3 flip operations to form target. Example 2: Input: target = "101" Output: 3 Explanation: Initially, s = "000". Choose index i = 0: "000" -&gt; "111" Choose index i = 1: "111" -&gt; "100" Choose index i = 2: "100" -&gt; "101" We need at least 3 flip operations to form target. Example 3: Input: target = "00000" Output: 0 Explanation: We do not need any operations since the initial s already equals target. &nbsp; Constraints: n == target.length 1 &lt;= n &lt;= 105 target[i] is either '0' or '1'.
class Solution: def minFlips(self, target: str) -> int: flip = False res = 0 for c in target: if (c == '1') != flip: flip = not flip res += 1 return res
class Solution { public int minFlips(String target) { boolean lastBit = false; int flips = 0; for(int i=0;i<target.length();i++){ if(target.charAt(i)=='1' && !lastBit){ flips++; lastBit = !lastBit; } else if(target.charAt(i)=='0' && lastBit){ flips++; lastBit = !lastBit; } } return flips; } }
class Solution { public: int minFlips(string target) { int count=0; // we see thye number of times the change occur for(int i=0; i<target.size()-1;i++){ if(target[i] != target[i+1] ){ count++; }} if(target[0]=='0'){return count;} else{return count+1;} return 0; } };
var minFlips = function(target) { target = "0" + target; let count = (target.match(/01/g) || []).length * 2; return target[target.length -1] ==="0" ? count : count - 1; };
Minimum Suffix Flips
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. Example 2: Input: root = [1] Output: 0 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. -1000 &lt;= Node.val &lt;= 1000
def is_leaf(x): return x.left is None and x.right is None class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: if root is None: return 0 if root.left and is_leaf(root.left): left = root.left.val else: left = self.sumOfLeftLeaves(root.left) return left + self.sumOfLeftLeaves(root.right)
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; if(root.left!=null && root.left.left==null && root.left.right==null){ return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); }else{ return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); } } }
class Solution { int sum=0; public: bool solve(TreeNode* root){ if(root==NULL) return false; if(root->left==NULL && root->right==NULL) return true; if(solve(root->left)) sum+=root->left->val; solve(root->right); return false; } int sumOfLeftLeaves(TreeNode* root) { solve(root); return sum; } };
var sumOfLeftLeaves = function(root) { let total = 0; const go = (node, isLeft) => { if (isLeft && !node.left && !node.right) { total += node.val; return; } if (node.left) go(node.left, true); if (node.right) go(node.right, false) } go(root, false) return total; };
Sum of Left Leaves
You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks. &nbsp; Example 1: Input: tasks = [[1,2],[2,4],[4,8]] Output: 8 Explanation: Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. Example 2: Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]] Output: 32 Explanation: Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. Example 3: Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]] Output: 27 Explanation: Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6. &nbsp; Constraints: 1 &lt;= tasks.length &lt;= 105 1 &lt;= actual​i&nbsp;&lt;= minimumi&nbsp;&lt;= 104
class Solution: def minimumEffort(self, tasks: List[List[int]]) -> int: tasks.sort(key=lambda x: x[0]-x[1]) def ok(mid): for actual, minimum in tasks: if minimum > mid or actual > mid: return False if minimum <= mid: mid -= actual return True l, r = 0, 10 ** 9 while l <= r: mid = (l+r) // 2 if ok(mid): r = mid - 1 else: l = mid + 1 return l
import java.util.*; class Solution { public int minimumEffort(int[][] tasks) { Arrays.sort(tasks, new Comparator<int[]>(){ @Override public int compare(int[] a, int[] b) { return (b[1]-b[0])-(a[1]-a[0]); } }); int sum=0, max=0; for(int i=0;i<tasks.length;i++) { max=Math.max(max, sum+tasks[i][1]); sum+=tasks[i][0]; } return max; } }```
class Solution { public: int minimumEffort(vector<vector<int>>& tasks) { int diff=INT_MAX,ans=0; for(auto i : tasks){ diff=min(diff,i[1]-i[0]); ans+=i[0]; } int val=0; for(auto i : tasks) val=max(val,i[1]); return max(ans+diff,val); } };
var minimumEffort = function(tasks) { let minimumStartingEnergy = 0; let currentEnergy = 0; tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]) ); for (let task of tasks) { if (task[1] > currentEnergy) { minimumStartingEnergy += (task[1] - currentEnergy); currentEnergy = task[1]; } currentEnergy -= task[0]; } return minimumStartingEnergy; };
Minimum Initial Energy to Finish Tasks
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. &nbsp; Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Explanation: 1 + 2 + 4 = 7 There are no other valid combinations. Example 2: Input: k = 3, n = 9 Output: [[1,2,6],[1,3,5],[2,3,4]] Explanation: 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. Example 3: Input: k = 4, n = 1 Output: [] Explanation: There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. &nbsp; Constraints: 2 &lt;= k &lt;= 9 1 &lt;= n &lt;= 60
class Solution: def solve(self,k,target,ans,temp,idx,nums): if idx==len(nums): if target==0 and k==0: ans.append(list(temp)) return if nums[idx]<=target: temp.append(nums[idx]) self.solve(k-1,target-nums[idx],ans,temp,idx+1,nums) temp.pop() self.solve(k,target,ans,temp,idx+1,nums) def combinationSum3(self, k: int, n: int) -> List[List[int]]: ans = [] temp = [] idx = 0 nums = list(range(1,10)) self.solve(k,n,ans,temp,idx,nums) return ans
//Recursion class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); //int[] arr = new int{1,2,3,4,5,6,7,8,9}; List<Integer> ds = new ArrayList<>(); helper(1, n, k, ds, ans); return ans; } private static void helper(int i, int tar, int k, List<Integer> ds, List<List<Integer>> ans){ //base if(k == 0) { if(tar == 0){ ans.add(new ArrayList<>(ds)); } return; } if(tar == 0) return; //bcz if k is not zero and tar is zero then no possible valid combination if(i > tar) return; if(i > 9) return; //Take if(i <= tar) { ds.add(i); helper(i+1, tar - i, k-1 , ds, ans); ds.remove(ds.size()-1); } // Not take helper(i+1 , tar, k , ds, ans); return; } }
class Solution { public: vector<vector<int>> ans; //declare temp global vector in this vector we will store temprary combinations vector<int> temp; void solve(int k,int n,int order){ //check if our target became zero and combination size became zero then push temp vector inside the ans it means this temp vector combination having sum is equal to target and size of vector is equal to k if(n==0 && k==0){ ans.push_back(temp); return; } //check if our target is less than zero then return if(n<0) return; // take for loop and check for all posibility ahead of order for(int i=order;i<=9;i++){ //push current index value temp.push_back(i); // call solve function for further posiblity solve(k-1,n-i,i+1); //Pop last push value temp.pop_back(); } } vector<vector<int>> combinationSum3(int k, int n) { solve(k,n,1); return ans; } };
/** * @param {number} k * @param {number} n * @return {number[][]} */ var combinationSum3 = function(k, n) { const ans = []; const st = []; function dfs(start, t) { if (t === 0 && st.length === k) { ans.push(Array.from(st)); return; } for (let i = start; i <= 9 && st.length < k; i++) { if (i > t) break; st.push(i); dfs(i + 1, t - i); st.pop(); } } dfs(1, n); return ans; };
Combination Sum III
Given an array of integers&nbsp;nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue&nbsp;plus&nbsp;elements in nums&nbsp;(from left to right). Return the minimum positive value of&nbsp;startValue such that the step by step sum is never less than 1. &nbsp; Example 1: Input: nums = [-3,2,-3,4,2] Output: 5 Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2 Example 2: Input: nums = [1,2] Output: 1 Explanation: Minimum start value should be positive. Example 3: Input: nums = [1,-2,-3] Output: 5 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 100 -100 &lt;= nums[i] &lt;= 100
class Solution: def minStartValue(self, nums: List[int]) -> int: return max(1, 1 - min(accumulate(nums)))
class Solution { public int minStartValue(int[] nums) { int lowest_sum = 0; int sum = 0; for(int i=0; i<nums.length; i++) { sum += nums[i]; if(lowest_sum > sum) { lowest_sum = sum; } } return 1-lowest_sum; } }
class Solution { public: int minStartValue(vector<int>& nums) { int result=min(nums[0],0); for(int i=1;i<nums.size();i++){ nums[i]+=nums[i-1]; result = min(result,nums[i]); } return abs(result)+1; } };
var minStartValue = function(nums) { var min = 1; var sum = 0; for(var i=0;i<nums.length;i++){ sum = sum+nums[i]; min = Math.min(min,sum); } if(min == 1){ return min; } // add 1 to negative of min value obtained to keep the sum always positive return (-1*min)+1; };
Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 &lt;= i, j &lt; nums.length i != j nums[i] - nums[j] == k Notice that |val| denotes the absolute value of val. &nbsp; Example 1: Input: nums = [3,1,4,1,5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input: nums = [1,2,3,4,5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: nums = [1,3,1,5,4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1). &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -107 &lt;= nums[i] &lt;= 107 0 &lt;= k &lt;= 107
class Solution: def findPairs(self, nums: List[int], k: int) -> int: nums.sort() dict1={} s=0 res=[] for n in nums: if dict1.get(n,None) is not None: res.append(n) dict1[n+k]=n res=list(set(res)) return len(res)
// O(n) Time Solution class Solution { public int findPairs(int[] nums, int k) { Map<Integer, Integer> map = new HashMap(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int result = 0; for (int i : map.keySet()) if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1) result++; return result; } }
class Solution { public: int findPairs(vector<int>& nums, int k) { unordered_map<int,int> a; for(int i:nums) a[i]++; int ans=0; for(auto x:a) { if(k==0) { if(x.second>1) ans++; } else if(a.find(x.first+k)!=a.end()) ans++; } return ans; } };
var findPairs = function(nums, k) { nums.sort((a, b) => b - a); const { length } = nums; const hash = new Set(); let left = 0; let right = 1; while (left < length - 1) { while (right < length) { const diff = nums[left] - nums[right]; diff === k && hash.add(`${nums[left]},${nums[right]}`); diff > k ? right = length : right += 1; } left += 1; right = left + 1; } return hash.size; };
K-diff Pairs in an Array
Given the root of a binary tree, return the preorder traversal of its nodes' values. &nbsp; Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]. -100 &lt;= Node.val &lt;= 100 &nbsp; Follow up: Recursive solution is trivial, could you do it iteratively?
from collections import deque from typing import List, Optional class Solution: """ Time: O(n) """ def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if root is None: return [] queue = deque([root]) preorder = [] while queue: node = queue.pop() preorder.append(node.val) if node.right is not None: queue.append(node.right) if node.left is not None: queue.append(node.left) return preorder class Solution: """ Time: O(n) """ def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: return list(self.preorder_generator(root)) @classmethod def preorder_generator(cls, tree: Optional[TreeNode]): if tree is not None: yield tree.val yield from cls.preorder_generator(tree.left) yield from cls.preorder_generator(tree.right)
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); preorderTraversal2(root, result); return result; } public List<Integer> preorderTraversal2(TreeNode root,List<Integer> result) { if(root!=null){ result.add(root.val); if(root.left!=null){ preorderTraversal2(root.left,result); } if(root.right!=null){ preorderTraversal2(root.right,result); } } return result; } }
class Solution { void solve(TreeNode *root, vector<int> &ans){ if(root == NULL) return; ans.push_back(root->val); solve(root->left, ans); solve(root->right, ans); } public: vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; solve(root, ans); return ans; } };
var preorderTraversal = function(root) { let res = [] const check = node => { if(node === null) return else res.push(node.val) if(node.left !== null) check(node.left) if(node.right !== null) check(node.right) } check(root) return res };
Binary Tree Preorder Traversal
You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1. You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj. A friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests. Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not. Note: If uj and vj are already direct friends, the request is still successful. &nbsp; Example 1: Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]] Output: [true,false] Explanation: Request 0: Person 0 and person 2 can be friends, so they become direct friends. Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0). Example 2: Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]] Output: [true,false] Explanation: Request 0: Person 1 and person 2 can be friends, so they become direct friends. Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1). Example 3: Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]] Output: [true,false,true,false] Explanation: Request 0: Person 0 and person 4 can be friends, so they become direct friends. Request 1: Person 1 and person 2 cannot be friends since they are directly restricted. Request 2: Person 3 and person 1 can be friends, so they become direct friends. Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1). &nbsp; Constraints: 2 &lt;= n &lt;= 1000 0 &lt;= restrictions.length &lt;= 1000 restrictions[i].length == 2 0 &lt;= xi, yi &lt;= n - 1 xi != yi 1 &lt;= requests.length &lt;= 1000 requests[j].length == 2 0 &lt;= uj, vj &lt;= n - 1 uj != vj
class UnionFindSet(object): def __init__(self, n): self.data = range(n) def find(self, x): while x <> self.data[x]: x = self.data[x] return x def union(self, x, y): self.data[self.find(x)] = self.find(y) def speedup(self): for i in range(len(self.data)): self.data[i] = self.find(i) class Solution(object): def friendRequests(self, n, restrictions, requests): uf = UnionFindSet(n) ret = [True] * len(requests) for k, [x, y] in enumerate(requests): # Process Requests Sequentially xh = uf.find(x) # backup the head of x for undo uf.union(x, y) # link [x, y] and verify if any restriction triggers for [i, j] in restrictions: if uf.find(i) == uf.find(j): ret[k] = False break if not ret[k]: # if any restriction triggers, undo uf.data[xh] = xh else: uf.speedup() return ret
class Solution { int[] parent; boolean[] result; public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) { parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } result = new boolean[requests.length]; for (int i = 0; i < requests.length; i++) { // personA and personB can become friends if for all restrictions // person x_i and person y_i are not in the same set as personA and personB // and vice versa int personA = requests[i][0]; int personB = requests[i][1]; int personASetRepresentative = find(personA); int personBSetRepresentative = find(personB); boolean flag = true; for (int[] restriction : restrictions) { int blackListPersonARepresentative = find(restriction[0]); int blackListPersonBRepresentative = find(restriction[1]); if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) { flag = false; } if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) { flag = false; } } if (flag) { union(personA, personB); } result[i] = flag; } return result; } private int find(int node) { int root = node; while (parent[root] != root) { root = parent[root]; } //path compression int curr = node; while (parent[curr] != root) { int next = parent[curr]; parent[curr] = root; curr = next; } return root; } private boolean union(int node1, int node2) { int root1 = find(node1); int root2 = find(node2); if (root1 == root2) { return false; } parent[root2] = root1; return true; } }
/ Standard DSU Class class DSU { vector<int> parent, size; public: DSU(int n) { for(int i=0; i<=n; i++) { parent.push_back(i); size.push_back(1); } } int findParent(int num) { if(parent[num] == num) return num; return parent[num] = findParent(parent[num]); } // Directly getting parents of u and v // To avoid finding parent multiple times void unionBySize(int parU, int parV) { if(size[parU] < size[parV]) { size[parV] += size[parU]; parent[parU] = parV; } else { size[parU] += size[parV]; parent[parV] = parU; } } }; class Solution { public: vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) { DSU dsu(n); vector<bool> successful; for(auto& request : requests) { int u = request[0], v = request[1]; int parU = dsu.findParent(u), parV = dsu.findParent(v); bool flag = true; if(parU != parV) { // Check if current friend requested is restricted or not. for(auto& restriction : restrictions) { int restricted_U = restriction[0], restricted_V = restriction[1]; int restricted_parU = dsu.findParent(restricted_U); int restricted_parV = dsu.findParent(restricted_V); if((parU == restricted_parU && parV == restricted_parV) || (parU == restricted_parV && parV == restricted_parU)) { flag = false; break; } } // Union u and v by passing parents // Since it is already calculated above if(flag) { dsu.unionBySize(parU, parV); } } successful.push_back(flag); } return successful; } };
/* DSU Class Template */ class DSU { constructor() { this.parents = new Map(); this.rank = new Map(); } add(x) { this.parents.set(x, x); this.rank.set(x, 0); } find(x) { const parent = this.parents.get(x); if (parent === x) return x; const setParent = this.find(parent); this.parents.set(x, setParent); return setParent; } union(x, y) { const xParent = this.find(x), yParent = this.find(y); const xRank = this.rank.get(xParent), yRank = this.rank.get(yParent); if (xParent === yParent) return; if (xRank > yRank) { this.parents.set(yParent, xParent); } else if (yRank > xRank) { this.parents.set(xParent, yParent); } else { this.parents.set(xParent, yParent); this.rank.set(yParent, yRank + 1); } } } /* Friend Requests */ var friendRequests = function(n, restrictions, requests) { const dsu = new DSU(), result = []; for (let i = 0; i < n; i++) dsu.add(i); for (let [friend1, friend2] of requests) { const parent1 = dsu.find(friend1), parent2 = dsu.find(friend2); let friendshipPossible = true; for (let [enemy1, enemy2] of restrictions) { const enemyParent1 = dsu.find(enemy1), enemyParent2 = dsu.find(enemy2); const condition1 = (enemyParent1 === parent1 && enemyParent2 === parent2); const condition2 = (enemyParent1 === parent2 && enemyParent2 === parent1); if (condition1 || condition2) { friendshipPossible = false; break; } } if (friendshipPossible) dsu.union(friend1, friend2); result.push(friendshipPossible); } return result; };
Process Restricted Friend Requests
You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x. Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0. Note that you may have multiple coins of the same value. &nbsp; Example 1: Input: coins = [1,3] Output: 2 Explanation: You can make the following values: - 0: take [] - 1: take [1] You can make 2 consecutive integer values starting from 0. Example 2: Input: coins = [1,1,1,4] Output: 8 Explanation: You can make the following values: - 0: take [] - 1: take [1] - 2: take [1,1] - 3: take [1,1,1] - 4: take [4] - 5: take [4,1] - 6: take [4,1,1] - 7: take [4,1,1,1] You can make 8 consecutive integer values starting from 0. Example 3: Input: nums = [1,4,10,3,1] Output: 20 &nbsp; Constraints: coins.length == n 1 &lt;= n &lt;= 4 * 104 1 &lt;= coins[i] &lt;= 4 * 104
class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: coins.sort() res = 1 for coin in coins: if (res >= coin): res += coin return res
class Solution { public int getMaximumConsecutive(int[] coins) { if(coins.length==0 && coins==null) return 0; TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>(); for(int i:coins) map.put(i,map.getOrDefault(i,0)+1); int range=0; for(int i:map.keySet()){ if(range==0 && i==1) range=i*map.get(i); else if(range!=0 && range+1>=i) range+=i*map.get(i); else break; } return range+1; } }
class Solution { public: int getMaximumConsecutive(vector<int>& coins) { sort(coins.begin(), coins.end()); int n = coins.size(); int ans = 1; for(int i = 0; i < n; i++) { if(coins[i] > ans) return ans; ans += coins[i]; } return ans; } };
// we iterate from the smallest number while maintaining an integer sum. sum means that we can produce all number from 0 to sum. // when we can make numbers from 0 to sum, and we encounter a new number, lets say arr[2]. // it is obvious that we can create all numbers from sum to sum + arr[2]. // if there is a gap if(arr[i] > sum+1) it means no combinations could create that number and we stop. var getMaximumConsecutive = function(coins) { coins.sort((a,b) => a-b); let sum = 1; for(let i = 0; i < coins.length; i++) { if(coins[i] <= sum) { sum += coins[i]; } else { break; } } return sum; };
Maximum Number of Consecutive Values You Can Make
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums. &nbsp; Constraints: 3 &lt;= nums.length &lt;= 105 0 &lt;= nums[i] &lt;= 104
class Solution: def waysToSplit(self, nums: List[int]) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) ans = 0 for i in range(1, len(nums)): j = bisect_left(prefix, 2*prefix[i]) k = bisect_right(prefix, (prefix[i] + prefix[-1])//2) ans += max(0, min(len(nums), k) - max(i+1, j)) return ans % 1_000_000_007
class Solution { public int waysToSplit(int[] nums) { int size = nums.length; for (int i = 1; i < size; ++i) { nums[i] += nums[i - 1]; } int res = 0; int mod = 1_000_000_007; for (int i = 0; i < size - 2; ++i) { int left = searchLeft(nums, i, size - 1); int right = searchRight(nums, i, size - 1); if (left == -1 || right == -1) { continue; } res = (res + right - left + 1) % mod; } return res; } private int searchLeft(int[] nums, int left, int right) { int pos = -1; int min = nums[left]; int lo = left + 1, hi = right - 1; while (lo <= hi) { int mi = lo + (hi - lo) / 2; int mid = nums[mi] - min; int max = nums[right] - nums[mi]; if (mid < min) { lo = mi + 1; } else if (max < mid){ hi = mi - 1; } else { pos = mi; hi = mi - 1; } } return pos; } private int searchRight(int[] nums, int left, int right) { int pos = -1; int min = nums[left]; int lo = left + 1, hi = right - 1; while (lo <= hi) { int mi = lo + (hi - lo) / 2; int mid = nums[mi] - min; int max = nums[right] - nums[mi]; if (mid < min) { lo = mi + 1; } else if (max < mid){ hi = mi - 1; } else { pos = mi; lo = mi + 1; } } return pos; } }
class Solution { public: int waysToSplit(vector<int>& nums) { int n = nums.size(), mod = 1e9 + 7; long long ans = 0; vector<int> prefix(n); partial_sum(nums.begin(), nums.end(),prefix.begin()); for (int i = 0; i < n - 2; i++) { int left = prefix[i], remain = (prefix[n - 1] - prefix[i]); if (remain < left * 2) break; int leftPtr = lower_bound(prefix.begin() + i + 1, prefix.end() - 1, left * 2) - prefix.begin(); int rightPtr = upper_bound(prefix.begin() + i + 1, prefix.end() - 1, left + remain / 2) - prefix.begin() - 1; if (rightPtr - leftPtr + 1 > 0) ans += rightPtr - leftPtr + 1; } return ans % mod; } };
var waysToSplit = function(nums) { const mod = 1000000007; const lastIndex = nums.length - 2; const total = nums.reduce((sum, num) => sum + num) let midLeftPtr = -1; let midRightPtr = -1; let leftSum = 0; let midLeftSum = 0; let midRightSum = 0; let numWaysToSplit = 0; for (let leftPtr = 0; leftPtr < nums.length; leftPtr++) { leftSum += nums[leftPtr]; midLeftSum -= nums[leftPtr]; midRightSum -= nums[leftPtr]; // find the first index that satisfies the middle sum // being greater than or equal to the left sum while (midLeftPtr <= lastIndex && (midLeftPtr <= leftPtr || midLeftSum < leftSum)) { midLeftPtr++; midLeftSum += nums[midLeftPtr] } // find the first index that makes the middle sum greater than the right sum while (midRightPtr <= lastIndex && (midLeftPtr > midRightPtr || midRightSum <= total - midRightSum - leftSum)) { midRightPtr++ midRightSum += nums[midRightPtr] } numWaysToSplit = (numWaysToSplit + midRightPtr - midLeftPtr) % mod; } return numWaysToSplit };
Ways to Split Array Into Three Subarrays
Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows. The points are then calculated as follows: The target has integer scoring sections ranging from 0 to 11 inclusive. For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak &gt;= bk, then Alice takes k points. If ak &lt; bk, then Bob takes k points. However, if ak == bk == 0, then nobody takes k points. For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. &nbsp; Example 1: Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0] Output: [0,0,0,0,1,1,0,0,1,2,3,1] Explanation: The table above shows how the competition is scored. Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47. It can be shown that Bob cannot obtain a score higher than 47 points. Example 2: Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2] Output: [0,0,0,0,0,0,0,0,1,1,1,0] Explanation: The table above shows how the competition is scored. Bob earns a total point of 8 + 9 + 10 = 27. It can be shown that Bob cannot obtain a score higher than 27 points. &nbsp; Constraints: 1 &lt;= numArrows &lt;= 105 aliceArrows.length == bobArrows.length == 12 0 &lt;= aliceArrows[i], bobArrows[i] &lt;= numArrows sum(aliceArrows[i]) == numArrows
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: self.bestScore = 0 self.bestBobArrows = None def backtracking(k, remainArrows, score, bobArrows): if k == 12: if score > self.bestScore: self.bestScore = score self.bestBobArrows = bobArrows[::] return backtracking(k+1, remainArrows, score, bobArrows) # Bob loses # Bob wins arrowsNeeded = aliceArrows[k] + 1 if remainArrows >= arrowsNeeded: old = bobArrows[k] bobArrows[k] = arrowsNeeded # set new backtracking(k+1, remainArrows - arrowsNeeded, score + k, bobArrows) bobArrows[k] = old # backtrack backtracking(0, numArrows, 0, [0] * 12) # In case of having remain arrows then it means in all sections Bob always win # then we can distribute the remain to any section, here we simple choose first section. self.bestBobArrows[0] += numArrows - sum(self.bestBobArrows) return self.bestBobArrows
class Solution { int bobPoint = 0; int[] maxbob = new int[12]; public int[] maximumBobPoints(int numArrows, int[] aliceArrows) { int[] bob = new int[12]; calculate(aliceArrows, bob, 11, numArrows, 0); //Start with max point that is 11 return maxbob; } public void calculate(int[] alice, int[] bob, int index, int remainArr, int point) { if(index < 0 || remainArr <= 0) { if(remainArr > 0) bob[0] += remainArr; if(point > bobPoint) { // Update the max points and result output bobPoint = point; maxbob = bob.clone(); } return; } //part 1: assign 1 more arrow than alice if(remainArr >= alice[index]+1) { bob[index] = alice[index] + 1; calculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index); bob[index] = 0; } //part 2: assign no arrow and move to next point calculate(alice, bob, index-1, remainArr, point); bob[index] = 0; } }
class Solution { public: int maxscore; vector<int> ans; void helper(vector<int> &bob, int i, vector<int>& alice, int remarrows, int score) { if(i == -1 or remarrows <= 0) { if(score >= maxscore) { maxscore = score; ans = bob; } return; } helper(bob, i-1, alice, remarrows, score); if(remarrows > alice[i]) { bob[i] = alice[i] + 1; remarrows -= (alice[i] + 1); score += i; helper(bob, i-1, alice, remarrows, score); bob[i] = 0; } } vector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) { vector<int> bob(12, 0); maxscore = INT_MIN; helper(bob, 11, aliceArrows, numArrows, 0); int arrows_used = 0; for(int a : ans) arrows_used += a; if(arrows_used < numArrows) ans[0] += (numArrows - arrows_used); return ans; } };
var maximumBobPoints = function(numArrows, aliceArrows) { let max = 0, n = aliceArrows.length, res; backtrack(numArrows, 0, 0, Array(n).fill(0)); return res; function backtrack(arrows, idx, points, bobArrows) { if (idx === n || arrows === 0) { let origVal = bobArrows[n - 1]; if (arrows > 0) bobArrows[n - 1] += arrows; // put extra arrows in any slot if (points > max) { max = points; res = [...bobArrows]; } bobArrows[n - 1] = origVal; return; } backtrack(arrows, idx + 1, points, bobArrows); // don't use any arrows if (aliceArrows[idx] + 1 <= arrows) { // use aliceArrows[idx] + 1 arrows to gain idx points bobArrows[idx] = aliceArrows[idx] + 1; backtrack(arrows - (aliceArrows[idx] + 1), idx + 1, points + idx, bobArrows); bobArrows[idx] = 0; } } };
Maximum Points in an Archery Competition
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr. &nbsp; Example 1: Input: arr = [4,9,3], target = 10 Output: 3 Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer. Example 2: Input: arr = [2,3,5], target = 10 Output: 5 Example 3: Input: arr = [60864,25176,27249,21296,20204], target = 56803 Output: 11361 &nbsp; Constraints: 1 &lt;= arr.length &lt;= 104 1 &lt;= arr[i], target &lt;= 105
class Solution: def findBestValue(self, arr: List[int], t: int) -> int: def getsum(x): s = 0 for i in range(n): if arr[i] > x: s += x*(n-i) break else: s += arr[i] return s arr.sort() n = len(arr) l, r = 0, max(arr) ans = [inf, inf] while l <= r: m = l+(r-l)//2 if abs(getsum(m)-t) <= ans[0]: if abs(getsum(m)-t) == ans[0]: ans[1] = min(m, ans[1]) else: ans = [abs(getsum(m)-t), m] if getsum(m) > t: r = m-1 else: l = m+1 return ans[1]
class Solution { int max = 0; int len; public int findBestValue(int[] arr, int target) { this.len = arr.length; for (int i = 0; i < len; i++) max = Math.max(max, arr[i]); int l = 0; int r = max; while(l < r){ int mid = l + (r-l) / 2; if(check(arr, mid, target) <= check(arr, mid+1, target)) r = mid; else l = mid + 1; } return l; } private int check(int[] arr, int value, int target){ int sum = 0; for(int e : arr){ if(e > value) sum += value; else sum += e; } return Math.abs(sum-target); } }
// This Question Includes Both Binary Search And bit of Greedy Concept also. // See We Know Ans Always Lies Between 0 and maximum element according to given question condition Because // sum value at maximum element is same as any other element greater than it. // So we get our sum from getval function after that you need to choose as to move forward(l = mid+1) or backward // i.e.(h = mid-1) so if sum value we obtain is less than target then l = mid+1 why so?? // Because 2 3 5 lets suppose you are having this array if we pick 2 as mid then sum value will be 6 whereas if we pick 3 then sum value will be 8 and 10 when we pick 5 so notice that sum will increase when we increase value and // correspondingly decrease when we decrease value...So yess This is all what we did and got Accepted. class Solution { public: int getval(int mid , vector<int>&arr) { int sum = 0; for(int i = 0 ; i < arr.size() ; i++) { if(arr[i] > mid) sum+=mid; else sum+=arr[i]; } return sum; } int findBestValue(vector<int>& arr, int target) { int n = arr.size(); int l = 0 , h = *max_element(arr.begin(),arr.end()); int ans = 0, min1 = INT_MAX; while(l<=h) { int mid = l + (h-l)/2; int k = getval(mid,arr); if(k==target) { return mid; } else if(k<target) { l = mid+1; } else h = mid -1; int j = abs(k - target); if(j<min1) { min1 = j; ans = mid; } else if(j==min1) { ans = min(ans , mid); } } return ans; } };
/** * @param {number[]} arr * @param {number} target * @return {number} */ var findBestValue = function(arr, target) { const sortedArr = [...arr].sort(function (a, b) { return a - b; }); var lowestValue = Math.min(sortedArr[arr.length-1], Math.floor(target/arr.length)); var higestValue = Math.min(sortedArr[arr.length-1], target); var value, deltaLeft, deltaRight; while (true) { candidateRight = Math.ceil((lowestValue + higestValue)/2) candidateLeft = candidateRight - 1 deltaLeft = calculateDeltaForCandidate(sortedArr, target, candidateLeft) if (deltaLeft == 0) { return candidateLeft } deltaRight = calculateDeltaForCandidate(sortedArr, target, candidateRight) if (deltaRight == 0) { return candidateRight } if (deltaRight == 0) { return candidateRight } if (candidateRight == higestValue) { return deltaLeft <= deltaRight ? candidateLeft : candidateRight; } if (deltaLeft <= deltaRight) { higestValue = candidateLeft } else { lowestValue = candidateRight } } }; var calculateDeltaForCandidate = function(sArr, target, candidate) { var sum //find idx lover then candidate for (var i=0; i < sArr.length; i++) { if (sArr[i] >= candidate) { sum = sArr.slice(0, i).reduce((partialSum, a) => partialSum + a, 0) + (sArr.length - i) * candidate; return Math.abs(sum - target) }; } return NaN };
Sum of Mutated Array Closest to Target
Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string. &nbsp; Example 1: Input: word1 = "aaaa", word2 = "bccb" Output: false Explanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb". The difference is 4, which is more than the allowed 3. Example 2: Input: word1 = "abcdeef", word2 = "abaaacc" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 1 time in word1 and 4 times in word2. The difference is 3. - 'b' appears 1 time in word1 and 1 time in word2. The difference is 0. - 'c' appears 1 time in word1 and 2 times in word2. The difference is 1. - 'd' appears 1 time in word1 and 0 times in word2. The difference is 1. - 'e' appears 2 times in word1 and 0 times in word2. The difference is 2. - 'f' appears 1 time in word1 and 0 times in word2. The difference is 1. Example 3: Input: word1 = "cccddabba", word2 = "babababab" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 2 times in word1 and 4 times in word2. The difference is 2. - 'b' appears 2 times in word1 and 5 times in word2. The difference is 3. - 'c' appears 3 times in word1 and 0 times in word2. The difference is 3. - 'd' appears 2 times in word1 and 0 times in word2. The difference is 2. &nbsp; Constraints: n == word1.length == word2.length 1 &lt;= n &lt;= 100 word1 and word2 consist only of lowercase English letters.
class Solution: def checkAlmostEquivalent(self, w1: str, w2: str) -> bool: return all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())
class Solution { public boolean checkAlmostEquivalent(String word1, String word2) { Map<Character,Integer> map = new HashMap(); for (int i = 0; i < word1.length(); i++) { map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1); map.put(word2.charAt(i), map.getOrDefault(word2.charAt(i), 0) - 1); } for (int i : map.values()) { //get value set if (i > 3 || i < -3) { return false; } } return true; } }
class Solution { public: bool checkAlmostEquivalent(string word1, string word2) { unordered_map<char, int> m; for(int i = 0; i < word1.size(); i++){ m[word1[i]]++; } for(int i = 0; i < word2.size(); i++){ m[word2[i]]--; } for(auto i : m){ if(abs(i.second) > 3){ return false; } } return true; } };
var checkAlmostEquivalent = function(word1, word2) { const hm = new Map() const addToHm = (ch, add) => { if (hm.has(ch)) hm.set(ch, hm.get(ch) + (add ? +1 : -1)) else hm.set(ch, (add ? +1 : -1)) } for (let i = 0; i < word1.length; i++) { addToHm(word1[i], true) addToHm(word2[i], false) } for (const val of hm.values()) if (Math.abs(val) > 3) return false return true };
Check Whether Two Strings are Almost Equivalent
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. &nbsp; Example 1: Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. Example 2: Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window. Example 3: Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. &nbsp; Constraints: m == s.length n == t.length 1 &lt;= m, n&nbsp;&lt;= 105 s and t consist of uppercase and lowercase English letters. &nbsp; Follow up: Could you find an algorithm that runs in O(m + n) time?
# Added on 2022-08-18 15:51:55.963915 var minWindow = function(s, t) { const tf = {}, sf = {}; for(let c of t) { tf[c] = (tf[c] || 0) + 1; } let l = 0, r = 0, rs = t.length; let ml = -1, mr = -1; for(; r < s.length; r++) { const c = s[r]; if(!tf[c]) continue; const sc = sf[c] || 0; sf[c] = sc + 1; if(sf[c] <= tf[c]) { rs--; } if(rs == 0) { while(true) { if(mr == -1 || mr - ml > r - l) { [mr, ml] = [r, l]; } const c = s[l]; if(!tf[c]) { l++; } else if(sf[c] - 1 < tf[c]) { sf[c]--, l++, rs++; break; } else { sf[c]--; l++; } } } } if(mr == -1) return ''; return s.slice(ml, mr + 1); };
class Solution { public String minWindow(String s, String t) { HashMap<Character, Integer> child = new HashMap<>(); HashMap<Character, Integer> parent = new HashMap<>(); int left = -1, right = -1, match = 0; String window = ""; for(int i = 0; i < t.length(); i++){ char c = t.charAt(i); child.put(c, child.getOrDefault(c, 0) + 1); //Child frequency map } while(true){ boolean f1 = false, f2 = false; while(right < s.length() - 1 && match < t.length()){ right++; char c = s.charAt(right); parent.put(c, parent.getOrDefault(c, 0) + 1); // Acquiring characters till if(parent.getOrDefault(c, 0) <= child.getOrDefault(c, 0)) // match count is equal match++; f1 = true; } while(left < right && match == t.length()){ String potstring = s.substring(left + 1, right + 1); if(window.length() == 0 || window.length() > potstring.length()) window = potstring; //Calculating length of window left++; char c = s.charAt(left); parent.put(c, parent.getOrDefault(c, 0) - 1); if(parent.get(c) == 0) //Releasing characters by parent.remove(c); //left pointer for finding smallest window if(parent.getOrDefault(c, 0) < child.getOrDefault(c, 0)) match--; f2 = true; } if(f1 == false && f2 == false) break; } return window; } }
class Solution { public: string minWindow(string s, string t) { unordered_map<char,int> ump; for(auto i:t){ ump[i]++; } int i =0,j =0,count =0; int ans =INT_MAX,answer =0; for (;j < s.size();j++) { if(ump[s[j]]>0) { count++; } ump[s[j]]--; if(count==t.size()){ while (i < j && ump[s[i]]<0) { ump[s[i]]++; i++; } if(ans > j-i+1){ ans = j-i+1; answer = i; } ump[s[i]]++; i++; count--; } } return ans==INT_MAX?"":s.substr(answer,ans); } };
var minWindow = function(s, t) { const tf = {}, sf = {}; for(let c of t) { tf[c] = (tf[c] || 0) + 1; } let l = 0, r = 0, rs = t.length; let ml = -1, mr = -1; for(; r < s.length; r++) { const c = s[r]; if(!tf[c]) continue; const sc = sf[c] || 0; sf[c] = sc + 1; if(sf[c] <= tf[c]) { rs--; } if(rs == 0) { while(true) { if(mr == -1 || mr - ml > r - l) { [mr, ml] = [r, l]; } const c = s[l]; if(!tf[c]) { l++; } else if(sf[c] - 1 < tf[c]) { sf[c]--, l++, rs++; break; } else { sf[c]--; l++; } } } } if(mr == -1) return ''; return s.slice(ml, mr + 1); };
Minimum Window Substring
You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively. &nbsp; Example 1: Input: memory1 = 2, memory2 = 2 Output: [3,1,0] Explanation: The memory is allocated as follows: - At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory. - At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory. - At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively. Example 2: Input: memory1 = 8, memory2 = 11 Output: [6,0,4] Explanation: The memory is allocated as follows: - At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory. - At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory. - At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory. - At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory. - At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory. - At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively. &nbsp; Constraints: 0 &lt;= memory1, memory2 &lt;= 231 - 1
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: inverted = False if memory2>memory1: memory2, memory1 = memory1, memory2 inverted = True #Compute the number of steps in first stage - 1 i_start = solve_quadratic(1,2*(memory1-memory2)) memory1-= i_start*(i_start+1)//2 if memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion) inverted = False #Compute number of steps in stage - 2 n_end = solve_quadratic((i_start+1), memory2) #Compute sums of respective arithmetic sequences i_end_1 = i_start - 1 + 2*n_end i_end_2 = i_start + 2*n_end sum1 = n_end * (i_start+1 + i_end_1)//2 sum2 = n_end * (i_start+2 + i_end_2)//2 #Compute updated memories memory1-=sum1 memory2-=sum2 full_cnt=2*n_end+i_start if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it. memory1-=(i_end_2+1) full_cnt+=1 return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2] ```
class Solution { public int[] memLeak(int memory1, int memory2) { int i = 1; while(Math.max(memory1, memory2) >= i){ if(memory1 >= memory2) memory1 -= i; else memory2 -= i; i++; } return new int[]{i, memory1, memory2}; } }
class Solution { public: vector<int> memLeak(int memory1, int memory2) { int time = 1; while (max(memory1, memory2) >= time) { if (memory1 >= memory2) { memory1 -= time; } else { memory2 -= time; } ++time; } return {time, memory1, memory2}; } };
var memLeak = function(memory1, memory2) { var count=1; while(true) { if(memory1>=memory2 && memory1>=count) memory1-=count; else if(memory2>=memory1 && memory2>=count) memory2-=count else return [count, memory1, memory2]; count++; } };
Incremental Memory Leak
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1. &nbsp; Example 1: Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. Example 2: Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved. Example 3: Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]] &nbsp; Constraints: board.length == 2 board[i].length == 3 0 &lt;= board[i][j] &lt;= 5 Each value board[i][j] is unique.
class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: def findNei(board): directs = [[0, 1], [0, -1], [1, 0], [-1, 0]] boards = [] for i in range(2): for j in range(3): if board[i][j] == 0: for dr, dc in directs: tmp = [row.copy() for row in board] r, c = i + dr, j + dc if r in range(2) and c in range(3): tmp[r][c], tmp[i][j] = tmp[i][j], tmp[r][c] boards.append(tmp) return boards visited = set() target = [[1, 2, 3], [4, 5, 0]] if board == target: return 0 rows, cols = len(board), len(board[0]) q = collections.deque() step = 1 for row in range(rows): for col in range(cols): if board[row][col] == 0: boards = findNei(board) for b in boards: if b == target: return step visited.add(tuple([tuple(row) for row in b])) q.append(b) break while q: step += 1 for _ in range(len(q)): b = q.popleft() boards = findNei(b) for b in boards: if b == target: return step t = tuple([tuple(row) for row in b]) if t not in visited: visited.add(t) q.append(b) return -1
class Solution { int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}}; public int slidingPuzzle(int[][] board) { String tar="123450"; String src=""; for(int i =0;i<board.length;i++){ for(int j=0;j<board[i].length;j++){ src+=board[i][j]; } } HashSet<String> visited=new HashSet<>(); visited.add(src); int level=0; ArrayDeque<String> q=new ArrayDeque<>(); q.add(src); while(q.size()!=0){ int t=q.size(); while(t-->0){ String rem=q.remove(); if(rem.equals(tar)){ return level; } int idx=-1; for(int i=0;i<rem.length();i++){ if(rem.charAt(i)=='0'){ idx=i; break; } } for(int i =0;i<dir[idx].length;i++){ String str=swapEle(rem,idx,dir[idx][i]); if(!visited.contains(str)){ q.add(str); visited.add(str); } } } level++; } return -1; } public String swapEle(String rem,int i,int j){ StringBuilder sb=new StringBuilder(rem); sb.setCharAt(i,rem.charAt(j)); sb.setCharAt(j,rem.charAt(i)); return sb.toString(); } }
class Node{ public: int row; int col; vector<vector<int>>state; }; class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { vector<vector<int>>target={{1,2,3},{4,5,0}}; queue<Node>q; int n=2; int m=3; vector<vector<int>>dir={{1,0},{-1,0},{0,1},{0,-1}}; for(int i=0;i<board.size();i++) for(int j=0;j<board[0].size();j++){ if(board[i][j]==0){ q.push({i,j,board}); break; } } set<vector<vector<int>>>set; set.insert(q.front().state); int ladder=0; while(!q.empty()){ int size=q.size(); for(int i=0;i<size;i++){ Node curr=q.front(); q.pop(); if(curr.state==target) return ladder; int row=curr.row; int col=curr.col; for(auto &x:dir){ int r=x[0]+row; int c=x[1]+col; if(r<n && r>=0 && c<m && c>=0 ){ swap(curr.state[r][c],curr.state[row][col]) ; if(set.find(curr.state)==set.end()){ set.insert(curr.state); q.push({r,c,curr.state}); } swap(curr.state[r][c],curr.state[row][col]) ; } } } ladder++; } return -1; } };
/** * @param {number[][]} board * @return {number} */ class BoardState { constructor(board, currStep) { this.board = this.copyBoard(board); this.boardString = this.flatToString(board); this.emptyIndex = this.findIndexOf0(board); this.currStep = currStep; } findIndexOf0(board) { for(let i = 0; i < board.length; i++) { for (let j = 0; j < board[i].length; j++) { if(board[i][j] === 0) return [i, j]; } } return null; } copyBoard(board) { const newBoard = []; board.forEach((row) => { newBoard.push([...row]); }); return newBoard; } flatToString(board) { let str = ''; for(let i = 0; i < board.length; i++) { for (let j = 0; j < board[i].length; j++) { str += board[i][j]; } } return str; } } var slidingPuzzle = function(board) { let queue = [new BoardState(board, 0)]; let set = new Set(); const x = board.length, y = board[0].length; const switchMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]]; let slide = (i, j, newi, newj, currBoardState) => { if (newi < 0 || newj < 0 || newi >= x || newj >= y) { return null; } const newBoard = currBoardState.copyBoard(currBoardState.board); const temp = newBoard[i][j]; newBoard[i][j] = newBoard[newi][newj]; newBoard[newi][newj] = temp; const newBoardState = new BoardState(newBoard, currBoardState.currStep + 1); return newBoardState } while(queue.length > 0) { const currBoardState = queue.shift(); set.add(currBoardState.boardString); if(currBoardState.boardString === '123450') { return currBoardState.currStep; } const [i, j] = currBoardState.emptyIndex; switchMoves.forEach((move) => { const newBoardState = slide(i, j, i + move[0], j + move[1], currBoardState); if (newBoardState && !set.has(newBoardState.boardString)) { queue.push(newBoardState); } }); } return -1; };
Sliding Puzzle
An n-bit gray code sequence is a sequence of 2n integers where: Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differs by exactly one bit, and The binary representation of the first and last integers differs by exactly one bit. Given an integer n, return any valid n-bit gray code sequence. &nbsp; Example 1: Input: n = 2 Output: [0,1,3,2] Explanation: The binary representation of [0,1,3,2] is [00,01,11,10]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit Example 2: Input: n = 1 Output: [0,1] &nbsp; Constraints: 1 &lt;= n &lt;= 16
import math class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)] grayCodes = [0] for diff in allowedDiffs: grayCodes += [code + diff for code in reversed(grayCodes)] return grayCodes
class Solution { public List<Integer> grayCode(int n) { ArrayList list=new ArrayList(); for(int i=0;i<(1<<n);i++){ list.add(i^(i>>1)); } return list; } }
class Solution { public: vector<int> grayCode(int n) { vector<int> dp = {0,1}; int cnt = 1; for(int i = 2; i < n+1; i++) { int mod = pow(2, cnt); int index = dp.size()-1; while(index >= 0) { dp.push_back(dp[index] + mod); index--; } cnt++; } return dp; } };
/** * @param {number} n * @return {number[]} */ var grayCode = function(n) { return binaryToInt(dfs(n, ['0', '1'])) }; const dfs = (n, arr) => { if (n === 1) return arr const revArr = [...arr].reverse() addOneBefore('0', arr) addOneBefore('1', revArr) return dfs(n - 1, [...arr, ...revArr]) } const addOneBefore = (e, arr) => { for (let i = 0; i < arr.length; i++) { arr[i] = e + arr[i] } } const binaryToInt = (arr) => { for (let i = 0; i < arr.length; i++){ arr[i] = parseInt(arr[i], 2) } return arr }
Gray Code
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: multiply the number on display by 2, or subtract 1 from the number on display. Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator. &nbsp; Example 1: Input: startValue = 2, target = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -&gt; 4 -&gt; 3}. Example 2: Input: startValue = 5, target = 8 Output: 2 Explanation: Use decrement and then double {5 -&gt; 4 -&gt; 8}. Example 3: Input: startValue = 3, target = 10 Output: 3 Explanation: Use double, decrement and double {3 -&gt; 6 -&gt; 5 -&gt; 10}. &nbsp; Constraints: 1 &lt;= startValue, target &lt;= 109
class Solution(object): def brokenCalc(self, startValue, target): """ :type startValue: int :type target: int :rtype: int """ res = 0 while target > startValue: res += 1 if target % 2: target += 1 else: target //= 2 return res + startValue - target
class Solution { public int brokenCalc(int startValue, int target) { if(startValue >= target) return startValue - target; if(target % 2 == 0){ return 1 + brokenCalc(startValue, target / 2); } return 1 + brokenCalc(startValue, target + 1); } }
class Solution { public: int brokenCalc(int startValue, int target) { int result=0; while(target>startValue) { result++; if(target%2==0) target=target/2; else target+=1; } result=result+(startValue-target); return result; } };
/** * @param {number} startValue * @param {number} target * @return {number} */ var brokenCalc = function(startValue, target) { let steps = 0; while(target !== startValue){ if(startValue > target){ return steps + startValue - target; } if(target %2 === 0){ target /= 2; }else { target += 1; } steps++; } return steps };
Broken Calculator
You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. &nbsp; Example 1: Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: num = 9973 Output: 9973 Explanation: No swap. &nbsp; Constraints: 0 &lt;= num &lt;= 108
class Solution: def maximumSwap(self, num: int) -> int: digits = [int(x) for x in str(num)] n = len(digits) for i in range(n): maxx = digits[i] indx = i for j in range(i+1,n): if digits[j]>=maxx and digits[j]!=digits[i]: maxx = digits[j] indx = j if indx!=i: digits[i],digits[indx] = digits[indx],digits[i] #only one swap allowed return "".join([str(x) for x in digits]) #already sorted return num
class Solution { public int maximumSwap(int num) { char str[]=String.valueOf(num).toCharArray(); char arr[]=str.clone(); Arrays.sort(arr); int i=0; int j=str.length-1; while(i<str.length && j>=0 && arr[j]==str[i]){i++;j--;} int search=j; if(i==str.length) return num; j=str.length-1; while(arr[search]!=str[j]){j--;} char c=str[i]; str[i]=str[j]; str[j]=c; return Integer.parseInt(new String(str)); } }
class Solution { public: int maximumSwap(int num) { string st_n=to_string(num); int maxNum=-1,maxIdx=-1; int leftidx=-1,rightidx=-1; for(int i=st_n.size()-1;i>=0;i--) { if(st_n[i]>maxNum) { maxNum=st_n[i]; maxIdx=i; continue; } if(st_n[i]<maxNum) { leftidx=i; rightidx=maxIdx; } } if(leftidx==-1) return num; swap(st_n[leftidx],st_n[rightidx]); return stoi(st_n); } };
var maximumSwap = function(num) { const nums = `${num}`.split(''); for (let index = 0; index < nums.length - 1; index++) { const current = nums[index]; const diff = nums.slice(index + 1); const max = Math.max(...diff); if (current >= max) continue; const swapIndex = index + diff.lastIndexOf(`${max}`) + 1; [nums[index], nums[swapIndex]] = [nums[swapIndex], nums[index]]; break; } return nums.join(''); };
Maximum Swap
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem&nbsp;in O(1)&nbsp;extra space complexity and O(n) time complexity. &nbsp; Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4] &nbsp; Constraints: The number of nodes in the linked list is in the range [0, 104]. -106 &lt;= Node.val &lt;= 106
class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return odd, even_start, even = head, head.next, head.next while odd is not None and even is not None: odd.next = even.next if odd.next is not None: odd = odd.next even.next = odd.next even = even.next else: break odd.next = even_start return head
class Solution { public ListNode oddEvenList(ListNode head) { if(head == null) { return head; } ListNode result = head, evenHalf = new ListNode(0), evenHalfPtr = evenHalf; for(; head.next != null; head = head.next) { evenHalfPtr = evenHalfPtr.next = head.next; head.next = head.next.next; evenHalfPtr.next = null; if(head.next == null) { break; } } head.next = evenHalf.next; return result; } }
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head == NULL || head->next == NULL || head->next->next == NULL){ return head; } ListNode *first = head; ListNode *second = head->next; ListNode *last = head; int count = 1; while(last->next != NULL){ last = last->next; count++; } int n = count/2; while(n != 0){ first->next = second->next; last->next = second; second->next = NULL; first = first->next; last = second; second = first->next; n--; } return head; } };
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var oddEvenList = function(head) { if (!head || !head.next) return head; let oddNode = head; const evenHead = head.next; let evenNode = head.next; while(evenNode?.next) { oddNode.next = evenNode.next; oddNode = oddNode.next; evenNode.next = oddNode.next; evenNode = evenNode.next; } oddNode.next = evenHead; return head; };
Odd Even Linked List
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. &nbsp; Example 1: Input: accounts = [[1,2,3],[3,2,1]] Output: 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. Example 2: Input: accounts = [[1,5],[7,3],[3,5]] Output: 10 Explanation: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. Example 3: Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] Output: 17 &nbsp; Constraints: m ==&nbsp;accounts.length n ==&nbsp;accounts[i].length 1 &lt;= m, n &lt;= 50 1 &lt;= accounts[i][j] &lt;= 100
class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: return max(map(sum, accounts))
class Solution { public int maximumWealth(int[][] accounts) { int res = 0; for(int i =0;i<accounts.length;i++){ int temp = 0; for(int j = 0;j<accounts[i].length;j++){ temp+=accounts[i][j]; } res = Math.max(res,temp); } return res; } }
class Solution { public: int maximumWealth(vector<vector<int>>& accounts) { int maxWealth = 0; for (auto account : accounts) { int currentSum = 0; for (int x : account) currentSum += x; if (currentSum > maxWealth) maxWealth = currentSum; } return maxWealth; } };
var maximumWealth = function(accounts) { var res = 0; for(var i =0;i<accounts.length;i++){ var temp = 0; for(var j = 0;j<accounts[i].length;j++){ temp+=accounts[i][j]; } res = Math.max(res,temp); } return res; };
Richest Customer Wealth
You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. &nbsp; Example 1: Input: s = "1001010", k = 5 Output: 5 Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal. Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively. The length of this subsequence is 5, so 5 is returned. Example 2: Input: s = "00101001", k = 1 Output: 6 Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal. The length of this subsequence is 6, so 6 is returned. &nbsp; Constraints: 1 &lt;= s.length &lt;= 1000 s[i] is either '0' or '1'. 1 &lt;= k &lt;= 109
class Solution: def longestSubsequence(self, s: str, k: int) -> int: end, n = len(s)-1, s.count("0") while end >=0 and int(s[end:], 2)<= k: end-=1 return n+ s[end+1:].count("1")
class Solution { public int longestSubsequence(String s, int k) { int numOfZeros = 0; int numOfOnes = 0; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(ch == '0'){ numOfZeros++; } } int sum = 0; for(int i = s.length() - 1; i >= 0; i--){ char ch = s.charAt(i); if(ch == '1'){ double val = Math.pow(2, s.length() - i - 1); sum += val; if(sum <= k){ numOfOnes++; } } } return numOfZeros + numOfOnes; } }
class Solution { public: int ans = 0; int f(int i,int size, int sum, string &s, vector<vector<int>>&dp){ if(i<0){ return 0; } if(dp[i][size] != -1){ return dp[i][size]; } int no = f(i-1,size,sum,s,dp); int yes = 0; if((sum-(s[i]-'0')*pow(2,size)) >=0){ yes = 1+ f(i-1,size+1,(sum-(s[i]-'0')*pow(2,size)),s,dp); } return dp[i][size]=max(no,yes); } int longestSubsequence(string s, int k) { int n = s.size(); vector<vector<int>>dp(n,vector<int>(n,-1)); return f(n-1,0,k,s,dp); } };
/** * @param {string} s * @param {number} k * @return {number} */ var longestSubsequence = function(s, k) { let count = 0; let j = s.length - 1; // starting from the last digit let i = 0; // binary number position let acc = 0; while(j >= 0){ let positionNumber = Number(s[j]) * Math.pow(2, i); j--; i++; if(acc + positionNumber > k) continue; acc += positionNumber; count++; } return count; };
Longest Binary Subsequence Less Than or Equal to K
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged&nbsp;IP address&nbsp;replaces every period "." with "[.]". &nbsp; Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" &nbsp; Constraints: The given address is a valid IPv4 address.
class Solution: def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]')
class Solution { public String defangIPaddr(String address) { return address.replace(".","[.]"); } }
class Solution { public: string defangIPaddr(string address) { string res; for(int i=0;i<address.length();i++){ if(address[i]=='.'){ res+="[.]"; } else{ res+=address[i]; } } return res; } };
var defangIPaddr = function(address) { return address.split("").map((x)=>{ if(x=='.') return "[.]" else return x }).join("") };
Defanging an IP Address
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike. Otherwise, return false. &nbsp; Example 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. Example 2: Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. &nbsp; Constraints: 2 &lt;= s.length &lt;= 1000 s.length is even. s consists of uppercase and lowercase letters.
vowels = "aeiouAEIOU" class Solution: def halvesAreAlike(self, S: str) -> bool: mid, ans = len(S) // 2, 0 for i in range(mid): if S[i] in vowels: ans += 1 if S[mid+i] in vowels: ans -=1 return ans == 0
class Solution { public boolean halvesAreAlike(String s) { //add vowels to the set Set<Character> set = new HashSet<>(); set.add('a'); set.add('e'); set.add('i'); set.add('o'); set.add('u'); set.add('A'); set.add('E'); set.add('I'); set.add('O'); set.add('U'); //find the mid int mid = s.length() / 2; int count = 0; //increment the count for left half, decrement count for the second half if its a vowel for (int i = 0; i < s.length(); i++) count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0; //finally count should be 0 to match left and right half return count == 0; } }
class Solution { public: bool halvesAreAlike(string s) { unordered_set<char> set = {'a', 'e', 'i', 'o', 'u','A','I','E','O','U'}; int i=0,j=s.size()/2,cnt=0; while(j<s.size()){ if(set.find(s[i])!=set.end()) cnt++; if(set.find(s[j])!=set.end()) cnt--; i++; j++; } return cnt==0; } };
var halvesAreAlike = function(s) { let isVowel = ["a","e","i","o","u","A","E","I","O","U"]; let count = 0; for (let i = 0; i < s.length / 2; i++) { if (isVowel.indexOf(s[i]) !== -1) { count++; } } for (let i = s.length / 2; i < s.length; i++) { if (isVowel.indexOf(s[i]) !== -1) { count--; } } return count === 0; };
Determine if String Halves Are Alike
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). &nbsp; Example 1: Input: graph = [[1,2],[3],[3],[]] Output: [[0,1,3],[0,2,3]] Explanation: There are two paths: 0 -&gt; 1 -&gt; 3 and 0 -&gt; 2 -&gt; 3. Example 2: Input: graph = [[4,3,1],[3,2,4],[3],[4],[]] Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]] &nbsp; Constraints: n == graph.length 2 &lt;= n &lt;= 15 0 &lt;= graph[i][j] &lt; n graph[i][j] != i (i.e., there will be no self-loops). All the elements of graph[i] are unique. The input graph is guaranteed to be a DAG.
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] self.explore(graph, graph[0], [0], res) return res def explore(self, graph, candidates, step, res): if step[-1] == len(graph)-1: res.append(list(step)) else: for i in range(len(candidates)): step.append(candidates[i]) self.explore(graph, graph[candidates[i]], step, res) step.pop()
Approach : Using dfs+ backtracking we can solve it class Solution { public List<List<Integer>> allPathsSourceTarget(int[][] graph) { List<List<Integer>> ans=new ArrayList<>(); List<Integer> temp=new ArrayList<>(); boolean []visit=new boolean [graph.length]; helper(graph,0,graph.length-1,ans,temp,visit); return ans; } public void helper(int[][] graph, int src,int dest,List<List<Integer>> ans,List<Integer> temp,boolean[]vis) { vis[src]=true; temp.add(src); if(src==dest) { List<Integer> b =new ArrayList<>(); for(int h:temp){ b.add(h); } ans.add(b); } for(int i:graph[src]) { if(vis[i]!=true) { helper(graph,i,dest,ans,temp,vis); } } vis[src]=false; temp.remove(temp.size()-1); } }
class Solution { public: // setting a few class variables, so that we do not have to pass them down all the time in the recursive dfs calls int target; vector<vector<int>> res; vector<int> tmp; void dfs(vector<vector<int>>& graph, int currNode = 0) { // updating tmp tmp.push_back(currNode); // and either updating res with it if target is met if (currNode == target) res.push_back(tmp); // or callling dfs again recursively else for (int node: graph[currNode]) { dfs(graph, node); } // backtracking with tmp tmp.pop_back(); } vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { target = graph.size() - 1; dfs(graph); return res; } };
/** * @param {number[][]} graph * @return {number[][]} */ const allPathsSourceTarget = function(graph) { const n = graph.length; const result = []; const dfs = (node, path) => { if (node === n-1) { result.push([...path, node]); // Add the current path to the result if we have reached the target node return; } for (const neighbor of graph[node]) { dfs(neighbor, [...path, node]); // Recursively explore all neighbors of the current node } }; dfs(0, []); // Start the DFS from the source node return result; };
All Paths From Source to Target
Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. &nbsp; Example 1: Input: n = 2 Output: ["1/2"] Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2. Example 2: Input: n = 3 Output: ["1/2","1/3","2/3"] Example 3: Input: n = 4 Output: ["1/2","1/3","1/4","2/3","3/4"] Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2". &nbsp; Constraints: 1 &lt;= n &lt;= 100
class Solution: def simplifiedFractions(self, n: int) -> List[str]: collect = {} for b in range(2, n+1): for a in range(1, b): if a/b not in collect: collect[a/b] = f"{a}/{b}" return list(collect.values())
class Solution { public List<String> simplifiedFractions(int n) { List<String> list = new ArrayList<>() ; for(int numerator = 1; numerator< n ; numerator++) { for(int denominator = numerator+1; denominator<=n; denominator++) { if(gcd(numerator,denominator) == 1) { list.add(numerator+"/"+denominator); // System.out.println(numerator+"/"+denominator); } } } return list ; } static int gcd(int a, int b) { // euclidean algo if(a==0) { return b ; } return gcd(b%a,a); } }
class Solution { public: bool simplified(int n, int i){ while(i>0){ n-=i; if(i>n)swap(n,i); } if(n>1) return false; else return true; } vector<string> simplifiedFractions(int n) { vector<string> ans; while(n>1){ int i=1; while(i<n){ if(simplified(n, i)){ string fraction; int num=i; while(num>0){ fraction.push_back(num%10+'0'); num/=10; } fraction.push_back('/'); num = n; while(num>0){ fraction.push_back(num%10+'0'); num/=10; } if(i>9) swap(fraction[0],fraction[1]); if(n>99) swap(fraction[fraction.size()-1],fraction[fraction.size()-3]); else if(n>9) swap(fraction[fraction.size()-1],fraction[fraction.size()-2]); ans.push_back(fraction); } i++; } n--; } return ans; } };
var simplifiedFractions = function(n) { const res = []; const checkValid = (a, b) => { if(a === 1) return 1; let num = 2; while(num <= a) { if(b % num === 0 && a % num === 0) return num; num++; } return 1; } let i = 1; while(i / n < 1) { let j = i + 1; while(j <= n) { if(checkValid(i, j) < 2) { res.push(`${i}/${j}`); } j++; } i++; } return res; };
Simplified Fractions
Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. &nbsp; Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true &nbsp; Constraints: 1 &lt;= s.length &lt;= 5 * 104 t.length == s.length s and t consist of any valid ascii character.
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: dict1={} m="" #creating a dictionary by mapping each element from string S to string T for i,j in zip(s,t): # this for the cases like "badc" and "baba" so we dont want two keys mapping to same value hence we can reject directly if j in dict1.values() and i not in dict1.keys(): return False dict1[i]=j #now take each letter from string s and using dictionary values replace it with that specific character for k in s: m=m+dict1[k] #now if newly formed string m == T is same then the strings are Isomorphic if(m==t): return True else: return False
class Solution { public boolean isIsomorphic(String s, String t) { ArrayList<Integer>list1 = new ArrayList<>(); ArrayList<Integer>list2 = new ArrayList<>(); for(int i=0;i<s.length();i++){ list1.add(s.lastIndexOf(s.charAt(i))); list2.add(t.lastIndexOf(t.charAt(i))); } if(list1.equals(list2)){ return true; } else{ return false; } } }
class Solution { public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; unordered_map<char,char>mp; for(int i=0;i<s.size();i++){ if(mp.find(s[i])==mp.end()){ for(auto it:mp){ if(it.second==t[i])return false; } mp[s[i]]=t[i]; } else{ if(mp[s[i]]!=t[i]) return false; } } return true; } };
/** * @param {string} s * @param {string} t * @return {boolean} */ var isIsomorphic = function(s, t) { const obj = {}; const setValues = new Set(); let isIso = true; for(var indexI=0; indexI<s.length;indexI++) { if(obj[s[indexI]] || setValues.has(t[indexI])) { if (obj[s[indexI]] === t[indexI]) continue; isIso= false; break; } else { obj[s[indexI]] = t[indexI]; setValues.add(t[indexI]); } } return isIso; };
Isomorphic Strings
You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; nums2.length, is valid if both i &lt;= j and nums1[i] &lt;= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] &gt;= arr[i] for every 1 &lt;= i &lt; arr.length. &nbsp; Example 1: Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] Output: 2 Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4). The maximum distance is 2 with pair (2,4). Example 2: Input: nums1 = [2,2,2], nums2 = [10,10,1] Output: 1 Explanation: The valid pairs are (0,0), (0,1), and (1,1). The maximum distance is 1 with pair (0,1). Example 3: Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] Output: 2 Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4). The maximum distance is 2 with pair (2,4). &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 105 1 &lt;= nums1[i], nums2[j] &lt;= 105 Both nums1 and nums2 are non-increasing.
class Solution: def maxDistance(self, n1: List[int], n2: List[int]) -> int: i = j = res = 0 while i < len(n1) and j < len(n2): if n1[i] > n2[j]: i += 1 else: res = max(res, j - i) j += 1 return res
class Solution { public int maxDistance(int[] nums1, int[] nums2) { int max = 0; for (int i = 0; i < nums1.length; i++) { int r = nums2.length - 1; int l = i; int m = i; while (l <= r) { m = l + (r - l) / 2; if (nums1[i] > nums2[m]) { r = m - 1; } else if (nums1[i] == nums2[m]) { l = m + 1; } else { l = m + 1; } } if (r < 0) { continue; } max = Math.max(max, r - i); } return max; } }
class Solution { public: int maxDistance(vector<int>& nums1, vector<int>& nums2) { reverse(nums2.begin(),nums2.end()); int ans = 0; for(int i=0;i<nums1.size();++i){ auto it = lower_bound(nums2.begin(),nums2.end(),nums1[i]) - nums2.begin(); //Finds first element greater than or equal to nums1[i] int j = nums2.size() - 1 - it; //Index of the found element in the original array if(i<=j) ans = max(ans,j-i); //Update distance } return ans; } };
var maxDistance = function(nums1, nums2) { let i = 0, j = 0; let ans = 0; while (i < nums1.length && j < nums2.length) { // maintain the i <= j invariant j = Math.max(j, i); // we want to maximize j so move it forward whenever possible while (nums1[i] <= nums2[j]) { ans = Math.max(ans, j - i); j++; } // we want to minimize i so move it forward only to maintain invariants i++; } return ans; };
Maximum Distance Between a Pair of Values
You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color&nbsp;you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: inventory = [2,5], orders = 4 Output: 14 Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3). The maximum total value is 2 + 5 + 4 + 3 = 14. Example 2: Input: inventory = [3,5], orders = 6 Output: 19 Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2). The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. &nbsp; Constraints: 1 &lt;= inventory.length &lt;= 105 1 &lt;= inventory[i] &lt;= 109 1 &lt;= orders &lt;= min(sum(inventory[i]), 109)
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) inventory += [0] res = 0 k = 1 for i in range(len(inventory)-1): if inventory[i] > inventory[i+1]: if k*(inventory[i]-inventory[i+1]) < orders: diff = inventory[i]-inventory[i+1] res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2 orders -= k*diff else: q, r = divmod(orders, k) res += k*(inventory[i]+(inventory[i]-q+1))*q//2 res += r*(inventory[i]-q) return res%(10**9+7) k += 1
class Solution { private long mod = 1000000007L; public int maxProfit(int[] inventory, int orders) { // we use pq to find the most balls PriorityQueue<Long> pq = new PriorityQueue<>((x, y) -> Long.compare(y, x)); pq.offer(0L); // we use map to count the balls Map<Long, Long> map = new HashMap<>(); map.put(0L, 0L); for (int j : inventory) { long i = (long)j; if (map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { pq.offer(i); map.put(i, 1L); } } long res = 0; while (orders > 0) { long ball = pq.poll(), nextBall = pq.peek(); long times = map.get(ball); long diff = Math.min(ball - nextBall, orders / times); if (diff == 0) { res = (res + orders * ball) % mod; break; } long sum = (ball * 2 + 1 - diff) * diff / 2 * times; res = (res + sum) % mod; orders -= diff * times; if (!map.containsKey(ball - diff)) { map.put(ball - diff, map.get(ball)); pq.offer(ball - diff); } else { map.put(ball - diff, map.get(ball - diff) + map.get(ball)); } map.remove(ball); } return (int) res; } }
#define ll long long const int MOD = 1e9+7; class Solution { public: ll summation(ll n) { return (n*(n+1)/2); } int maxProfit(vector<int>& inventory, int orders) { ll n = inventory.size(), i = 0, ans = 0; inventory.push_back(0); sort(inventory.rbegin(), inventory.rend()); while(orders and i < n) { if(inventory[i] != inventory[i+1]) { ll width = i+1, h = inventory[i] - inventory[i+1]; ll available = width * h, gain = 0; if(available <= orders) { orders -= available; // from each of the first i+1 inventories, we gain (inventory[i+1] + 1) + ... + inventory[i] value gain = (width * (summation(inventory[i]) - summation(inventory[i+1]))) % MOD; } else { ll q = orders / width, r = orders % width; // q balls picked from each of the first i+1 inventories gain = (width * (summation(inventory[i]) - summation(inventory[i]-q))) % MOD; // 1 ball picked from r inventories providing value (inventory[i]-q) gain = (gain + r*(inventory[i]-q)) % MOD; orders = 0; } ans = (ans + gain) % MOD; } i++; } return ans; } };
var maxProfit = function(A, k) { //rangeSum Formula let rangesum=(i,j)=>{ i=BigInt(i),j=BigInt(j) return ((j*((j+1n))/2n)-(i*(i+1n)/2n)) } A.unshift(0) //prepend the sentinel 0 A.sort((a,b)=>a-b) let n=A.length,result=0n,mod=BigInt(1e9+7),i=n-1 // can use all current levels while((k>=(n-i)*(A[i]-A[i-1]))&&i>0){ if(A[i]!=A[i-1]) result=(result+(rangesum(A[i-1],A[i])*BigInt(n-i)))%mod, k-=(n-i)*(A[i]-A[i-1]) i-- } //can use some of the current levels if(k>0&&k>=n-i){ let levels=Math.floor(k/(n-i)) //the levels i can use result=(result+(BigInt(n-i)*rangesum(A[i]-levels,A[i])))%mod k-=levels*(n-i) A[i]-=levels } // can use some of the items OF the first level if(k>0&&k<n-i) result=(result+BigInt(k)*BigInt(A[i]))%mod return Number(result) };
Sell Diminishing-Valued Colored Balls
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. &nbsp; Example 1: Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1 Output: 6 Explanation: The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -&gt; (0,1) -&gt; (0,2) -&gt; (1,2) -&gt; (2,2) -&gt; (3,2) -&gt; (4,2). Example 2: Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1 Output: -1 Explanation: We need to eliminate at least two obstacles to find such a walk. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 40 1 &lt;= k &lt;= m * n grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0
class Solution: def shortestPath(self, grid: List[List[int]], k: int) -> int: Q = [[0, 0, k]] # m, n, remaining elimination quota rows, cols = len(grid), len(grid[0]) V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited while Q: frontier = [] for m, n, rem in Q: if m == rows - 1 and n == cols - 1: return counter for dm, dn in [[1, 0], [-1, 0], [0, 1], [0, -1]]: if 0 <= m+dm < rows and 0 <= n+dn < cols: # check inbound if grid[m+dm][n+dn] == 0: if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem: # if not visited or could be visited with fewer elimination frontier.append([m+dm, n+dn, rem]) V[(m+dm, n+dn)] = rem elif rem > 0: # I see a wall and I can still eliminate if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem - 1: # if not visited or could be visited with fewer elimination frontier.append([m+dm, n+dn, rem-1]) V[(m+dm, n+dn)] = rem - 1 Q = frontier counter += 1 return -1 ```
class Solution { int rowLen = 0; int colLen = 0; int MAXVAL = 0; public int shortestPath(int[][] grid, int k) { rowLen = grid.length; colLen = grid[0].length; MAXVAL = rowLen * colLen + 1; int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k+1][4]); return path == MAXVAL ? -1 : path; } /* Direction 0 - Up 1 - Down 2 - Left 3 - Right */ // For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we consider the direction as well int shortest(int[][] grid, int k, int row, int col, int direction, boolean[][] visited, Integer[][][][] dp){ // Reached end of the matrix if(row == rowLen - 1 && col == colLen - 1 && k >= 0) return 0; // Couldn't find a valid path if(k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen) return MAXVAL; if(dp[row][col][k][direction] != null) return dp[row][col][k][direction]; // 4 options to choose a direction // Go right int op1 = MAXVAL; if(col + 1 < colLen && !visited[row][col+1]) { visited[row][col+1] = true; if(grid[row][col+1] == 0) op1 = shortest(grid, k, row, col+1, 3, visited, dp) + 1; else op1 = shortest(grid, k-1, row, col+1, 3, visited, dp) + 1; visited[row][col+1] = false; } // Go left int op2 = MAXVAL; if(col - 1 >= 0 && !visited[row][col-1]) { visited[row][col-1] = true; if(grid[row][col-1] == 0) op2 = shortest(grid, k, row, col-1, 2, visited, dp) + 1; else op2 = shortest(grid, k-1, row, col-1, 2, visited, dp) + 1; visited[row][col-1] = false; } // Go up int op3 = MAXVAL; if(row - 1 >= 0 && !visited[row-1][col]) { visited[row-1][col] = true; if(grid[row-1][col] == 0) op3 = shortest(grid, k, row-1, col, 0, visited, dp) + 1; else op3 = shortest(grid, k-1, row-1, col, 0, visited, dp) + 1; visited[row-1][col] = false; } // Go down int op4 = MAXVAL; if(row + 1 < rowLen && !visited[row+1][col]) { visited[row+1][col] = true; if(grid[row+1][col] == 0) op4 = shortest(grid, k, row+1, col, 1, visited, dp) + 1; else op4 = shortest(grid, k-1, row+1, col, 1, visited, dp) + 1; visited[row+1][col] = false; } dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4)); return dp[row][col][k][direction]; } }
class Solution { public: vector<vector<int>> directions{{-1,0},{1,0},{0,1},{0,-1}}; int shortestPath(vector<vector<int>>& grid, int k) { int m = grid.size(),n = grid[0].size(),ans=0; queue<vector<int>> q; bool visited[m][n][k+1]; memset(visited,false,sizeof(visited)); q.push({0,0,k}); visited[0][0][k]=true; while(!q.empty()) { int size = q.size(); while(size--) { auto p = q.front(); q.pop(); if(p[0]==m-1 && p[1]==n-1) return ans; for(auto x : directions) { int i= p[0]+x[0]; int j= p[1]+x[1]; int obstacle = p[2]; if(i>=0 && i<m && j>=0 && j<n) { if(grid[i][j]==0 && !visited[i][j][obstacle]) { q.push({i,j,obstacle}); visited[i][j][obstacle] =true; } else if(grid[i][j]==1 && obstacle>0 && !visited[i][j][obstacle-1]) { q.push({i,j,obstacle-1}); visited[i][j][obstacle-1]=true; } } } } ans++; } return -1; } };
var shortestPath = function(grid, k) { const dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const m = grid.length; const n = grid[0].length; let q = [[0,0,k]]; const visited = new Set(); visited.add(`0:0:${k}`); let cnt = 0; while(q.length>0) { const size = q.length; for(let i = 0; i<size; i++) { let [x, y, ob] = q.shift(); if(x === m-1 && y === n-1) { return cnt; } for(const d of dir) { const xx = d[0] + x; const yy = d[1] + y; if(xx>=0 && xx<m && yy>=0 && yy<n) { const newK = grid[xx][yy] === 1 ? ob-1 : ob; if(newK >=0 && !visited.has(`${xx}:${yy}:${newK}`) ) { q.push([xx, yy, newK]); visited.add(`${xx}:${yy}:${newK}`); } } } } cnt++; } return -1; };
Shortest Path in a Grid with Obstacles Elimination
You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: If i % 2 == 0, then arr[i] = perm[i / 2]. If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. You will then assign arr​​​​ to perm. Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. &nbsp; Example 1: Input: n = 2 Output: 1 Explanation: perm = [0,1] initially. After the 1st operation, perm = [0,1] So it takes only 1 operation. Example 2: Input: n = 4 Output: 2 Explanation: perm = [0,1,2,3] initially. After the 1st operation, perm = [0,2,1,3] After the 2nd operation, perm = [0,1,2,3] So it takes only 2 operations. Example 3: Input: n = 6 Output: 4 &nbsp; Constraints: 2 &lt;= n &lt;= 1000 n​​​​​​ is even.
class Solution: def reinitializePermutation(self, n: int) -> int: ans = 0 perm = list(range(n)) while True: ans += 1 perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)] if all(perm[i] == i for i in range(n)): return ans
class Solution { public int reinitializePermutation(int n) { int ans = 1; int num = 2; if(n == 2) return 1; while(true){ if(num % (n-1) == 1)break; else { ans++; num = (num * 2) % (n-1); } } return ans; } }
class Solution { public: vector<int> change(vector<int>arr,vector<int>v){ int n=v.size(); for(int i=0;i<n;i++){ if(i%2==0){ arr[i]=v[i/2]; } else{ arr[i]=v[(n/2) + ((i-1)/2) ]; } } return arr; } int reinitializePermutation(int n) { vector<int>v(n); for(int i=0;i<n;i++){ v[i]=i; } vector<int>arr(n); arr=change(arr,v); if(arr==v){return 1;} int cnt=1; while(arr!=v){ arr=change(arr,arr); cnt++; if(arr==v){return cnt;} } return cnt; } };
* @param {number} n * @return {number} */ var reinitializePermutation = function(n) { if (n < 2) return 0; let prem = []; let count = 0; for (var i = 0; i < n; i++) { prem[i] = i; } let newArr = []; newArr = helper(prem, newArr); const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); if (equals(prem, newArr)) { count++; return count; } else { while (!equals(prem, newArr)) { count++; let temp = newArr; newArr = []; newArr = helper(temp, newArr); } } return count + 1; }; var helper = function (prem, arr) { let n = prem.length; for (var i = 0; i < n; i++) { if (i % 2 == 0) { arr[i] = prem[i / 2]; } else { arr[i] = prem[n / 2 + (i - 1) / 2]; } } return arr; };
Minimum Number of Operations to Reinitialize a Permutation
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. &nbsp; Example 1: Input: nums = [1,2,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [2], range = 2 - 2 = 0 [3], range = 3 - 3 = 0 [1,2], range = 2 - 1 = 1 [2,3], range = 3 - 2 = 1 [1,2,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4. Example 2: Input: nums = [1,3,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [3], range = 3 - 3 = 0 [3], range = 3 - 3 = 0 [1,3], range = 3 - 1 = 2 [3,3], range = 3 - 3 = 0 [1,3,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4. Example 3: Input: nums = [4,-2,-3,4,1] Output: 59 Explanation: The sum of all subarray ranges of nums is 59. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 1000 -109 &lt;= nums[i] &lt;= 109 &nbsp; Follow-up: Could you find a solution with O(n) time complexity?
class Solution: def subArrayRanges(self, nums: List[int]) -> int: n = len(nums) # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray # so totalsum = maxsum - minsum # we calculate minsum and maxsum in two different loops minsum = maxsum = 0 # first calculate sum{ Min(subarray) } over all subarrays # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1 # where f(i) is number of subarrays where nums[i] is the minimum value # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i] # we can claculate these indices in linear time using a monotonically increasing stack. stack = [] for next_smaller in range(n + 1): # we pop from the stack in order to satisfy the monotonically increasing order property # if we reach the end of the iteration and there are elements present in the stack, we pop all of them while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]): i = stack.pop() prev_smaller = stack[-1] if stack else -1 minsum += nums[i] * (next_smaller - i) * (i - prev_smaller) stack.append(next_smaller) # then calculate sum{ Max(subarray) } over all subarrays # sum{ Max(subarray) } = sum(f'(i) * nums[i]) ; i=0..n-1 # where f'(i) is number of subarrays where nums[i] is the maximum value # f'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i] # this time we use a monotonically decreasing stack. stack = [] for next_larger in range(n + 1): # we pop from the stack in order to satisfy the monotonically decreasing order property # if we reach the end of the iteration and there are elements present in the stack, we pop all of them while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]): i = stack.pop() prev_larger = stack[-1] if stack else -1 maxsum += nums[i] * (next_larger - i) * (i - prev_larger) stack.append(next_larger) return maxsum - minsum
class Solution { class Node{ long val, displace; Node(long val, long displace){ this.val = val; this.displace = displace; } } public long subArrayRanges(int[] nums) { //lesser than current element Stack<Node> stack = new Stack<>(); //from left long [] lesserLeft = new long[nums.length]; for (int i = 0; i< nums.length; i++){ long count = 1; while(stack.size()>0 && stack.peek().val<=nums[i]){ count+=stack.pop().displace; } stack.add(new Node(nums[i], count)); lesserLeft[i] = count; } stack.clear(); //from right long[] lesserRight = new long[nums.length]; for (int i = nums.length-1; i>=0; i--){ long count = 1; while(stack.size()>0 && stack.peek().val<nums[i]){ count+=stack.pop().displace; } stack.add(new Node(nums[i], count)); lesserRight[i] = count; } //greater than current element stack.clear(); //from left long [] greaterLeft = new long[nums.length]; for (int i = 0; i< nums.length; i++){ long count = 1; while(stack.size()>0 && stack.peek().val>=nums[i]){ count+=stack.pop().displace; } stack.add(new Node(nums[i], count)); greaterLeft[i] = count; } stack.clear(); //from right long[] greaterRight = new long[nums.length]; for (int i = nums.length-1; i>=0; i--){ long count = 1; while(stack.size()>0 && stack.peek().val>nums[i]){ count+=stack.pop().displace; } stack.add(new Node(nums[i], count)); greaterRight[i] = count; } long ans = 0; //Now we subtract the count of minimum occurrences from the count of maximum occurrences for (int i = 0; i< nums.length; i++){ ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i]; } return ans; } }
class Solution { public: long long subArrayRanges(vector<int>& nums) { int n=nums.size(); long long res=0; for(int i=0;i<n-1;i++){ int maxi=nums[i], mini=nums[i]; for(int j=i+1;j<n;j++){ if(nums[j]>maxi)maxi=nums[j]; else if(nums[j]<mini)mini=nums[j]; res+=maxi-mini; } } return res; } };
// O(n^3) time | O(1) space var subArrayRanges = function(nums) { let res = 0 for (let i = 1; i < nums.length; i++) { for (let j = 0; j < i; j++) { let smallest = nums[i], biggest = nums[i] for (let k = j; k < i; k++) { smallest = Math.min(smallest, nums[k]) biggest = Math.max(biggest, nums[k]) } res += biggest - smallest } } return res };
Sum of Subarray Ranges
You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. Each token may be played at most once and in any order. You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens. &nbsp; Example 1: Input: tokens = [100], power = 50 Output: 0 Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. Example 2: Input: tokens = [100,200], power = 150 Output: 1 Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. Example 3: Input: tokens = [100,200,300,400], power = 200 Output: 2 Explanation: Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. &nbsp; Constraints: 0 &lt;= tokens.length &lt;= 1000 0 &lt;= tokens[i],&nbsp;power &lt; 104
class Solution: def bagOfTokensScore(self, tokens, power): tokens.sort() n = len(tokens) i, j = 0, n while i < j: if tokens[i] <= power: power -= tokens[i] i += 1 elif i - (n - j) and j > i + 1: j -= 1 power += tokens[j] else: break return i - (n - j)
class Solution { public int bagOfTokensScore(int[] tokens, int power) { //initially score is 0, that's why in these conditions, return 0. if(tokens.length == 0 || power < tokens[0]) return 0; Arrays.sort(tokens); //sort the array int i = 0; int r = tokens.length - 1; int score = 0; int answer = 0; while(i<=r){ if(power >= tokens[i]){ power -= tokens[i++]; answer = Math.max(answer, ++score); //play all tokens, but store the max score in answer. } else if (score > 0){ power += tokens[r--]; //take power from greatest element score--; //decrease by 1. } //when you can't do any of the steps (face up, face down) else return answer; } return answer; } }
class Solution { public: int bagOfTokensScore(vector<int>& tokens, int power) { sort(tokens.begin(),tokens.end()); int start=0,end=tokens.size()-1,score=0,ans=0; while(start<=end){ if(power>=tokens[start]){ ans=max(ans,++score); power-=tokens[start++]; } else if(score>0){ score--; power+=tokens[end--]; } else { return 0; } } return ans; } };
var bagOfTokensScore = function(tokens, power) { const n = tokens.length; tokens.sort((a, b) => a - b); let maxScore = 0; let currScore = 0; let left = 0; let right = n - 1; while (left <= right) { const leftPower = tokens[left]; const rightPower = tokens[right]; if (power >= leftPower) { power -= leftPower; currScore++; maxScore = Math.max(currScore, maxScore); left++; } else if (currScore > 0) { power += rightPower; currScore--; right--; } else { return maxScore; } } return maxScore; };
Bag of Tokens
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three. &nbsp; Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 Explanation: Since 4 is not divisible by 3, do not pick any number. Example 3: Input: nums = [1,2,3,4,4] Output: 12 Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3). &nbsp; Constraints: 1 &lt;= nums.length &lt;= 4 * 10^4 1 &lt;= nums[i] &lt;= 10^4
class Solution: def maxSumDivThree(self, nums: List[int]) -> int: dp = [0, float('-inf'), float('-inf')] for x in nums: dp_cp = dp[:] for left in range(3): right = (left + x) % 3 dp[right] = max(dp_cp[right], dp_cp[left] + x) return dp[0]
class Solution { public int maxSumDivThree(int[] nums) { int r0 = 0; int r1 = 0; int r2 = 0; for (int i = 0; i < nums.length; i++) { int nr0 = r0; int nr1 = r1; int nr2 = r2; int a = r0 + nums[i]; int b = r1 + nums[i]; int c = r2 + nums[i]; if (a % 3 == 0) { nr0 = Math.max(nr0, a); } else if (a % 3 == 1) { nr1 = Math.max(nr1, a); } else if (a % 3 == 2) { nr2 = Math.max(nr2, a); } if (b % 3 == 0) { nr0 = Math.max(nr0, b); } else if (b % 3 == 1) { nr1 = Math.max(nr1, b); } else if (b % 3 == 2) { nr2 = Math.max(nr2, b); } if (c % 3 == 0) { nr0 = Math.max(nr0, c); } else if (c % 3 == 1) { nr1 = Math.max(nr1, c); } else if (c % 3 == 2) { nr2 = Math.max(nr2, c); } r0=nr0; r1=nr1; r2=nr2; } return r0; } }
class Solution { public: int maxSumDivThree(vector<int>& nums) { vector<int> twos = {(int)1e4+1, (int)1e4+1}, ones = {(int)1e4+1, (int)1e4+1}; int res = 0; for(int i: nums) { if(i%3 == 2) { if(i <= twos[0]) { twos[1] = twos[0], twos[0] = i; } else if(i < twos[1]) twos[1] = i; } else if(i%3 == 1) { if(i <= ones[0]) { ones[1] = ones[0], ones[0] = i; } else if(i < ones[1]) ones[1] = i; } res += i; } if(res%3 == 2) return max(res - twos[0], res - ones[0] - ones[1]); else if(res%3 == 1) return max(res - ones[0], res - twos[0] - twos[1]); return res; } };
var maxSumDivThree = function(nums) { // there are 3 options for how the sum fit's into 3 via mod % 3 // track those 3 options via indices in the dp array // dp[0] = %3 === 0 // dp[1] = %3 === 1 // dp[2] = %3 === 2 let dp = new Array(3).fill(0); for (let num of nums) { for (let i of dp.slice(0)) { let sum = i + num; let mod = sum % 3; // on each pass, set the value of dp[mod] to the Math.max val dp[mod] = Math.max(dp[mod], sum); } } return dp[0]; };
Greatest Sum Divisible by Three
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. &nbsp; Example 1: Input: people = [1,2], limit = 3 Output: 1 Explanation: 1 boat (1, 2) Example 2: Input: people = [3,2,2,1], limit = 3 Output: 3 Explanation: 3 boats (1, 2), (2) and (3) Example 3: Input: people = [3,5,3,4], limit = 5 Output: 4 Explanation: 4 boats (3), (3), (4), (5) &nbsp; Constraints: 1 &lt;= people.length &lt;= 5 * 104 1 &lt;= people[i] &lt;= limit &lt;= 3 * 104
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo = 0 hi = len(people)-1 boats = 0 while lo <= hi: if people[lo] + people[hi] <= limit: lo += 1 hi -= 1 else: hi -= 1 boats += 1 return boats
class Solution { public int numRescueBoats(int[] people, int limit) { int boatCount = 0; Arrays.sort(people); int left = 0; int right = people.length - 1; while(left <= right){ int sum = people[left] + people[right]; if(sum <= limit){ boatCount++; left++; right--; } else{ boatCount++; right--; } } return boatCount; } }
// πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰Please upvote if it helps πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰ class Solution { public: int numRescueBoats(vector<int>& people, int limit) { // sort vector sort(people.begin(),people.end()); int i = 0, j = people.size() - 1,cnt = 0; while(i <= j) { // lightest person + heaviest person sum <= limit // they can go together if(people[i] + people[j] <= limit) { ++i; --j; } // if sum is over the limit, // heaviest will go alone. else --j; ++cnt; // number of boats } return cnt; } // for github repository link go to my profile. };
/** * @param {number[]} people * @param {number} limit * @return {number} */ var numRescueBoats = function(people, limit) { people = people.sort((a,b) => a - b) let left = 0 let right = people.length - 1 let res = 0 while (left <= right) { if (people[left] + people[right] <= limit) { res++ right-- left++ } else if (people[right] <= limit) { res++ right-- } } return res };
Boats to Save People
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). &nbsp; Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. Example 2: Input: nums = [1,5,4,5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. Example 3: Input: nums = [3,7] Output: 12 &nbsp; Constraints: 2 &lt;= nums.length &lt;= 500 1 &lt;= nums[i] &lt;= 10^3
class Solution: def maxProduct(self, nums: List[int]) -> int: # mx1 - max element, mx2 - second max element mx1 = nums[0] if nums[0] > nums[1] else nums[1] mx2 = nums[1] if nums[0] > nums[1] else nums[0] for num in nums[2:]: if num > mx1: mx1, mx2 = num, mx1 elif num > mx2: mx2 = num return (mx1 - 1) * (mx2 - 1)
class Solution { public int maxProduct(int[] nums) { int max = Integer.MIN_VALUE; int maxi = -1; for (int i = 0; i < nums.length; ++i) { if (nums[i] > max) { max = nums[i]; maxi = i; } } nums[maxi] = Integer.MIN_VALUE; int nextmax = Integer.MIN_VALUE; for (int i = 0; i < nums.length; ++i) { if (nums[i] > nextmax) nextmax = nums[i]; } return max*nextmax-max-nextmax+1; } }
class Solution { public: int maxProduct(vector<int>& nums) { int n = nums.size(); sort(nums.begin(), nums.end()); return (nums[n -1]-1)* (nums[n-2]-1); } };
var maxProduct = function(nums) { let val = []; for(let i=0; i<nums.length; i++){ for(let j=i+1; j<nums.length; j++){ val.push((nums[i]-1)*(nums[j]-1)) } } return Math.max(...val) };
Maximum Product of Two Elements in an Array
We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank. &nbsp; Example 1: Input: n = 4, left = [4,3], right = [0,1] Output: 4 Explanation: In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). Example 2: Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7] Output: 7 Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. Example 3: Input: n = 7, left = [0,1,2,3,4,5,6,7], right = [] Output: 7 Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall. &nbsp; Constraints: 1 &lt;= n &lt;= 104 0 &lt;= left.length &lt;= n + 1 0 &lt;= left[i] &lt;= n 0 &lt;= right.length &lt;= n + 1 0 &lt;= right[i] &lt;= n 1 &lt;= left.length + right.length &lt;= n + 1 All values of left and right are unique, and each value can appear only in one of the two arrays.
class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: # make sure left and right are not empty without changing the answer left.append(0) right.append(n) return max(max(left), n - min(right))
class Solution { public int getLastMoment(int n, int[] left, int[] right) { int max = 0; for (int i = 0; i < left.length; i++) { if (left[i] > max) max = left[i]; } for (int i = 0; i < right.length; i++) { if (n - right[i] > max) max = n - right[i]; } return max; } }
class Solution { public: int getLastMoment(int n, vector<int>& left, vector<int>& right) { int mx=0; for(auto&i:left)mx=max(mx,i); for(auto&i:right)mx=max(mx,n-i); return mx; } };
var getLastMoment = function(n, left, right) { const maxLeft = Math.max(...left); const minRight = Math.min(...right); return Math.max(n - minRight, maxLeft); };
Last Moment Before All Ants Fall Out of a Plank
You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root. As a reminder, any shorter prefix of a string is lexicographically smaller. For example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children. &nbsp; Example 1: Input: root = [0,1,2,3,4,3,4] Output: "dba" Example 2: Input: root = [25,1,3,1,3,0,2] Output: "adz" Example 3: Input: root = [2,2,1,null,1,0,null,0] Output: "abc" &nbsp; Constraints: The number of nodes in the tree is in the range [1, 8500]. 0 &lt;= Node.val &lt;= 25
class Solution: res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13 def smallestFromLeaf(self, root: TreeNode) -> str: def helper(node: TreeNode, prev): prev = chr(97 + node.val) + prev if not node.left and not node.right: self.res = min(self.res, prev) return if node.left: helper(node.left, prev) if node.right: helper(node.right, prev) helper(root, "") return self.res
class Solution { String result = null; public String smallestFromLeaf(TreeNode root) { build(root, new StringBuilder()); return result; } public void build(TreeNode root, StringBuilder str) { if (root == null) return; StringBuilder sb = new StringBuilder(str).insert(0, String.valueOf(intToChar(root.val))); if (root.left == null && root.right == null) { // we are on a leaf node result = result == null || sb.toString().compareTo(result) < 0 ? sb.toString() : result; return; } build(root.left, sb); // build left child build(root.right, sb); // build right child } // turns an int (0-25) into a Character ex: 0 -> a, 1 -> b, 2 -> c public Character intToChar(int i) { return (char) (i + 'a'); } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: string res; void solve(TreeNode* root,string cur){ if(!root) return; cur.push_back((char)('a'+root->val));//converting integer to corresponding characer if(!root->left and !root->right){ //reversing the string since it is computed from root to leaf, but we need viceversa reverse(cur.begin(),cur.end()); if(res=="" or cur<res) res=cur;//updating the result based on lexicographical order return; } solve(root->left,cur); solve(root->right,cur); return; } string smallestFromLeaf(TreeNode* root) { if(!root) return ""; solve(root,""); return res; } };
var smallestFromLeaf = function(root) { if(root === null) return ''; let queue = [[root, ''+giveCharacter(root.val)]]; let leafLevelFound = false; let possibleSmallString = []; while(queue.length > 0){ let currentLevelLength = queue.length; for(let i=0; i<currentLevelLength; i++){ let [currentNode, currentPath] = queue.shift(); if(currentNode.left === null && currentNode.right ===null){ // as one of the test case is failing with this approacch - saying legth/depth of the path doesnt matter // even TOTAL (ASCII)SUM of letters also not matter - it should be dictionary first path // hence, no need of this logic and have to continue until all path discovered // So, instead removing - just never doing TRUE - hence it will continue exploring and putting all paths leafLevelFound = false; possibleSmallString.push(currentPath); //.split("").reverse().join("") } if(!leafLevelFound){ if(currentNode.left !== null) queue.push([currentNode.left,giveCharacter(currentNode.left.val)+currentPath]); if(currentNode.right !== null) queue.push([currentNode.right,giveCharacter(currentNode.right.val)+currentPath]); } } if(leafLevelFound) break; } // console.log(possibleSmallString); possibleSmallString.sort(); // console.log(possibleSmallString); return possibleSmallString[0]; }; function giveCharacter(num){ return String.fromCharCode(num+97); }
Smallest String Starting From Leaf
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length &gt;= 3 There exists some i with 0 &lt; i &lt; arr.length - 1 such that: arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1] Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. &nbsp; Example 1: Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. Example 2: Input: array = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1. &nbsp; Constraints: 3 &lt;= mountain_arr.length() &lt;= 104 0 &lt;= target &lt;= 109 0 &lt;= mountain_arr.get(index) &lt;= 109
# """ # This is MountainArray's API interface. # You should not implement it, or speculate about its implementation # """ #class MountainArray: # def get(self, index: int) -> int: # def length(self) -> int: class Solution: def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: min_index = -1 peak = self.findpeak(mountain_arr) min_index = self.binary_search(0, peak, mountain_arr, target, 1) if min_index == -1: min_index = self.binary_search(peak+1, mountain_arr.length() - 1, mountain_arr, target, -1) return min_index def findpeak(self, mountain_arr): start = 0 end = mountain_arr.length() - 1 while start < end: mid = start + int((end - start)/2) if mountain_arr.get(mid) < mountain_arr.get(mid + 1): start = mid + 1 else: end = mid return start def binary_search(self, start, end, mountain_arr, target, asc): while start <= end: mid = start + int((end - start)/2) mountain_arr_get_mid = mountain_arr.get(mid) if target == mountain_arr_get_mid: return mid if asc == 1: if target < mountain_arr_get_mid: end = mid - 1 elif target > mountain_arr_get_mid: start = mid + 1 else: if target < mountain_arr_get_mid: start = mid + 1 elif target > mountain_arr_get_mid: end = mid - 1 return -1
class Solution { public int findInMountainArray(int target, MountainArray mountainArr) { int peak = findPeak(mountainArr); int left =binary(0,peak,mountainArr,target,true); if(left!=-1){ return left; } int right= binary(peak+1,mountainArr.length()-1,mountainArr, target,false); return right; } static int findPeak(MountainArray mountainArr){ int start=0; int end =mountainArr.length()-1; while(start<end){ int mid=start+((end-start)/2); if(mountainArr.get(mid)<mountainArr.get(mid+1)){ start=mid+1; }else{ end=mid; } } return start; } static int binary(int low, int high, MountainArray arr,int target, boolean left){ while(low<=high){ int mid=low+((high-low)/2); if(target<arr.get(mid)){ if(left){ high=mid-1; }else{ low=mid+1; } }else if(target>arr.get(mid)){ if(left){ low=mid+1; }else{ high=mid-1; } }else{ return mid; } } return -1; } }
/** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * class MountainArray { * public: * int get(int index); * int length(); * }; */ class Solution { public: //----------------------- find peak --------------------------------------- int find_max(MountainArray &mountainArr,int start,int end) { int n= mountainArr.length(); while(start<=end) { int mid= start+(end-start)/2; int next=(mid+1)%n; int prev=(mid+n-1)%n; int mid_val = mountainArr.get(mid); int pre_val = mountainArr.get(prev); int next_val = mountainArr.get(next); if(mid_val > next_val and mid_val>pre_val) return mid; else if(mid_val<next_val and mid_val > pre_val) start=mid+1; else if(mid_val>next_val and mid_val<pre_val) end=mid-1; } return -1; } //--------------------------binary search------------------------------------------- int binary_search(MountainArray &mountainArr,int start,int end,int target) { while(start<=end) { int mid= start + (end-start)/2; int mid_val=mountainArr.get(mid); if(mid_val==target) return mid; else if(target < mid_val) { end=mid-1; } else start=mid+1; } return -1; } //----------------------binary search in reverse sorted------------------------------ int binary_search_rev(MountainArray &mountainArr,int start,int end,int target) { while(start<=end) { int mid= start + (end-start)/2; int mid_val=mountainArr.get(mid); if(mid_val==target) return mid; else if(target > mid_val) { end=mid-1; } else start=mid+1; } return -1; } //------------------------------returns minimum index of target-------------------------------------- int evaluate_ans(int a,int b) { if(a==-1 and b==-1 ) return -1; else if(a!= -1 and b!= -1) return min(a,b); else if(a==-1 and b!=-1) return b; else return a; } int findInMountainArray(int target, MountainArray &mountainArr) { int start=0; int n= mountainArr.length()-1; int max_in = find_max(mountainArr,start ,n); int a= binary_search(mountainArr,start,max_in,target); int b= binary_search_rev(mountainArr,max_in + 1,n,target); return evaluate_ans(a,b); } };
/** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * function MountainArray() { * @param {number} index * @return {number} * this.get = function(index) { * ... * }; * * @return {number} * this.length = function() { * ... * }; * }; */ var binarySearch = function(left, right, condition) { while (left < right) { var mid = left + Math.floor((right - left) / 2); if (condition(mid)) { right = mid; } else { left = mid + 1; } } return left; } /** * @param {number} target * @param {MountainArray} mountainArr * @return {number} */ var findInMountainArray = function(target, mountainArr) { var n = mountainArr.length(); var maxNumIdx = binarySearch(1, n - 2, function(idx) { return mountainArr.get(idx) > mountainArr.get(idx + 1); }); var leftIdx = binarySearch(0, maxNumIdx, function(idx) { return mountainArr.get(idx) >= target; }); if (mountainArr.get(leftIdx) === target) { return leftIdx; } var rightIdx = binarySearch(maxNumIdx, n - 1, function(idx) { return mountainArr.get(idx) <= target; }); if (mountainArr.get(rightIdx) === target) { return rightIdx; } return -1; };
Find in Mountain Array
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score. &nbsp; Example 1: Input: parents = [-1,2,0,2,0] Output: 3 Explanation: - The score of node 0 is: 3 * 1 = 3 - The score of node 1 is: 4 = 4 - The score of node 2 is: 1 * 1 * 2 = 2 - The score of node 3 is: 4 = 4 - The score of node 4 is: 4 = 4 The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score. Example 2: Input: parents = [-1,2,0] Output: 2 Explanation: - The score of node 0 is: 2 = 2 - The score of node 1 is: 2 = 2 - The score of node 2 is: 1 * 1 = 1 The highest score is 2, and two nodes (node 0 and node 1) have the highest score. &nbsp; Constraints: n == parents.length 2 &lt;= n &lt;= 105 parents[0] == -1 0 &lt;= parents[i] &lt;= n - 1 for i != 0 parents represents a valid binary tree.
class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: graph = collections.defaultdict(list) for node, parent in enumerate(parents): # build graph graph[parent].append(node) n = len(parents) # total number of nodes d = collections.Counter() def count_nodes(node): # number of children node + self p, s = 1, 0 # p: product, s: sum for child in graph[node]: # for each child (only 2 at maximum) res = count_nodes(child) # get its nodes count p *= res # take the product s += res # take the sum p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself) d[p] += 1 # count the product return s + 1 # return number of children node + 1 (self) count_nodes(0) # starting from root (0) return d[max(d.keys())] # return max count
class Solution { long max = 0, res = 0; public int countHighestScoreNodes(int[] parents) { Map<Integer, List<Integer>> hm = new HashMap(); for(int i = 0; i < parents.length; i++) { // build the tree hm.computeIfAbsent(parents[i], x ->new ArrayList<>()).add(i); } dfs(0, parents.length, hm); // traverse the tree to get the result return (int)res; } int dfs(int s, int n, Map<Integer, List<Integer>> hm) { int sum = 1; long mult = 1L; for(int child : hm.getOrDefault(s, new ArrayList<>())) { int count = dfs(child, n, hm); // subtree node count sum += count; mult *= count; // multiply the result by children size } mult *= (s == 0 ? 1L : n - sum); // multiply the result by remain size except self and children size(the nodes through parent) if(mult > max) { max = mult; res = 1; } else if (mult == max) { res++; } return sum; // return the node count of the tree rooted at s } }
class Solution { public: // Steps : // 1 - For each node, you need to find the sizes of the subtrees rooted in each of its children. // 2 - How to determine the number of nodes in the rest of the tree? // Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree? // 3 - Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score. // calculating size of each subtree by standing at every node '0' to 'n-1' int dfs(int src,vector<vector<int>>& g,vector<int>& size) { int ans = 1;// for curent node for(auto child : g[src]){ ans += dfs(child,g,size); } return size[src] = ans; } // This code can also be work for generalized tree not only for Binary tree int countHighestScoreNodes(vector<int>& parents) { int n=parents.size(); vector<int>size(n,0); // size[i] indicates size of subtree(rooted at i node) + 1 vector<vector<int>>g(n); // storing left and right child of a node for(int i=1;i<n;i++){ g[parents[i]].push_back(i); // 'There is no parent for 0th node' } dfs(0,g,size); //calculating size of each subtree(rooted at ith node) long long int maxCount = 0; // To avoid overflow because perform product below you should take "long long int" long long int maxScore = 0; for(int i=0;i<n;i++) // Nodes from '0' to 'n-1' { // calculate score of each node after removal their 'edge' or 'node itself'. long long int product = 1; product = max(product, (long long int)(n - size[i])); // calculating leftover nodes excluding child nodes for(auto x : g[i]) { product = product*size[x]; } if(product > maxScore){ maxScore = product; maxCount = 1; } else if(product == maxScore){ maxCount++; // store count of nodes which have maximum score equal to "maxScore" } } return maxCount; } };
var countHighestScoreNodes = function(parents) { const n = parents.length; const adj = []; for (let i = 0; i < n; ++i) { adj[i] = []; } for (let i = 1; i < n; ++i) { const parent = parents[i]; adj[parent].push(i); } let maxProd = 0; let maxCount = 0; dfs(0); return maxCount; function dfs(node) { let rem = n - 1; let sum = 0; let prod = 1; for (const child of adj[node]) { const count = dfs(child); sum += count; prod *= count; rem -= count; } if (rem > 0) prod *= rem; if (prod > maxProd) { maxProd = prod; maxCount = 1; } else if (prod === maxProd) { ++maxCount; } return sum + 1; } };
Count Nodes With the Highest Score
We run a&nbsp;preorder&nbsp;depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.&nbsp; If the depth of a node is D, the depth of its immediate child is D + 1.&nbsp; The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root. &nbsp; Example 1: Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7] Example 2: Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7] Example 3: Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90] &nbsp; Constraints: The number of nodes in the original tree is in the range [1, 1000]. 1 &lt;= Node.val &lt;= 109
class Solution: def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: i = 0 dummy_head = TreeNode() depth = 0 while i < len(traversal): if traversal[i].isdigit(): value, i = get_value(traversal, i) insert_node(dummy_head, depth, value) else: depth, i = get_depth(traversal, i) return dummy_head.left # Returns the next value from the string traversal, and returns the position following the last digit of the current value. def get_value(traversal, i): value = 0 while i < len(traversal) and traversal[i].isdigit(): value *= 10 value += int(traversal[i]) i += 1 return value, i # Insertes a node of the given `value` at the given `depth` of the subtree whose root is the given `root`. def insert_node(root, depth, value): for _ in range(depth): if root.right: root = root.right else: root = root.left new_node = TreeNode(value) if root.left: root.right = new_node else: root.left = new_node # Gets the next depth from the string traversal, and returns the position following the last dash of the current depth. def get_depth(traversal, i): depth = 0 while i < len(traversal) and traversal[i] == "-": depth += 1 i += 1 return depth, i
class Solution { public TreeNode recoverFromPreorder(String traversal) { if(!traversal.contains("-")) return new TreeNode(Integer.parseInt(traversal)); String number = ""; int i = 0; while(traversal.charAt(i)!='-'){ number+=traversal.charAt(i); i++; } //System.out.print("root = " + number + " " + i + " "); TreeNode root = new TreeNode(Integer.parseInt(number)); StringBuilder str = new StringBuilder(); int bk = 0; for(int j = i; i < traversal.length(); i++){ if(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-' && traversal.charAt(i+1) != '-') bk = str.toString().length(); else if(!(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-')) str.append(traversal.charAt(i)); } String divide = str.toString(); TreeNode left = (bk==0)?recoverFromPreorder(divide):recoverFromPreorder(divide.substring(0,bk)); TreeNode right = (bk==0)?null:recoverFromPreorder(divide.substring(bk,divide.length())); root.left = left; root.right = right; return root; } }
class Solution { public: // Returns the index of '-' if present otherwise returns the string length int findIndex(int ind, string &traversal){ int req = traversal.size(); for(int i=ind; i<traversal.size(); i++){ if(traversal[i] == '-'){ req = i; break; } } return req; } TreeNode* recoverFromPreorder(string traversal) { // Pushing the node along with its depth into the stack int depth = 0; stack<pair<TreeNode*,int>> st; // Finding the root node int ind = findIndex(0, traversal); string str = traversal.substr(0, ind); TreeNode *root = new TreeNode(stoi(str)); // Pushing the root node along with its depth st.push({root, 0}); // Starting from 'ind' as it has the next '-' character int i = ind; while(i<traversal.size()){ // Increment the depth if(traversal[i] == '-'){ depth++; i++; continue; } // Find the complete number as no.of digits can be > 1 int ind = findIndex(i, traversal); string str = traversal.substr(i, ind-i); TreeNode *node = new TreeNode(stoi(str)); // Finding its appropriate parent, whose depth is one less than current depth while(!st.empty() && st.top().second != depth-1){ st.pop(); } // There is already left child for the parent if(st.top().first->left){ st.top().first->right = node; } else{ st.top().first->left = node; } // Pushing that node and its depth into stack st.push({node, depth}); depth = 0; i = ind; } return root; } };
var recoverFromPreorder = function(traversal) { let n = traversal.length; // Every layer in dfs handles the depth+1 of '-' only. // ex: // depth=0 -> find '-' as splitter // depth=1 -> find '--' as splitter // depth=2 -> find '---' as splitter let dfs = (str,depth)=>{ if(str.indexOf("-") === -1) return new TreeNode(str); // 1. We split by the depth+1 number of '-' // Using regex to split is much easier. -> str.split(/(?<=\d)-(?=\d)/g) // where (?<=\d) means positive lookbehind , ex: "1- ...", then we'll split '-' excluding 1. // Similarly , (?=\d) means positive lookahead , ex: "-5 ...", then we'll split '-' excluding 5. let re = new RegExp(`(?<=\\d)${"-".repeat(depth+1)}(?=\\d)`,'g'); let [val,leftStr,rightStr] = str.split(re); // ex: 1-2--3--4-5--6--7 --> ['1','2--3--4','5--6--7'] // 2. After splitting, we'll get [val,leftStr,rightStr] // Then we could handle left / right node in the next dfs layer intuitively. let node = new TreeNode(val); if(leftStr) node.left = dfs(leftStr,depth+1); if(rightStr) node.right = dfs(rightStr,depth+1); return node; }; return dfs(traversal,0); };
Recover a Tree From Preorder Traversal
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position, you can walk one step to the left, right, up, or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. &nbsp; Example 1: Input: grid = [[0,6,0],[5,8,7],[0,9,0]] Output: 24 Explanation: [[0,6,0], [5,8,7], [0,9,0]] Path to get the maximum gold, 9 -&gt; 8 -&gt; 7. Example 2: Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]] Output: 28 Explanation: [[1,0,7], [2,0,6], [3,4,5], [0,3,0], [9,0,20]] Path to get the maximum gold, 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 15 0 &lt;= grid[i][j] &lt;= 100 There are at most 25 cells containing gold.
class Solution: def getMaximumGold(self, grid): answer = [0] def visit(visited, i, j, gold_sum): val = grid[i][j] if val == 0 or (i,j) in visited: answer[0] = max(answer[0], gold_sum) return gold_sum_new = gold_sum + val visited_new = visited.union({(i,j)}) if i > 0: visit(visited_new, i-1, j, gold_sum_new) if j < len(grid[i]) - 1: visit(visited_new, i, j+1, gold_sum_new) if i < len(grid) - 1: visit(visited_new, i+1, j, gold_sum_new) if j > 0: visit(visited_new, i, j-1, gold_sum_new) #choosing the starting points for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] != 0: count = 0 try: if grid[i-1][j] != 0: count += 1 except: pass try: if grid[i][j+1] != 0: count += 1 except: pass try: if grid[i+1][j] != 0: count += 1 except: pass try: if grid[i][j-1] != 0: count += 1 except: pass if count < 3: visit(set(),i,j,0) return answer[0]
class Solution { int r = 0; int c = 0; int max = 0; public int getMaximumGold(int[][] grid) { r = grid.length; c = grid[0].length; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(grid[i][j] != 0) { dfs(grid, i, j, 0); } } } return max; } private void dfs(int[][] grid, int i, int j, int cur) { if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] == 0) { max = Math.max(max, cur); return; } int val = grid[i][j]; grid[i][j] = 0; dfs(grid, i + 1, j, cur + val); dfs(grid, i - 1, j, cur + val); dfs(grid, i, j + 1, cur + val); dfs(grid, i, j - 1, cur + val); grid[i][j] = val; } }
class Solution { public: int maxgold=0; int m,n; void gold(int i,int j,vector<vector<int>>& grid,vector<vector<int>>& vis,int count){ // Down if(i+1<m && !vis[i+1][j] && grid[i+1][j]){ vis[i][j]=1; gold(i+1,j,grid,vis,count+grid[i+1][j]); vis[i][j]=0; } // Left if(j-1>=0 && !vis[i][j-1] && grid[i][j-1]){ vis[i][j]=1; gold(i,j-1,grid,vis,count+grid[i][j-1]); vis[i][j]=0; } // Right if(j+1<n && !vis[i][j+1] && grid[i][j+1]){ vis[i][j]=1; gold(i,j+1,grid,vis,count+grid[i][j+1]); vis[i][j]=0; } // Up if(i-1>=0 && !vis[i-1][j] && grid[i-1][j]){ vis[i][j]=1; gold(i-1,j,grid,vis,count+grid[i-1][j]); vis[i][j]=0; } maxgold=max(maxgold,count); } int getMaximumGold(vector<vector<int>>& grid) { m=grid.size(); n=grid[0].size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]){ vector<vector<int>>vis(m,vector<int>(n,0)); gold(i,j,grid,vis,grid[i][j]); } } } return maxgold; } };
var getMaximumGold = function(grid) { let max = 0; // This is our internal dfs function that will search all possible directions from a cell const mine = (x, y, n) => { // We can't mine any gold if the position is out of the grid, or the cell doesnt have any gold if (x < 0 || y < 0 || x > grid.length - 1 || y > grid[x].length - 1 || grid[x][y] == 0) return 0; // Save the temp value so we can mark the cell as visited let temp = grid[x][y]; grid[x][y] = 0; // Try mining left, right, up, and down from the current position, // bringing along the gold total that was found in the current cell mine(x + 1, y, n + temp); mine(x - 1, y, n + temp); mine(x, y + 1, n + temp); mine(x, y - 1, n + temp); // After we've tried all directions reset cell to have its original value, // so it can be mined from a different starting point grid[x][y] = temp; // Update the max based on the mining done up until the current cell max = Math.max(max, n + temp); } // We need to run this dfs function through every potential starting point for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { mine(i, j, 0); } } return max; };
Path with Maximum Gold
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. &nbsp; Example 1: Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Example 2: Input: nums = [-1] Output: [0] Example 3: Input: nums = [-1,-1] Output: [0,0] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 -104 &lt;= nums[i] &lt;= 104
class Solution: def countSmaller(self, nums: List[int]) -> List[int]: # build the binary indexed tree num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0 tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1 result = [0] * len(nums) # iterate from right to left for result_index in range(len(nums) - 1, -1, -1): n = nums[result_index] # add 10**4 to n to account for negative numbers i = n + 10 ** 4 # convert to 1-based index for the tree i += 1 # perform range sum query of buckets [-inf, n-1], where n is current number # because we want n - 1 for range sum query of [-inf, n-1], not n, subtract 1 from i: i -= 1 val = 0 while i != 0: val += tree[i] # get parent node by subtracting least significant set bit i -= i & -i result[result_index] = val # update the binary indexed tree with new bucket i = n + 10 ** 4 i += 1 while i < len(tree): tree[i] += 1 # get next node to update by adding the least significant set bit i += i & -i return result
class Solution { public List<Integer> countSmaller(int[] nums) { int min = 20001; int max = -1; for (int num : nums) { min = Math.min(min, num); max = Math.max(max, num); } min--; int[] count = new int[max-min+1]; Integer[] result = new Integer[nums.length]; for (int i = nums.length-1; i >=0; i--) { int k = nums[i]-min-1; int c = 0; do { c += count[k]; k -= (-k&k); } while (k > 0); result[i] = c; k = nums[i]-min; while (k < count.length) { count[k]++; k += (-k&k); } } return Arrays.asList(result); } }
typedef struct _SmallerValueCount { _SmallerValueCount(const int &value, const int &originalIndex) : mValue(value), mOriginalIndex(originalIndex) {} int mValue = 0; int mOriginalIndex = 0; } SmallerValueCount; class Solution { public: vector<int> countSmaller(vector<int>& nums) { vector<SmallerValueCount> convertedNums; convertedNums.reserve(nums.size()); for (int i = 0; i < nums.size(); ++i) convertedNums.emplace_back(SmallerValueCount(nums[i], i)); vector<int> smallerCounts(convertedNums.size(), 0); merge_sort(convertedNums, smallerCounts, 0, nums.size() - 1); return smallerCounts; } void merge_sort(vector<SmallerValueCount> &nums, vector<int> &smallerCounts, const int &left, const int &right) { if (left >= right) return; const auto mid = (left + right) / 2; merge_sort(nums, smallerCounts, left, mid); merge_sort(nums, smallerCounts, mid+1, right); merge(nums, smallerCounts, left, mid, right); } void merge(vector<SmallerValueCount> &nums, vector<int> &smallerCounts, const int &left, const int &mid, const int &right) { vector<SmallerValueCount> buffer; buffer.reserve(right - left + 1); int i = left, j = mid + 1; int smallerCount = 0; while (i <= mid && j <= right) if (nums[i].mValue > nums[j].mValue) { ++smallerCount; buffer.push_back(nums[j]); ++j; } else { smallerCounts[nums[i].mOriginalIndex] += smallerCount; buffer.push_back(nums[i]); ++i; } while (i <= mid) { smallerCounts[nums[i].mOriginalIndex] += smallerCount; buffer.push_back(nums[i]); ++i; } while (j <= right) { buffer.push_back(nums[j]); ++j; } std::move(std::begin(buffer), std::end(buffer), std::next(std::begin(nums), left)); } };
var countSmaller = function(nums) { if(nums===null || nums.length == 0) return [] let N = nums.length const result = new Array(N).fill(0) const numsWithIdx = new Array(N).fill(0) for(let i = 0; i < nums.length; i++) { const curr = nums[i] numsWithIdx[i] = {val:curr, originalIdx: i} } divideAndConqueuer(0, nums.length - 1) const resultList = [] result.forEach(el => resultList.push(el)) return resultList function divideAndConqueuer(left, right) { if(left < right) { const mid = Math.floor(left + (right - left)/2) divideAndConqueuer(left, mid) divideAndConqueuer(mid+1, right) merge(left, mid, right) } } function merge(left, mid, right) { const leftLen = mid - left + 1 const rightLen = right - mid let rightSmallers = 0 const leftAux = new Array(leftLen).fill(0) const rightAux = new Array(rightLen).fill(0) for(let i = 0; i < leftLen; i++) { leftAux[i] = numsWithIdx[left+i] } for(let i = 0; i < rightLen; i++) { rightAux[i] = numsWithIdx[mid+1+i] } let leftPointer = 0 let rightPointer = 0 let insertAtPointer = left while(leftPointer < leftLen && rightPointer < rightLen) { if(leftAux[leftPointer].val <= rightAux[rightPointer].val) { result[leftAux[leftPointer].originalIdx] += rightSmallers numsWithIdx[insertAtPointer++] = leftAux[leftPointer++] } else { numsWithIdx[insertAtPointer++] = rightAux[rightPointer++] rightSmallers++ } } while(rightPointer < rightLen) { numsWithIdx[insertAtPointer++] = rightAux[rightPointer++] } while(leftPointer < leftLen) { result[leftAux[leftPointer].originalIdx] += rightSmallers numsWithIdx[insertAtPointer++] = leftAux[leftPointer++] } } };
Count of Smaller Numbers After Self
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. &nbsp; Example 1: Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]] Example 2: Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]] &nbsp; Constraints: m == mat.length n == mat[i].length 1 &lt;= m, n &lt;= 104 1 &lt;= m * n &lt;= 104 mat[i][j] is either 0 or 1. There is at least one 0 in mat.
class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: if not mat or not mat[0]: return [] m, n = len(mat), len(mat[0]) queue = deque() MAX_VALUE = m * n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE. for i in range(m): for j in range(n): if mat[i][j] == 0: queue.append((i, j)) else: mat[i][j] = MAX_VALUE directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] while queue: row, col = queue.popleft() for dr, dc in directions: r, c = row + dr, col + dc if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1: queue.append((r, c)) mat[r][c] = mat[row][col] + 1 return mat
class Solution { // BFS // We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it. boolean visited[][]; // Could also convert the indexes to a single number by mat[0].length * i + j. class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } public int[][] updateMatrix(int[][] mat) { int level = 0; visited = new boolean[mat.length][mat[0].length]; Queue<Pair> q = new ArrayDeque<>(); // Addition of all pairs in mat that have 0. for(int i = 0; i < mat.length; i++){ for(int j = 0; j < mat[0].length; j++){ if(mat[i][j] == 0){ visited[i][j] = true; q.add(new Pair(i, j)); } } } while(q.size()>0){ int size = q.size(); while(size-- > 0){ Pair p = q.remove(); mat[p.x][p.y] = level; if(p.x > 0 && visited[p.x - 1][p.y] == false){ visited[p.x-1][p.y] = true; q.add(new Pair(p.x-1, p.y)); } if(p.x < mat.length - 1 && visited[p.x + 1][p.y] == false){ visited[p.x+1][p.y] = true; q.add(new Pair(p.x+1, p.y)); } if(p.y > 0 && visited[p.x][p.y-1] == false){ visited[p.x][p.y-1] = true; q.add(new Pair(p.x, p.y-1)); } if(p.y < mat[0].length-1 && visited[p.x][p.y + 1] == false){ visited[p.x][p.y+1] = true; q.add(new Pair(p.x, p.y + 1)); } } level++; } return mat; } }
class Solution { bool isValid(vector<vector<int>>& grid,int r,int c,int nr,int nc,int m,int n){ if(nr>=0 && nc>=0 && nr<m && nc<n && grid[nr][nc]==-1){ if(grid[r][c]==0) grid[nr][nc]=1; else grid[nr][nc]=grid[r][c]+1; return 1; } return 0; } public: vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { queue<pair<int,int>> q; int m = mat.size(); int n = mat[0].size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(mat[i][j]==0) q.push({i,j}); else mat[i][j]=-1; } } while(!q.empty()){ auto per = q.front(); int r = per.first; int c = per.second; // if() q.pop(); if(isValid(mat,r,c,r-1,c,m,n)){ q.push({r-1,c}); } if(isValid(mat,r,c,r+1,c,m,n)){ q.push({r+1,c}); } if(isValid(mat,r,c,r,c-1,m,n)){ q.push({r,c-1}); } if(isValid(mat,r,c,r,c+1,m,n)){ q.push({r,c+1}); } } return mat; } };
/** * @param {number[][]} mat * @return {number[][]} */ var updateMatrix = function(mat) { const rows = mat.length, cols = mat[0].length; if (!rows) return mat; const queue = new Queue(); const dist = Array.from({length: rows}, () => new Array(cols).fill(Infinity)); for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (!mat[i][j]) { dist[i][j] = 0; queue.enqueue([i, j]); } } } const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]; while (!queue.isEmpty()) { const [ row, col ] = queue.dequeue(); for (let i = 0; i < 4; i++) { const nRow = row + dirs[i][0], nCol = col + dirs[i][1]; if (nRow < 0 || nCol < 0 || nRow >= rows || nCol >= cols) continue; if (dist[nRow][nCol] > dist[row][col] + 1) { dist[nRow][nCol] = dist[row][col] + 1; queue.enqueue([nRow, nCol]); } } } return dist; };
01 Matrix
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. &nbsp; Example 1: Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] Output: true Explanation: We can rotate mat 90 degrees clockwise to make mat equal target. Example 2: Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]] Output: false Explanation: It is impossible to make mat equal to target by rotating mat. Example 3: Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]] Output: true Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target. &nbsp; Constraints: n == mat.length == target.length n == mat[i].length == target[i].length 1 &lt;= n &lt;= 10 mat[i][j] and target[i][j] are either 0 or 1.
class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: # if already equal if target == mat: return True # there are 4 different rotation with 90 deg. # We need to check at most 3 more rotation. for i in range(3): # transpose the matrix by swap row and col values. for j in range(len(mat)): for k in range(j+1, len(mat)): mat[j][k], mat[k][j] = mat[k][j], mat[j][k] # Reflect the row by reverse it. mat[j] = mat[j][::-1] # now the matrix is roteted; check if they're alike. if target == mat: return True return False
class Solution { public boolean findRotation(int[][] mat, int[][] target) { if (mat == target) return true; int n = mat.length; int[] res[] = new int[n][n]; for (int i = 0; i < n; i++) { //clockwise 90 for (int j = 0; j < n; j++) { res[i][j] = mat[n - 1 - j][i]; } } int[] res2[] = new int[n][n]; for (int i = 0; i < n; i++) { //clockwise 180 for (int j = 0; j < n; j++) { res2[i][j] = res[n - 1 - j][i]; } } int[] res3[] = new int[n][n]; for (int i = 0; i < n; i++) { //clockwise 270 for (int j = 0; j < n; j++) { res3[i][j] = res2[n - 1 - j][i]; } } //compare to 90,180,270 and itself if(Arrays.deepEquals(target, res) || Arrays.deepEquals(target, res2) || Arrays.deepEquals(target, res3) || Arrays.deepEquals(target, mat) ){ return true; } return false; } } // Arrays.deepEquals() use for matrix
class Solution { public: bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) { int n = mat.size(); if(mat == target) { // rotation by 0 degree. return true; } int deg = 3; // more rotations with 90, 180, 270 degree's. while(deg --) { for(int i = 0; i < n; i ++) { for(int j = i; j < n; j ++) { swap(mat[i][j], mat[j][i]); // transpose of matrix. } } for(int i = 0; i < n; i ++) { reverse(mat[i].begin(),mat[i].end()); // reverse each row. } if(mat == target) { return true; } } return false; } };
var findRotation = function(mat, target) { let width = mat[0].length; let height = mat.length; let normal = true; let rightOneTime = true; let rightTwoTimes = true; let rightThreeTimes = true; for (let i = 0; i < height; i++) { for (let j = 0; j < width; j++) { // don't rotate mat if (mat[i][j] !== target[i][j]) { normal = false; } // rotate mat right 1 time if (mat[i][j] !== target[j][width - 1 - i]) { rightOneTime = false; } // rotate mat right 2 times if (mat[i][j] !== target[height - 1 - i][width - 1 - j]) { rightTwoTimes = false; } // rotate mat right 3 times if (mat[i][j] !== target[height - 1 - j][i]) { rightThreeTimes = false; } } } return normal || rightOneTime || rightTwoTimes || rightThreeTimes; };
Determine Whether Matrix Can Be Obtained By Rotation
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-negative. If the cell is a water cell, its height must be 0. Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them. &nbsp; Example 1: Input: isWater = [[0,1],[0,0]] Output: [[1,0],[2,1]] Explanation: The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. Example 2: Input: isWater = [[0,0,1],[1,0,0],[0,0,0]] Output: [[1,1,0],[0,1,1],[1,2,2]] Explanation: A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. &nbsp; Constraints: m == isWater.length n == isWater[i].length 1 &lt;= m, n &lt;= 1000 isWater[i][j] is 0 or 1. There is at least one water cell.
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: arr = collections.deque() m, n = len(isWater), len(isWater[0]) for i in range(m): for j in range(n): if isWater[i][j] == 1: arr.append((0, i, j)) ans = [[-1] * n for _ in range(m)] while arr: val, x, y = arr.popleft() if ans[x][y] != -1: continue ans[x][y] = val for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: xx, yy = x+dx, y+dy if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1: arr.append((val+1, xx, yy)) return ans
class Solution { static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; int rows; int cols; int[][] isWater; public int[][] highestPeak(int[][] isWater) { this.isWater = isWater; rows = isWater.length; cols = isWater[0].length; int[][] heightCells = new int[rows][cols]; //store the coordinate of water cell Queue<int[]> queue = new LinkedList(); for(int r = 0; r < rows; r++){ for(int c = 0; c < cols; c++){ if(isWater[r][c] == 1){ //mark as water heightCells[r][c] = 0; //add water coordinate queue.add(new int[]{r, c}); } else{ //mark default value for land heightCells[r][c] = -1; } } } /* * Approach * 1. start from every water source, update their neighbor height * 2. add each neighbours which was not processed earlier 3. do it every cell is processed */ bfs(queue, heightCells); return heightCells; } private void bfs(Queue<int[]> queue, int[][] heightCells){ while(!queue.isEmpty()){ int[] cell = queue.remove(); //increment height of neighbor cell in all 4 direction //e.g, left, right, up, down for(int[] dir : DIRECTION){ int newRow = cell[0] + dir[0]; int newCol = cell[1] + dir[1]; //check new coordinate of cell inside the grid or not if(!isInsideGrid(newRow, newCol)) continue; //check already handled if(heightCells[newRow][newCol] != -1) continue; //increament, heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1; //to handle the neighbour of this new cell queue.add(new int[]{newRow, newCol}); } } } private boolean isInsideGrid(int row, int col){ return row >= 0 && row < rows && col >= 0 && col < cols; } }
class Solution { public: vector<vector<int>> highestPeak(vector<vector<int>>& isWater) { int r = isWater.size(); int c = isWater[0].size(); queue <pair<int,int>> curr; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { //set the land cell to -1 (not visited) if (isWater[i][j] == 0) { isWater[i][j] = -1; } //set the water cell to zero and to queue else { isWater[i][j] = 0; curr.push({i, j}); } } } int hill = 0; while (!curr.empty()) { int len = curr.size(); for (int k = 0; k < len; k++) { //for each cell check its 4 boundary cells //if it is not visited, increase its hill by 1 pair <int, int> fnt = curr.front(); curr.pop(); int i = fnt.first, j = fnt.second; //top cell if (i > 0 && isWater[i - 1][j] == -1) { isWater[i - 1][j] = hill + 1; curr.push({i-1, j}); } //bottom cell if ((i < r - 1) && (isWater[i + 1][j] == -1)) { isWater[i + 1][j] = hill + 1; curr.push({i+1, j}); } //left cell if (j > 0 && (isWater[i][j - 1] == -1)) { isWater[i][j - 1] = hill + 1; curr.push({i, j-1}); } //right cell if ((j < c - 1) && (isWater[i][j + 1] == -1)) { isWater[i][j + 1] = hill + 1; curr.push({i, j+1}); } } //after 1 complete round increase the height of the hill hill += 1; } return isWater; } };
var highestPeak = function(isWater) { const RN = isWater.length, CN = isWater[0].length; const output = [...Array(RN)].map(() => Array(CN).fill(-1)); const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]] let queue = [] for(let r = 0; r < RN; r++) { for(let c = 0; c < CN; c++) { if(isWater[r][c]) { queue.push([r, c]); output[r][c] = 0; } } } while(queue.length) { const next = [] for(let [r, c] of queue) { for(let [dr, dc] of dir) { dr += r; dc += c; if(dr < 0 || dc < 0 || dr >= RN || dc >= CN || output[dr][dc] !== -1) continue; output[dr][dc] = output[r][c] + 1; next.push([dr, dc]); } } queue = next; } return output; };
Map of Highest Peak
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise. &nbsp; Example 1: Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more than once. Example 2: Input: path = "NESWW" Output: true Explanation: Notice that the path visits the origin twice. &nbsp; Constraints: 1 &lt;= path.length &lt;= 104 path[i] is either 'N', 'S', 'E', or 'W'.
class Solution: def isPathCrossing(self, path: str) -> bool: c = set() x,y = 0,0 c.add((x,y)) for i in path: if i == 'N': y+=1 elif i == 'E': x+=1 elif i == 'W': x-=1 else: y-=1 if (x,y) in c: return True else: c.add((x,y)) return False
// Path crossing // Leetcode class Solution { public boolean isPathCrossing(String path) { Set<String> visited = new HashSet<>(); int x = 0, y = 0; visited.add(x + "," + y); for (char c : path.toCharArray()) { if (c == 'N') y++; else if (c == 'S') y--; else if (c == 'E') x++; else x--; if (visited.contains(x + "," + y)) return true; visited.add(x + "," + y); } return false; } }
class Solution { public: bool isPathCrossing(string path) { set<pair<int, int>>st; int x=0,y=0; st.insert({0, 0}); for(int i=0;i<path.length();i++){ if(path[i]=='N'){ x++; } else if(path[i]=='S'){ x--; } else if(path[i]=='E'){ y++; } else{ y--; } //if pair find at any point, return true if(st.find({x,y}) != st.end()){ return 1; } //insert the pair st.insert({x, y}); } return 0; } };
var isPathCrossing = function(path) { let set = new Set(); let curr = [0, 0] let start = `${curr[0]}, ${curr[1]}` set.add(start) for (let el of path) { if (el === 'N') curr[1]++; else if (el === 'S') curr[1]--; else if (el === 'E') curr[0]++; else curr[0]--; let key = `${curr[0]}, ${curr[1]}` if (set.has(key)) return true; set.add(key) } return false; };
Path Crossing
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 &lt;= i &lt; pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs. &nbsp; Example 1: Input: pairs = [[5,1],[4,5],[11,9],[9,4]] Output: [[11,9],[9,4],[4,5],[5,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 9 == 9 = start1 end1 = 4 == 4 = start2 end2 = 5 == 5 = start3 Example 2: Input: pairs = [[1,3],[3,2],[2,1]] Output: [[1,3],[3,2],[2,1]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 3 == 3 = start1 end1 = 2 == 2 = start2 The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid. Example 3: Input: pairs = [[1,2],[1,3],[2,1]] Output: [[1,2],[2,1],[1,3]] Explanation: This is a valid arrangement since endi-1 always equals starti. end0 = 2 == 2 = start1 end1 = 1 == 1 = start2 &nbsp; Constraints: 1 &lt;= pairs.length &lt;= 105 pairs[i].length == 2 0 &lt;= starti, endi &lt;= 109 starti != endi No two pairs are exactly the same. There exists a valid arrangement of pairs.
#Hierholzer Algorithm from collections import defaultdict class Solution: def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]: G = defaultdict(list) din = defaultdict(int) dout = defaultdict(int) for v, w in pairs: G[v].append(w) dout[v] += 1 din[w] += 1 start = pairs[0][0] for v in G: if din[v]+1 == dout[v]: start = v route = [] def dfs(v): while G[v]: w = G[v].pop() dfs(w) route.append(v) dfs(start) route.reverse() return [[route[i],route[i+1]] for i in range(len(route)-1)]
class Solution { public int[][] validArrangement(int[][] pairs) { int n = pairs.length; int[][] ans = new int[n][2]; for (int[] a : ans) { a[0] = -1; a[1] = -1; } Map<Integer, Integer> outdegree = new HashMap<>(); Map<Integer, Deque<Integer>> out = new HashMap<>(); for (int[] pair : pairs) { outdegree.put(pair[0], outdegree.getOrDefault(pair[0], 0) + 1); outdegree.put(pair[1], outdegree.getOrDefault(pair[1], 0) - 1); out.computeIfAbsent(pair[0], k -> new ArrayDeque<>()); out.computeIfAbsent(pair[1], k -> new ArrayDeque<>()); out.get(pair[0]).addLast(pair[1]); } for (Map.Entry<Integer, Integer> entry : outdegree.entrySet()) { if (entry.getValue() == 1) ans[0][0] = entry.getKey(); if (entry.getValue() == -1) ans[n - 1][1] = entry.getKey(); } if (ans[0][0] == -1) { ans[0][0] = pairs[0][0]; ans[n - 1][1] = pairs[0][0]; } int i = 0; int j = n - 1; while (i < j) { int from = ans[i][0]; Deque<Integer> toList = out.get(from); if (toList.size() == 0) { ans[j][0] = ans[--i][0]; ans[--j][1] = ans[j + 1][0]; } else { ans[i++][1] = toList.removeLast(); ans[i][0] = ans[i - 1][1]; } } return ans; } }
class Solution { public: vector<vector<int>> validArrangement(vector<vector<int>>& pairs) { int m = pairs.size(); // Eulerian Path unordered_map<int, stack<int>> adj; unordered_map<int, int> in; unordered_map<int, int> out; // reserve spaces for unordered_map may help in runtime. adj.reserve(m); in.reserve(m); out.reserve(m); for (int i = 0; i < m; i++) { int u = pairs[i][0], v = pairs[i][1]; in[v]++; out[u]++; adj[u].push(v); } // find the starting node int start = -1; for (auto& p : adj) { int i = p.first; if (out[i] - in[i] == 1) start = i; } if (start == -1) { // Eulerian Circuit -> start at any node start = adj.begin()->first; } vector<vector<int>> ans; euler(adj, ans, start); reverse(ans.begin(), ans.end()); return ans; } private: void euler(unordered_map<int, stack<int>>& adj, vector<vector<int>>& ans, int curr) { auto& stk = adj[curr]; while (!stk.empty()) { int nei = stk.top(); stk.pop(); euler(adj, ans, nei); // postorder ans.push_back({curr, nei}); } } };
var validArrangement = function(pairs) { let graph = {}; let degrees = {}; // outdegree: positive, indegree: negative for (var [x, y] of pairs) { if (!graph[x]) graph[x] = []; graph[x].push(y); if (degrees[x] === undefined) degrees[x] = 0; if (degrees[y] === undefined) degrees[y] = 0; degrees[x]++; degrees[y]--; } let start = pairs[0][0]; for (var [x] of pairs) { if (degrees[x] === 1) start = x; // one extra outdegree } let ans = []; dfs(start); function dfs(node) { while ((graph[node] || []).length) { let neighbor = graph[node].pop(); dfs(neighbor); ans.push([node, neighbor]); } } return ans.reverse(); };
Valid Arrangement of Pairs
There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it&nbsp;and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. &nbsp; Example 1: Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. Example 2: Input: target = 10, position = [3], speed = [3] Output: 1 Explanation: There is only one car, hence there is only one fleet. Example 3: Input: target = 100, position = [0,2,4], speed = [4,2,1] Output: 1 Explanation: The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. &nbsp; Constraints: n == position.length == speed.length 1 &lt;= n &lt;= 105 0 &lt; target &lt;= 106 0 &lt;= position[i] &lt; target All the values of position are unique. 0 &lt; speed[i] &lt;= 106
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: def computeArrivalTime(curr_pos, curr_speed): nonlocal target return (target - curr_pos) / curr_speed # avoid integer division, as a car may arrive at 5.2s and another at 5.6s cars = list(zip(position, speed)) cars.sort(key=lambda x: x[0], reverse=True) arrival_bound = None # time upper bound fleet = 0 for pos, sp in cars: curr_arrival = computeArrivalTime(pos, sp) if not arrival_bound or curr_arrival > arrival_bound: arrival_bound = curr_arrival fleet += 1 return fleet # time O(n logn): sort = (nlogn); loop = (n) # space O(n): depend on sort
class Solution { class pair implements Comparable<pair>{ int pos; double time; pair(int pos,double time){ this.pos=pos; this.time=time; } public int compareTo(pair o){ return o.pos-this.pos; } } public int carFleet(int target, int[] position, int[] speed) { double []arr=new double[position.length]; for(int i=0;i<position.length;i++){ arr[i]=(target-position[i])*1.0/speed[i]; } PriorityQueue<pair>pq=new PriorityQueue<>(); for(int i=0;i<position.length;i++){ pq.add(new pair(position[i],arr[i])); } double updatetime=0; int fleet=0; while(pq.size()>0){ pair rem=pq.remove(); if(updatetime<rem.time){ fleet++; updatetime=rem.time; } } return fleet; } }
class Solution { public: int carFleet(int target, vector<int>& position, vector<int>& speed) { int n = position.size(); vector<pair<int,int>> cars; for(int i=0; i<n; i++)cars.push_back({position[i], speed[i]}); sort(cars.begin(),cars.end()); int start=0; int mid=0; int fleet = n; double times[n]; for(int i=n-1; i>=0; i--){ times[i] =((double) (target-cars[i].first)/cars[i].second); if(i<n-1)times[i] = max(times[i],times[i+1]); } while(mid<n){ double timeA = times[start]; double timeB = times[mid]; //cout<<timeA<<" "<<timeB<<endl; if(mid-start+1 == 2){ if(timeA<=timeB)fleet--; start++; } mid++; } return fleet; } };
var carFleet = function(target, position, speed) { for (let i = 0 ; i < position.length ; i ++) { position[i] = [target - position[i], speed[i]] } position.sort((a, b) => { return a[0] - b[0] }) let count = 1, prev = position[0][0] / position[0][1] for (let i = 1 ; i < position.length ; i ++) { // if the time taken is longer then it will cause another fleet if (position[i][0] / position[i][1] > prev) { count ++ prev = position[i][0] / position[i][1] } } return count };
Car Fleet
You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign. For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763. If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255. Return a string representing the maximum value of n​​​​​​ after the insertion. &nbsp; Example 1: Input: n = "99", x = 9 Output: "999" Explanation: The result is the same regardless of where you insert 9. Example 2: Input: n = "-13", x = 2 Output: "-123" Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123. &nbsp; Constraints: 1 &lt;= n.length &lt;= 105 1 &lt;= x &lt;= 9 The digits in n​​​ are in the range [1, 9]. n is a valid representation of an integer. In the case of a negative n,​​​​​​ it will begin with '-'.
class Solution: def maxValue(self, n: str, x: int) -> str: if int(n)>0: ans = "" flag = False for i in range(len(n)): if int(n[i])>=x: ans += n[i] else: a = n[:i] b = n[i:] ans = a+str(x)+b flag = True break if not flag: ans += str(x) else: n = n[1:] ans = "" flag = False for i in range(len(n)): if int(n[i])<=x: ans += n[i] else: a = n[:i] b = n[i:] ans = a+str(x)+b flag = True break if not flag: ans += str(x) ans = "-"+ans return ans
class Solution { public String maxValue(String n, int x) { StringBuilder res= new StringBuilder(); int i=0, j=0; if(n.charAt(0)=='-'){ res.append(n.charAt(0)); for(j=1; j<n.length(); j++){ char ch= n.charAt(j); int val= ch-'0'; if(val<= x){ res.append(ch); }else{ res.append(x); res.append(ch); res.append(n.substring(j+1)); break; } } if(j==n.length()){ res.append(x); } } else{ for(i=0; i<n.length(); i++){ char ch= n.charAt(i); int val= ch-'0'; if(val>= x){ res.append(ch); }else{ res.append(x); res.append(ch); res.append(n.substring(i+1)); break; } } if(i==n.length()){ res.append(x); } } return res.toString(); } }
class Solution { public: string maxValue(string s, int x) { int p=0,flag=0; char ch='0'+x; //change int to char string str; if(s[0]=='-') { //for negative numbers for(int i=1;i<s.size();i++) { if(ch<s[i] && !flag){ str+=ch; str+=s[i]; flag=1; } else str+=s[i]; } if(!flag) str+=ch; return '-'+str; } // if number is positive for(int i=0;i<s.size();i++) { if(ch>s[i] && !flag){ str+=ch; str+=s[i]; flag=1; } else str+=s[i]; } if(!flag) str+=ch; return str; } };
var maxValue = function(n, x) { let i; // if the number if positive, find the first // number that is less than x if (n[0] !== '-') { for (i = 0; i < n.length; i++) { if (Number(n[i]) < x) break; } // if the number is negative, find the first // number that is greater than x } else { for (i = 1; i < n.length; i++) { if (Number(n[i]) > x) break; } } // return the string with x inserted at the found index return n.slice(0, i) + x + n.slice(i) }; ///////////////// short hand //////////////////// var maxValue = function(n, x) { let i; if (n[0] !== '-') { for (i = 0; i < n.length; i++) { if (Number(n[i]) < x) break; } } else { for (i = 1; i < n.length; i++) { if (Number(n[i]) > x) break; } } return n.slice(0, i) + x + n.slice(i) };
Maximum Value after Insertion
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. &nbsp; Example 1: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". Example 2: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". Example 3: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est". &nbsp; Constraints: 1 &lt;= pattern.length, queries.length &lt;= 100 1 &lt;= queries[i].length &lt;= 100 queries[i] and pattern consist of English letters.
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: res, N = [], len(pattern) for query in queries: if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N: res.append(False) else: res.append(True) return res def LCS(self, A, B): N, M = len(A), len(B) d = [[0 for _ in range(M+1)] for _ in range(N+1)] for i in range(1, N+1): for j in range(1, M+1): if A[i - 1] == B[j - 1]: d[i][j] = 1 + d[i-1][j-1] else: d[i][j] = max(d[i-1][j], d[i][j-1]) return d[-1][-1] def upLetter(self, w): count = 0 for c in w: if c.isupper(): count += 1 return count
class Solution { public List<Boolean> camelMatch(String[] queries, String pattern) { List<Boolean> list = new ArrayList<>(); for (var q : queries) { int index = 0; boolean flag = true; for (var c : q.toCharArray()) { if(index < pattern.length() && c == pattern.charAt(index)){ index++; continue; } if(c >= 'A' && c <= 'Z'){ if(index >= pattern.length() || c != pattern.charAt(index)){ flag = false; break; } } } flag = flag && index == pattern.length(); list.add(flag); } return list; } }
class Solution { public: vector<bool> camelMatch(vector<string>& queries, string pattern) { vector<bool> res(queries.size()); for (int i = 0; i < queries.size(); i++) { int patRef = 0; bool isCamel = true; for (const char& ltr : queries[i]) { if (patRef == pattern.size()) { if (isupper(ltr)) { isCamel = false; break; } } else { if (isupper(ltr) and isupper(pattern[patRef]) and ltr != pattern[patRef]) { isCamel = false; break; } else if (islower(ltr) and islower(pattern[patRef]) and ltr == pattern[patRef]) patRef++; else if (ltr == pattern[patRef]) patRef++; } } if (patRef == pattern.size() and isCamel) res[i] = true; } return res; } };
var camelMatch = function(queries, pattern) { function camelMatch(q, p){ let qlist=[] let plist=[] for(let a of q) if(a<='Z') qlist.push(a); for(let a of p) if(a<='Z') plist.push(a); return plist.join('') === qlist.join('') } function seqMatch(q, p){ if(!camelMatch(p,q)) return false let pi=0 for(let qi=0; qi<q.length; qi++){ if(pi<p.length && p[pi]===q[qi]) pi++ } return pi===p.length } return queries.map(q=>seqMatch(q, pattern)) }
Camelcase Matching
You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphabet. Each letter in message is then substituted using the table. Spaces ' ' are transformed to themselves. For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -&gt; 'a', 'a' -&gt; 'b', 'p' -&gt; 'c', 'y' -&gt; 'd', 'b' -&gt; 'e', 'o' -&gt; 'f'). Return the decoded message. &nbsp; Example 1: Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv" Output: "this is a secret" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog". Example 2: Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb" Output: "the five boxing wizards jump quickly" Explanation: The diagram above shows the substitution table. It is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo". &nbsp; Constraints: 26 &lt;= key.length &lt;= 2000 key consists of lowercase English letters and ' '. key contains every letter in the English alphabet ('a' to 'z') at least once. 1 &lt;= message.length &lt;= 2000 message consists of lowercase English letters and ' '.
class Solution: def decodeMessage(self, key: str, message: str) -> str: alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] i=0 d={} for j in key: if j!=" " and j not in d: d[j]=alpha[i] i+=1 if len(d)==26: break res="" d[" "]=" " for i in message: res+=d[i] return res
class Solution { public String decodeMessage(String key, String message) { StringBuilder ans = new StringBuilder();//Using String Builder to append the string key = key.replaceAll(" ", ""); //Removing the spaces HashMap<Character,Character> letters = new HashMap<>(); //Mapping the key into a hashmap. char original = 'a'; for (int i = 0; i < key.length() ; i++) { if (!letters.containsKey(key.charAt(i))){ letters.put(key.charAt(i),original++); } } //After the first pass all the letters of the key will be mapped with their respective original letters. for (int i = 0; i < message.length(); i++) { if (letters.containsKey(message.charAt(i))){ //Now replacing the letters of the message with appropriate letter according to the key ans.append(letters.get(message.charAt(i))); }else{ ans.append(message.charAt(i)); //This is for characters other than the letters in the key example a space " " //They will not be replaced by any letters hence original letter is appended into the StringBuilder } } return ans.toString(); } }
class Solution { public: string decodeMessage(string key, string message) { vector <char> alpha {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; int i=0; map<char,char> d; for(int j=0;j<26;j++){ d[alpha[j]]='0'; } for(int j=0; j<key.size(); j++){ if(key[j]!=' ' && d[key[j]]=='0'){ d[key[j]]=alpha[i]; i++; } if (i==26) break; } d[' '] = ' '; string res=""; for(int i=0; i<message.size(); i++){ res += d[message[i]]; } return res; } };
var decodeMessage = function(key, message) { let result = '' key = Array.from(new Set(key.split(' ').join(''))) const hash = new Map() const alpha = 'abcdefghijklmnopqrstuvwxyz' for (let i = 0; i < alpha.length; i++) { hash.set(key[i], alpha[i]) } for (let chr of message) { result += hash.get(chr) || ' ' } return result };
Decode the Message
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. &nbsp; Example 1: Input: arr = [1,2,4,4,4,4], m = 1, k = 3 Output: true Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less. Example 2: Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2 Output: true Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times. Example 3: Input: arr = [1,2,1,2,1,3], m = 2, k = 3 Output: false Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times. &nbsp; Constraints: 2 &lt;= arr.length &lt;= 100 1 &lt;= arr[i] &lt;= 100 1 &lt;= m &lt;= 100 2 &lt;= k &lt;= 100
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: if len(arr) < k*m: return False n = len(arr) pattern = arr[0:m] repeats = 1 for i in range(m, n - m + 1, m): if arr[i:i+m] != pattern: break repeats += 1 if repeats >= k: return True return self.containsPattern(arr[1:], m, k)
// Time complexity: O(N) // Space complexity: O(1) class Solution { public boolean containsPattern(int[] arr, int m, int k) { int count = 0; for (int i = 0; i < arr.length - m; i++) { if (arr[i] == arr[i + m]) { count++; } else { count = 0; } if (count == m * (k-1)) { return true; } } return false; } }
class Solution { public: bool containsPattern(vector<int>& arr, int m, int k) { unordered_map<string, vector<int>> ump; string num = ""; for(int i = 0; i < arr.size(); ++i) num += to_string(arr[i]); for(int i = 0; i <= num.length() - m; ++i){ string str = num.substr(i, m); ump[str].push_back(i); } for(auto it = ump.begin(); it != ump.end(); ++it){ if(it->second.size() >= k){ bool flag = true; for(int i = 1; i < it->second.size(); ++i){ if(it->second[i] - it->second[i - 1] < m) flag = false; } if(flag == true) return true; } } return false; } };
var containsPattern = function(arr, m, k) { const origin = arr.join(','); return arr.some((_, index, array) => { const check = arr.slice(index, m + index).join(',') + ','; index + k * m > arr.length && array.splice(index); const target = check.repeat(k).slice(0, -1); if (~origin.indexOf(target)) return true }); };
Detect Pattern of Length M Repeated K or More Times
Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| &gt; |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] &gt; arr[j]. Return a list of the strongest k values in the array. return the answer in any arbitrary order. Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed). For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6. For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3. &nbsp; Example 1: Input: arr = [1,2,3,4,5], k = 2 Output: [5,1] Explanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer. Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 &gt; 1. Example 2: Input: arr = [1,1,3,5,5], k = 2 Output: [5,5] Explanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5]. Example 3: Input: arr = [6,7,11,7,6,8], k = 5 Output: [11,8,6,6,7] Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7]. Any permutation of [11,8,6,6,7] is accepted. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 105 -105 &lt;= arr[i] &lt;= 105 1 &lt;= k &lt;= arr.length
class Solution: def getStrongest(self, arr: List[int], k: int) -> List[int]: n = len(arr) medInd = (n-1)//2 arr = sorted(arr) med = arr[medInd] start, end = 0, n-1 ans = [] while start <= end and len(ans) < k: if abs(med - arr[end]) < abs(med - arr[start]): ans.append(arr[start]) start += 1 else:# abs(med - arr[end]) >= abs(med - arr[start]): # <= because end is always bigger in a sorted array ans.append(arr[end]) end -= 1 return ans
class Solution { public int[] getStrongest(int[] arr, int k) { int[] result = new int[k]; int n = arr.length, left = 0, right = n - 1, idx = 0; Arrays.sort(arr); int median = arr[(n - 1) / 2]; while (left <= right) { int diff_l = Math.abs(arr[left] - median); int diff_r = Math.abs(arr[right] - median); if (diff_r > diff_l) result[idx++] = arr[right--]; else if (diff_l > diff_r) result[idx++] = arr[left++]; else if (arr[right] > arr[left]) result[idx++] = arr[right--]; else result[idx++] = arr[left++]; if (idx == k) break; } return result; } }
class Solution { public: vector<int> getStrongest(vector<int>& arr, int k) { int n=arr.size(); sort(arr.begin(),arr.end()); int m=arr[(n-1)/2]; priority_queue<pair<int,int>> pq; for(auto it: arr) { pq.push({abs(it-m),it}); } vector<int> ans; while(k-- && !pq.empty()) { ans.push_back(pq.top().second); pq.pop(); } return ans; } };
var getStrongest = function(arr, k) { // sort array so we can easily find median const sorted = arr.sort((a,b) => a-b) // get index of median const medianIndex = Math.floor(((sorted.length-1)/2)) // get median const median = sorted[medianIndex] // custom sort function following the parameters given us in the description const compareFunction = (a, b) => { if (Math.abs(a-median) > Math.abs(b-median)) { return 1 } else if (Math.abs(a-median) === Math.abs(b-median) && a > b) { return 1 } else { return -1 } } // sort array using our custom sort function const strongest = arr.sort(compareFunction).reverse().slice(0,k); return strongest; };
The k Strongest Values in an Array
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2 * 104 -10 &lt;= nums[i] &lt;= 10 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
class Solution: def maxProduct(self, nums: List[int]) -> int: prod=1 maxprod=-100000000 for i in range(len(nums)): # traverse from L-R so that we get max prod*=nums[i] maxprod=max(maxprod,prod) if prod==0: prod=1 prod=1 for i in range(len(nums)-1,-1,-1): #if 0 or -ve present at starting then find from back prod*=nums[i] maxprod=max(maxprod,prod) if prod==0: prod=1 return maxprod
class Solution { public int maxProduct(int[] nums) { int ans = Integer.MIN_VALUE; int m = 1; for(int i=0; i< nums.length; i++){ m*=nums[i]; ans = Math.max(m, ans); if(m == 0) m=1; } int n = 1; for(int i=nums.length-1; i>=0; i--){ n*=nums[i]; ans = Math.max(n, ans); if(n == 0) n=1; } return ans; } }
class Solution { public: int maxProduct(vector<int>& nums) { int n = nums.size(); int negPro = 1; int posPro = 1; int CHECK_ZERO = 0; int res = INT_MIN; for(int i = 0; i < n; i++) { if(nums[i] == 0) { posPro = 1; negPro = 1; CHECK_ZERO = 1; } int numPos = posPro * nums[i]; int numNeg = negPro * nums[i]; posPro = max(numPos, max(numNeg, nums[i])); negPro = min(numPos, min(numNeg, nums[i])); res = max(posPro,res); } return (CHECK_ZERO ? max(0,res) : res); } };
/** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { const n = nums.length - 1; let ans = nums[0]; let l = 1, r = 1; for (let i = 0; i < nums.length; i++) { l = (l ? l : 1) * nums[i]; r = (r ? r : 1) * nums[n - i]; ans = Math.max(ans, Math.max(l, r)); } return ans; };
Maximum Product Subarray
Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array. &nbsp; Example 1: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] Example 2: Input: nums = [5], k = 9 Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 3 * 104 -104 &lt;= nums[i] &lt;= 104 2 &lt;= k &lt;= 104
class Solution: def subarraysDivByK(self, nums, k): n = len(nums) prefix_mod = 0 result = 0 # There are k mod groups 0...k-1. mod_groups = [0] * k mod_groups[0] = 1 for num in nums: # Take modulo twice to avoid negative remainders. prefix_mod = (prefix_mod + num % k + k) % k # Add the count of subarrays that have the same remainder as the current # one to cancel out the remainders. result += mod_groups[prefix_mod] mod_groups[prefix_mod] += 1 return result
class Solution { public int subarraysDivByK(int[] nums, int k) { HashMap<Integer,Integer> map = new HashMap<>(); int count = 0; int sum = 0; for(int i=0;i<nums.length;i++){ sum +=nums[i]; int rem =sum%k; if(rem <0){ rem = rem+k; // -4%3 == -1 and 2 both bec -4 = 3(-1) +(-1) = 3(-2) + 2 } if(rem==0){ count++; } if(map.containsKey(rem)){ count+=map.get(rem); } map.put(rem,map.getOrDefault(rem,0)+1); } return count; } }
class Solution { public: int subarraysDivByK(vector<int>& nums, int k) { // take an ans variable int ans = 0; // initialize a map of int, int and insert {0,1} as 0 occurs first time for sum unordered_map<int, int> mapp; mapp.insert({0,1}); // initialize presum = 0 and remainder rem = 0 which will be used in further calculations int presum = 0; int rem = 0; // Logic /* 1. We will traverse the entire given array/vector. 2. While traversing we will add the element in our presum, i.e presum += nums[i] . 3. Now we will do the % of presum and k and store it in rem that we have created. 4. We need to take care of negative value of rem. If it is < 0, then we will add k to the remainder to make it positive. 5. Now we will check if rem already exist in the map. If it exist then we will add it's frequency to ans variable and then increment rem's value in map, i.e. mapp[rem]++, else we will add it in the map. 6. At last we will return ans. */ for(int i=0; i<nums.size(); i++) { presum += nums[i]; rem = presum % k; if(rem < 0) rem += k; if(mapp.find(rem) != mapp.end()) { ans += mapp[rem]; mapp[rem]++; } else { mapp.insert({rem,1}); } } return ans; } };
var subarraysDivByK = function(nums, k) { let count = 0; let map = new Map(); map.set(0, 1) let sum = 0; for(let i=0; i<nums.length; i++){ sum += nums[i]; let rem = sum%k; if(rem<0) rem += k; if(map.has(rem)){ count += map.get(rem) map.set(rem, map.get(rem)+1) }else{ map.set(rem, 1) } } return count };
Subarray Sums Divisible by K