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 a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here.   Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1.   Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only.
class Solution: def longestPalindrome(self, s: str) -> int: letters = {} for letter in s: #count each letter and update letters dict if letter in letters: letters[letter] += 1 else: letters[letter] = 1 plus1 = 0 # if there is a letter with count of odd ans must +=1 ans = 0 for n in letters.values(): if n == 1: #1 can only appear in the middle of our word plus1 = 1 elif n%2 == 0: ans += n else: ans += n - 1 plus1 = 1 return ans + plus1
class Solution { public int longestPalindrome(String s) { HashMap<Character, Integer> map = new HashMap<>(); int evenNo = 0; int oddNo = 0; for ( int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } for (Map.Entry e : map.entrySet()) { int n = (int) e.getValue(); if (n % 2 != 0) { oddNo += n; } evenNo += (n / 2) * 2; } if (oddNo > 0) { evenNo += 1; } return evenNo; } }
class Solution { public: int longestPalindrome(string s) { map<char,int> mp; for(int i=0;i<s.length();i++){ mp[s[i]]++; } int ans = 0; int odd = 0; for(auto i:mp){ if(i.second % 2 == 1){ odd = 1; } ans = ans + (i.second/2)*2; } return ans+odd; } };
var longestPalindrome = function(s) { const hashMap = {}; let ouput = 0; let hashOdd = false; for (let i = 0; i < s.length; i++) { if (!hashMap[s[i]]) { hashMap[s[i]] = 0; } hashMap[s[i]] += 1; } Object.values(hashMap)?.forEach(character => { ouput += character%2 ? character - 1 : character; if (character%2 && !hashOdd) { hashOdd = true; } }); return ouput + (hashOdd ? 1 : 0); };
Longest Palindrome
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in&nbsp;O(n)&nbsp;time and without using the division operation. &nbsp; Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2: Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0] &nbsp; Constraints: 2 &lt;= nums.length &lt;= 105 -30 &lt;= nums[i] &lt;= 30 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. &nbsp; Follow up:&nbsp;Can you solve the problem in O(1)&nbsp;extra&nbsp;space complexity? (The output array does not count as extra space for space complexity analysis.)
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: pre = [1]* (len(nums)+1) back = [1]*(len(nums)+1) for i in range(len(nums)): pre[i+1] = pre[i]*nums[i] for i in range(len(nums)-1,-1,-1): back[i-1] = back[i]*nums[i] for i in range(len(pre)-1): nums[i]=pre[i]*back[i] return nums
class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int pre[] = new int[n]; int suff[] = new int[n]; pre[0] = 1; suff[n - 1] = 1; for(int i = 1; i < n; i++) { pre[i] = pre[i - 1] * nums[i - 1]; } for(int i = n - 2; i >= 0; i--) { suff[i] = suff[i + 1] * nums[i + 1]; } int ans[] = new int[n]; for(int i = 0; i < n; i++) { ans[i] = pre[i] * suff[i]; } return ans; } }
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int zero=0,product=1; for(auto i:nums){ if(i==0) zero++; else product*=i; } for(int i=0;i<nums.size();i++){ if(nums[i] == 0 && zero>1){ nums[i]=0; } else if(nums[i] == 0){ nums[i]=product; } else if(zero > 0){ nums[i]=0; } else nums[i]=product/nums[i]; } return nums; } };
/** * @param {number[]} nums * @return {number[]} */ var productExceptSelf = function(nums) { let result = []; let len = nums.length; let prefix = 1; for (let i = 0; i < len; i++) { result[i] = prefix; prefix *= nums[i]; } let postfix = 1; for (let i = len - 1; i >= 0; i--) { result[i] *= postfix; postfix *= nums[i]; } return result; };
Product of Array Except Self
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). &nbsp; Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 &nbsp; Constraints: 2 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 105
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: ans = 0 n = len(nums) countToFreq = defaultdict(int) # key = count value = Freq ex 2 occured 3 times in nums so 2 : 3 freqToCount = defaultdict(int) # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3 for i,val in enumerate(nums): x = countToFreq[val] + 1 freqToCount[x - 1] -= 1 if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1) freqToCount[x] += 1 countToFreq[val] = x # if a single item is repeated for i + 1 times like [1,1,1] if countToFreq[val] == i + 1 :ans = i + 1 # if all items are having same frequency like [2,2,1,1,3,3] elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1 # if all items have same frequency except one having 1 freq like [2,2,3,3,1] elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1 # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3] elif len(freqToCount) == 2: keys,values = [],[] for j in freqToCount:keys.append(j) , values.append(freqToCount[j]) if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1 return ans
import java.util.TreeMap; import java.util.NavigableMap; class Solution { public int maxEqualFreq(int[] nums) { Map<Integer, Integer> F = new HashMap<>(); //Frequencies NavigableMap<Integer, Integer> V = new TreeMap<>(); //Values for frequencies int max = 0; for (int i = 0; i < nums.length; i++) { increaseCount(F, nums[i]); int frequency = F.get(nums[i]); decreaseCount(V, frequency - 1); increaseCount(V, frequency); if (isPossibleToRemove(V)) max = i; } return max + 1; } public boolean isPossibleToRemove(NavigableMap<Integer, Integer> frequenciesMap) { if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies Map.Entry<Integer, Integer> first = frequenciesMap.firstEntry(); Map.Entry<Integer, Integer> last = frequenciesMap.lastEntry(); if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d] int firstReduced = removeElement(first); int lastReduced = removeElement(last); if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false; return true; } //Try to remove element which contributes to this frequency: //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1 //if there are more than 1 occurences of such frequency, removing 1 element will not change it public int removeElement(Map.Entry<Integer, Integer> frequencyValue) { if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1; return frequencyValue.getKey(); } public void decreaseCount(Map<Integer, Integer> map, int element) { if (!map.containsKey(element)) return; map.put(element, map.get(element) - 1); if (map.get(element) == 0) map.remove(element); } public void increaseCount(Map<Integer, Integer> map, int element) { if (!map.containsKey(element)) map.put(element, 0); map.put(element, map.get(element) + 1); } }
class Solution { public: int maxEqualFreq(vector<int>& nums) { int n=nums.size(); unordered_map<int,int> mp1,mp2; //one to store the frequency of each number , and one which will store the frequency of the frequency int ans=0; for(int i=0;i<n;i++) { int c=nums[i]; mp1[c]++; mp2[mp1[c]]++; if(i!=n-1 && mp2[mp1[c]]*mp1[c]==i+1) //when curernt length is equal to the total same frequency of numbers then we need one more //number which may be anything so doesn't matter . //so we just traverse till n-2 and that's it. ans=i+2; if(mp2[mp1[c]]*mp1[c]==i) //when current length is equal to the total same frequency of numbers plus one extra no. //( so here taken ==i (i+1-1)) which can be 1. same as any number present 2. different number .. //but doesn't matter and our condition just satisfies ... so just take the current length . ans=i+1; } return ans; } };
// *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value var maxEqualFreq = function(nums) { // create cache to count the frequency of each number const numCnt = {}; // create cache to count the number of 'number of frequencies' // e.g. [1,2,3,2,4,4,3,1,5] // { 1: 1 1 number appeared with a frequency of 1 // 2: 3 } 3 numbers appeared with a frequency of 2 const cntFreq = {}; // holds the maximum frequency a number has appeared let maxFreq = 0; // holds solution let result = 0; // iterate through numbers for (let i = 0; i < nums.length; i++) { // get current number; const num = nums[i]; // subtract one from the current frequency of the current number cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] - 1 : -1; // increase the count of the current number numCnt[num] = numCnt[num] ? numCnt[num] + 1 : 1; // add one to the current frequency of the current number cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] + 1 : 1; // if the current frequency is more than the max frequency update the max frequency if (maxFreq < numCnt[num]) maxFreq = numCnt[num]; // if max frequency is 1 or // if the max frequency multiplied by the number of values with that frequency equals the current index or // if the result of the 1 less than the max frequency equals to the current index // update result if (maxFreq === 1 || maxFreq * cntFreq[maxFreq] === i || (maxFreq - 1) * (cntFreq[maxFreq - 1] + 1) === i) { result = i + 1; } } return result; };
Maximum Equal Frequency
Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: FrontMiddleBack() Initializes the queue. void pushFront(int val) Adds val to the front of the queue. void pushMiddle(int val) Adds val to the middle of the queue. void pushBack(int val) Adds val to the back of the queue. int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1. int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1. int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1. Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6]. &nbsp; Example 1: Input: ["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] [[], [1], [2], [3], [4], [], [], [], [], []] Output: [null, null, null, null, null, 1, 3, 4, 2, -1] Explanation: FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // [1] q.pushBack(2); // [1, 2] q.pushMiddle(3); // [1, 3, 2] q.pushMiddle(4); // [1, 4, 3, 2] q.popFront(); // return 1 -&gt; [4, 3, 2] q.popMiddle(); // return 3 -&gt; [4, 2] q.popMiddle(); // return 4 -&gt; [2] q.popBack(); // return 2 -&gt; [] q.popFront(); // return -1 -&gt; [] (The queue is empty) &nbsp; Constraints: 1 &lt;= val &lt;= 109 At most&nbsp;1000&nbsp;calls will be made to&nbsp;pushFront,&nbsp;pushMiddle,&nbsp;pushBack, popFront, popMiddle, and popBack.
class FrontMiddleBackQueue: def __init__(self): self.front = deque() self.back = deque() def _correct_size(self): while len(self.back) > len(self.front): self.front.append(self.back.popleft()) while len(self.front) > len(self.back) + 1: self.back.appendleft(self.front.pop()) def pushFront(self, val: int) -> None: self.front.appendleft(val) self._correct_size() def pushMiddle(self, val: int) -> None: if len(self.front) > len(self.back): self.back.appendleft(self.front.pop()) self.front.append(val) self._correct_size() def pushBack(self, val: int) -> None: self.back.append(val) self._correct_size() def popFront(self) -> int: front = self.front if self.front else self.back ret = front.popleft() if front else -1 self._correct_size() return ret def popMiddle(self) -> int: ret = self.front.pop() if self.front else -1 self._correct_size() return ret def popBack(self) -> int: back = self.back if self.back else self.front ret = back.pop() if back else -1 self._correct_size() return ret
class FrontMiddleBackQueue { Deque<Integer> dq1, dq2; public FrontMiddleBackQueue() { dq1 = new ArrayDeque<Integer>(); dq2 = new ArrayDeque<Integer>(); } public void pushFront(int val) { dq1.addFirst(val); } public void pushBack(int val) { dq2.addLast(val); } public void pushMiddle(int val) { while(dq1.size() + 1 < dq2.size()) dq1.addLast(dq2.removeFirst()); while(dq1.size() > dq2.size()) dq2.addFirst(dq1.removeLast()); dq1.addLast(val); } public int popFront() { if(!dq1.isEmpty()) return dq1.removeFirst(); if(!dq2.isEmpty()) return dq2.removeFirst(); return -1; } public int popMiddle() { if(dq1.isEmpty() && dq2.isEmpty()) return -1; while(dq1.size() < dq2.size()) dq1.addLast(dq2.removeFirst()); while(dq1.size() > dq2.size() + 1) dq2.addFirst(dq1.removeLast()); return !dq1.isEmpty() ? dq1.removeLast() : dq2.removeFirst(); } public int popBack() { if(!dq2.isEmpty()) return dq2.removeLast(); if(!dq1.isEmpty()) return dq1.removeLast(); return -1; } }
class FrontMiddleBackQueue { public: deque<int> list1; deque<int> list2; int size; FrontMiddleBackQueue() { size = 0; } void pushFront(int val) { if(list1.size()- list2.size() == 0) { list1.push_front(val); } else { list1.push_front(val); list2.push_front(list1.back()); list1.pop_back(); } size++; } void pushMiddle(int val) { if(list1.size() - list2.size() == 0) { list1.push_back(val); } else { list2.push_front(list1.back()); list1.pop_back(); list1.push_back(val); } size++; } void pushBack(int val) { if(list1.size() - list2.size() == 0) { list2.push_back(val); list1.push_back(list2.front()); list2.pop_front(); } else { list2.push_back(val); } size++; } int popFront() { if(size ==0) return -1; int val = list1.front(); list1.pop_front(); if(list1.size()<list2.size()) { list1.push_back(list2.front()); list2.pop_front(); } size--; return val; } int popMiddle() { if(size ==0) return -1; int val = list1.back(); list1.pop_back(); if(list1.size() < list2.size()) { list1.push_back(list2.front()); list2.pop_front(); } size--; return val; } int popBack() { if(size ==0) return -1; int val; if(size==1) { val = list1.front(); list1.pop_front(); } else { val = list2.back(); list2.pop_back(); int s1 = list1.size(); int s2 = list2.size(); if(list1.size() - list2.size() > 1) { list2.push_front(list1.back()); list1.pop_back(); } } size--; return val; } };
// T.C: // O(1) for init and methods other than pushMiddle(), popMiddle() // O(N) for pushMiddle(), popMiddle() // S.C: O(N) for storage // Doubly linked list node function ListNode(val, prev, next) { this.val = val || 0; this.prev = prev || null; this.next = next || null; } var FrontMiddleBackQueue = function() { this.head = null; this.tail = null; this.len = 0; }; /** * @param {number} val * @return {void} */ FrontMiddleBackQueue.prototype.pushFront = function(val) { if (this.len === 0) { this.head = new ListNode(val); this.tail = this.head; this.len += 1; return; } let newNode = new ListNode(val); newNode.next = this.head; this.head.prev = newNode; this.head = newNode; // the new node becomes the new head this.len += 1; }; /** * @param {number} val * @return {void} */ FrontMiddleBackQueue.prototype.pushMiddle = function(val) { if (this.len <= 1) { this.pushFront(val); return; } let cur = this.head; for (let i = 1; i < Math.floor(this.len / 2); i++) { // we go to previous node of median cur = cur.next; } let newNode = new ListNode(val); let next = cur.next; cur.next = newNode; newNode.prev = cur; newNode.next = next; if (next) next.prev = newNode; this.len += 1; }; /** * @param {number} val * @return {void} */ FrontMiddleBackQueue.prototype.pushBack = function(val) { if (this.len === 0) { this.pushFront(val); return; } let newNode = new ListNode(val); this.tail.next = newNode; newNode.prev = this.tail; this.tail = newNode; // end node becomes the new tail this.len += 1; }; /** * @return {number} */ FrontMiddleBackQueue.prototype.popFront = function() { if (this.len === 0) { return -1; } let front = this.head; let next = front.next; if (next) next.prev = null; this.head = next; this.len -= 1; return front.val; }; /** * @return {number} */ FrontMiddleBackQueue.prototype.popMiddle = function() { if (this.len <= 2) { return this.popFront(); } let cur = this.head; for (let i = 1; i < Math.ceil(this.len / 2); i++) { // we go to median node cur = cur.next; } let prev = cur.prev; let next = cur.next; cur.prev = null; cur.next = null; if (prev) prev.next = next; if (next) next.prev = prev; this.len -= 1; return cur.val; }; /** * @return {number} */ FrontMiddleBackQueue.prototype.popBack = function() { if (this.len <= 1) { return this.popFront(); } let end = this.tail; let prev = end.prev; end.prev = null; prev.next = null; this.tail = prev; this.len -= 1; return end.val; }; /** * Your FrontMiddleBackQueue object will be instantiated and called as such: * var obj = new FrontMiddleBackQueue() * obj.pushFront(val) * obj.pushMiddle(val) * obj.pushBack(val) * var param_4 = obj.popFront() * var param_5 = obj.popMiddle() * var param_6 = obj.popBack() */
Design Front Middle Back Queue
Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way. &nbsp; Example 1: Input: nums = [4,2,3], k = 1 Output: 5 Explanation: Choose index 1 and nums becomes [4,-2,3]. Example 2: Input: nums = [3,-1,0,2], k = 3 Output: 6 Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2]. Example 3: Input: nums = [2,-3,-1,5,-4], k = 2 Output: 13 Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4]. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -100 &lt;= nums[i] &lt;= 100 1 &lt;= k &lt;= 104
from heapq import heapify, heapreplace class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: heapify(nums) while k and nums[0] < 0: heapreplace(nums, -nums[0]) k -= 1 if k % 2: heapreplace(nums, -nums[0]) return sum(nums)
class Solution { public int largestSumAfterKNegations(int[] nums, int k) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int val : nums) minHeap.add(val); while(k > 0){ int curr = minHeap.poll(); minHeap.add(-curr); k--; } int sum = 0; while(!minHeap.isEmpty()){ sum += minHeap.poll(); } return sum; } }
class Solution { public: int largestSumAfterKNegations(vector<int>& A, int k) { priority_queue<int, vector<int>, greater<int>> pq(A.begin(), A.end()); while(k--){ int t=pq.top();pq.pop(); pq.push(t*-1); } int n=0; while(!pq.empty()){ int t=pq.top();pq.pop(); n+=t; } return n; } };
/** * @param {number[]} nums * @param {number} k * @return {number} */ var largestSumAfterKNegations = function(nums, k) { let negations = k let index = 0 const sortedNums = [...nums] // Sort in increasing order sortedNums.sort((a, b) => a - b) // loop into the sorted array using the // number of negations while (negations > 0) { negations-- const currentNumber = -sortedNums[index] const nextNumber = sortedNums[index + 1] sortedNums[index] = currentNumber // if the number is 0, undefined or // the current number is less than the // next number (meaning it will be // less the amount if it's a negative // number) just use the same number // again to flip. if ( currentNumber === 0 || nextNumber === undefined || currentNumber < nextNumber ) continue index++ } return sortedNums.reduce((sum, num) => sum + num, 0) };
Maximize Sum Of Array After K Negations
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference. &nbsp; Example 1: Input: nums = [90], k = 1 Output: 0 Explanation: There is one way to pick score(s) of one student: - [90]. The difference between the highest and lowest score is 90 - 90 = 0. The minimum possible difference is 0. Example 2: Input: nums = [9,4,1,7], k = 2 Output: 2 Explanation: There are six ways to pick score(s) of two students: - [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5. - [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8. - [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2. - [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3. - [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3. - [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6. The minimum possible difference is 2. &nbsp; Constraints: 1 &lt;= k &lt;= nums.length &lt;= 1000 0 &lt;= nums[i] &lt;= 105
class Solution: def minimumDifference(self, nums: List[int], k: int) -> int: nums.sort() cur = float('inf') for i in range(len(nums)-k+1): cur = min(cur, nums[i+k-1]-nums[i])
class Solution { public int minimumDifference(int[] nums, int k) { if(k == 1)return 0; int i = 0,j = k-1,res = Integer.MAX_VALUE; Arrays.sort(nums); while(j < nums.length){ res = Math.min(res,nums[j] - nums[i]); j++; i++; } return res; } }
class Solution { public: int minimumDifference(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int res = nums[k-1] - nums[0]; for (int i = k; i < nums.size(); i++) res = min(res, nums[i] - nums[i-k+1]); return res; } };
```/** * @param {number[]} nums * @param {number} k * @return {number} */ var minimumDifference = function(nums, k) { nums.sort((a,b)=>a-b) let min=nums[0],max=nums[k-1],diff=max-min for(let i=k;i<nums.length;i++){ diff=Math.min(diff,nums[i]-nums[i-k+1]) } return diff };``
Minimum Difference Between Highest and Lowest of K Scores
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer num, return its complement. &nbsp; Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. &nbsp; Constraints: 1 &lt;= num &lt; 231 &nbsp; Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
class Solution: def findComplement(self, num: int) -> int: i = 0 while(2**i <= num): i += 1 return (2**i - num - 1)
class Solution { public int findComplement(int num) { int x=0;int sum=0; while(num>0){ int i = num%2; if(i==0){ sum+=Math.pow(2,x++); } else{ x++; } num/=2; } return sum; } }
class Solution { public: int findComplement(int num) { long n=1; while(n-1<num) { n<<=1; } n--; return n-num; } };
var findComplement = function(num) { return num ^ parseInt(Array(num.toString(2).length).fill("1").join(""), 2) }
Number Complement
Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non&nbsp;included elements in such subsequence.&nbsp; If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.&nbsp; Note that the solution with the given constraints is guaranteed to be&nbsp;unique. Also return the answer sorted in non-increasing order. &nbsp; Example 1: Input: nums = [4,3,10,9,8] Output: [10,9] Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.&nbsp; Example 2: Input: nums = [4,4,7,6,7] Output: [7,7,6] Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 500 1 &lt;= nums[i] &lt;= 100
class Solution: def minSubsequence(self, nums: List[int]) -> List[int]: nums.sort(reverse=True) val = sum(nums) temp = [] for i in range(len(nums)): temp.append(nums[i]) if sum(temp)>val-sum(temp): return temp
class Solution { public List<Integer> minSubsequence(int[] nums) { int total = 0; for(int i=0;i<nums.length;i++){ total += nums[i]; } Arrays.sort(nums); int sum = 0; ArrayList<Integer> ans = new ArrayList<>(); for(int i=nums.length-1;i>=0;i--){ ans.add(nums[i]); sum += nums[i]; if(sum>total-sum){ return ans; } } return ans; } }
class Solution { public: vector<int> minSubsequence(vector<int>& nums) { sort(nums.begin(), nums.end(),greater<int>()); vector<int> res; int sum = 0; for(int i: nums) sum += i; int x=0; for(int i=0; i<nums.size(); i++) { x += nums[i]; sum -= nums[i]; res.push_back(nums[i]); if(x>sum) break; } return res; } };
/** * @param {number[]} nums * @return {number[]} */ var minSubsequence = function(nums) { const target = nums.reduce((a, b) => a + b) / 2; nums.sort((a, b) => b - a); let i = 0, sum = 0; while (sum <= target) { sum += nums[i++]; } return nums.slice(0, i); };
Minimum Subsequence in Non-Increasing Order
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. &nbsp; Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4 Output: 6 Explanation: The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf. Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4 &nbsp; Constraints: 1 &lt;= books.length &lt;= 1000 1 &lt;= thicknessi &lt;= shelfWidth &lt;= 1000 1 &lt;= heighti &lt;= 1000
class Solution: def minHeightShelves(self, books, shelf_width: int) -> int: n, dp = len(books), [float('inf')] * (len(books)+1) dp[0] = 0 for i in range(1, n+1): max_width, max_height, j = shelf_width, 0, i - 1 while j >= 0 and max_width - books[j][0] >= 0: max_width -= books[j][0] max_height = max(max_height, books[j][1]) dp[i] = max_height j -= 1 if j >= 0 and max_width - books[j][0] < 0: j = i - 1 dp[i] = float('inf') width, height = 0, 0 while j >= 0 and width + books[j][0] <= shelf_width: width = width + books[j][0] height = max(books[j][1], height) dp[i] = min(dp[i], height + dp[j]) j -= 1 return dp[n]
class Solution { int[][] books; int shefWidth; Map<String, Integer> memo = new HashMap(); public int findMinHeight(int curr, int maxHeight, int wRem) { String key = curr + ":" + wRem ; if(memo.containsKey(key)) return memo.get(key); if(curr == books.length ) return maxHeight; int[] currBook = books[curr]; memo.put( key, currBook[0] <= wRem ? Math.min( maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0]) , // new shelf findMinHeight(curr + 1, Math.max(maxHeight, currBook[1]),wRem - currBook[0] )) // same shelf : maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0]) ); // new shelf return memo.get(key); } public int minHeightShelves(int[][] books, int shelfWidth) { this.books = books; this.shefWidth = shelfWidth; return findMinHeight(0, 0, shelfWidth); } }
class Solution { public: int minHeightShelves(vector<vector<int>>& books, int shelfWidth) { int n=books.size(); vector<vector<int>> cost(n+1,vector<int>(n+1)); for(int i=1;i<=n;i++) { int height=books[i-1][1]; int width=books[i-1][0]; cost[i][i]=height; for(int j=i+1;j<=n;j++) { height=max(height,books[j-1][1]); width+=books[j-1][0]; if(width<=shelfWidth) cost[i][j]=height; else cost[i][j]=-1; } } vector<int> ans(n+1); ans[0]=0; for(int i=1;i<=n;i++) { ans[i]=INT_MAX; for(int j=1;j<=i;j++) { if(cost[j][i]==-1) continue; if(ans[j-1]!=INT_MAX) ans[i]=min(ans[i],ans[j-1]+cost[j][i]); } } return ans[n]; } };
var minHeightShelves = function(books, shelfWidth) { let booksArr = [] for(let i = 0; i < books.length; i++) { let remainingWidth = shelfWidth - books[i][0] let bookHeight = books[i][1] let maxHeight = bookHeight let prevSum = booksArr[i - 1] !== undefined ? booksArr[i - 1] : 0 let minSumHeight = bookHeight + prevSum for(let x = i - 1; x >= 0 ; x--) { let prevBookWidth = books[x][0] let prevBookHeight = books[x][1] if(remainingWidth - prevBookWidth < 0) break remainingWidth -= prevBookWidth prevSum = booksArr[x - 1] !== undefined ? booksArr[x - 1] : 0 maxHeight = Math.max(maxHeight, prevBookHeight) minSumHeight = Math.min(prevSum + maxHeight, minSumHeight) } booksArr[i] = minSumHeight } return booksArr[books.length - 1] };
Filling Bookcase Shelves
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. &nbsp; Example 1: Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. Example 2: Input: n = 1, bad = 1 Output: 1 &nbsp; Constraints: 1 &lt;= bad &lt;= n &lt;= 231 - 1
class Solution: def firstBadVersion(self, n: int) -> int: fast, slow = int(n/2), n diff = abs(fast-slow) while isBadVersion(fast) == isBadVersion(slow) or diff > 1: fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast diff = abs(fast-slow) return fast if isBadVersion(fast) else slow
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int s = 0; int e = n; while(s < e) { int mid = s +(e-s)/2; if(isBadVersion(mid)){ e = mid ; } else { s = mid +1; } } return e ; } }
class Solution { public: int firstBadVersion(int n) { //Using Binary Search int lo = 1, hi = n, mid; while (lo < hi) { mid = lo + (hi - lo) / 2; if (isBadVersion(mid)) hi = mid; else lo = mid+1; } return lo; } };
/** * Definition for isBadVersion() * * @param {integer} version number * @return {boolean} whether the version is bad * isBadVersion = function(version) { * ... * }; */ /** * @param {function} isBadVersion() * @return {function} */ var solution = function(isBadVersion) { /** * @param {integer} n Total versions * @return {integer} The first bad version */ return function(n) { let ceiling = n let floor = 1 let firstBadVersion = -1 while (floor <= ceiling) { const middle = Math.floor((ceiling + floor) / 2) if (isBadVersion(middle)) { firstBadVersion = middle ceiling = middle - 1 } else { floor = middle + 1 } } return firstBadVersion }; };
First Bad Version
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations. You can perform the following operation at most maxOperations times: Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls. Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty&nbsp;after performing the operations. &nbsp; Example 1: Input: nums = [9], maxOperations = 2 Output: 3 Explanation: - Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -&gt; [6,3]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -&gt; [3,3,3]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. Example 2: Input: nums = [2,4,8,2], maxOperations = 4 Output: 2 Explanation: - Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -&gt; [2,4,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -&gt; [2,2,2,4,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -&gt; [2,2,2,2,2,4,2]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -&gt; [2,2,2,2,2,2,2,2]. The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2. Example 3: Input: nums = [7,17], maxOperations = 2 Output: 7 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= maxOperations, nums[i] &lt;= 109
class Solution: def minimumSize(self, nums: List[int], maxOperations: int) -> int: l, r = 1, max(nums) while l < r: mid = (l + r) // 2 if sum([(n - 1) // mid for n in nums]) > maxOperations: l = mid + 1 else: r = mid return l
class Solution { public int minimumSize(int[] nums, int maxOperations) { //initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at the price of time consumption. //The answer should be the minimized max value. int min = 0; int max = 1000000000; //Compared with min<max or min <= max, min + 1 < max will avoid infinite loops e.g. when min = 2, max = 3 while (min +1< max) { int mid = (max - min)/2 + min; //count indicates the operation times with atmost mid balls in bag. int count = 0; for (int a: nums) { //this is the same as Math. ceil(a/mid) - 1=> math.ceil(a/mid) gives the number of divided bags, we subtract the number by 1 to get the subdivision operation times. count+=(a-1)/mid; } //if count < maxOperations, max WOULD be further minimized and set to mid; //if count = maxOperations, max still COULD be further minimized and set to mid. //so we combine < and = cases together in one if condition if (count <= maxOperations) { //max = mid - 1 will not work in this case becasue mid could be the correct answer. //To not miss the correct answer we set a relatively "loose" boundary for max and min. max = mid; } else{ min = mid; } } //Now we find the minimized max value return max; } }
class Solution { public: bool isPossible(vector<int>&nums,int mid_penalty,int maxOperations) { int operations=0; for(int i=0;i<nums.size();i++) { operations+=(nums[i]/mid_penalty); //Operations Nedded to divide that element. if(nums[i]%mid_penalty==0) //if it is completely divisible means less 1 less is needed for that nums. operations--; } return operations<=maxOperations?1:0; //If operations are less than maxOperations it is one of our ans. } int minimumSize(vector<int>& nums, int maxOperations) { int low_penalty=1,high_penalty=*max_element(nums.begin(),nums.end()); int ans=high_penalty; while(low_penalty<=high_penalty) { int mid_penalty=low_penalty+(high_penalty-low_penalty)/2; if(mid_penalty==0) //To avoid divison by zero. break; if(isPossible(nums,mid_penalty,maxOperations)) { ans=mid_penalty; high_penalty=mid_penalty-1; } else low_penalty=mid_penalty+1; } return ans; } };
var minimumSize = function(nums, maxOperations) { let i = 1 let j = Math.max(...nums) while (i <= j) { let mid = Math.floor((j-i)/2 + i) let count = 0 nums.forEach(n => count += Math.floor((n-1)/mid)) if (count <= maxOperations) { j = mid - 1 } else { i = mid + 1 } } return i };
Minimum Limit of Balls in a Bag
You are given a map of a server center, represented as a m * n integer matrix&nbsp;grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers&nbsp;that communicate with any other server. &nbsp; Example 1: Input: grid = [[1,0],[0,1]] Output: 0 Explanation:&nbsp;No servers can communicate with others. Example 2: Input: grid = [[1,0],[1,1]] Output: 3 Explanation:&nbsp;All three servers can communicate with at least one other server. Example 3: Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] Output: 4 Explanation:&nbsp;The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m &lt;= 250 1 &lt;= n &lt;= 250 grid[i][j] == 0 or 1
class Solution: def countServers(self, grid: List[List[int]]) -> int: def helper(row,col,count): for c in range(len(grid[0])): if c == col: continue if grid[row][c] == 1: count += 1 return count for r in range(len(grid)): if r == row: continue if grid[r][col] == 1: count += 1 return count return count count = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 1: count = helper(row,col,count) return count
class Solution { int []parent; int []rank; public int countServers(int[][] grid) { parent=new int[grid.length*grid[0].length]; rank=new int[grid.length*grid[0].length]; for(int i=0;i<parent.length;i++){ parent[i]=i; rank[i]=0; } for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]==1){ check(i,j,grid); } } } int count=0; for(int i=0;i<parent.length;i++){ if(parent[i]!=i||rank[i]>0){ count++; } } return count; } public void check(int sr,int sc,int [][]grid){ int mbox=sr*grid[0].length+sc; for(int i=sr;i<grid.length;i++){ if(grid[i][sc]==1){ int cbox=i*grid[0].length+sc; int xl=find(mbox); int yl=find(cbox); if(xl!=yl){ union(xl,yl); } } } for(int j=sc;j<grid[0].length;j++){ if(grid[sr][j]==1){ int cbox=sr*grid[0].length+j; int xl=find(mbox); int yl=find(cbox); if(xl!=yl){ union(xl,yl); } } } } int find(int x){ if(parent[x]==x){ return x; }else{ parent[x]=find(parent[x]); return parent[x]; } } void union(int x,int y){ if(rank[x]>rank[y]){ parent[y]=x; }else if(rank[y]>rank[x]){ parent[x]=y; }else{ parent[x]=y; rank[y]++; } } }
class Solution { public: int countServers(vector<vector<int>>& grid) { int n=grid.size(),m=grid[0].size(); vector<vector<bool>>visited(n,vector<bool>(m,false)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j] && !visited[i][j]) { bool flag=false; for(int x=0;x<n;x++) { if(x!=i && grid[x][j] && !visited[x][j]) visited[x][j]=true,flag=true; if(!flag && x!=i && visited[x][j]) flag=true; } for(int x=0;x<m;x++) { if(x!=j && grid[i][x] && !visited[i][x]) visited[i][x]=true,flag=true; if(!flag && x!=j && visited[i][x]) flag=true; } if(flag) visited[i][j]=true; } } } int ans=0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(visited[i][j]) ans++; return ans; } };
var countServers = function(grid) { const m = grid.length; const n = grid[0].length; const lastRows = []; const lastCols = []; const set = new Set(); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { const currIdx = (i * n) + j; const rowNeiIdx = lastRows[i]; if (rowNeiIdx != null) { set.add(currIdx).add(rowNeiIdx); } const colNeiIdx = lastCols[j]; if (colNeiIdx != null) { set.add(currIdx).add(colNeiIdx); } lastRows[i] = currIdx; lastCols[j] = currIdx; } } } return set.size; };
Count Servers that Communicate
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary()&nbsp;Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word)&nbsp;Returns true if there is any string in the data structure that matches word&nbsp;or false otherwise. word may contain dots '.' where dots can be matched with any letter. &nbsp; Example: Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True &nbsp; Constraints: 1 &lt;= word.length &lt;= 25 word in addWord consists of lowercase English letters. word in search consist of '.' or lowercase English letters. There will be at most 3 dots in word for search queries. At most 104 calls will be made to addWord and search.
class TrieNode: def __init__(self, val): self.val = val self.children = {} self.isEnd = False class WordDictionary: def __init__(self): self.root = TrieNode("*") def addWord(self, word: str) -> None: curr = self.root for c in word: if c not in curr.children: curr.children[c] = TrieNode(c) curr = curr.children[c] curr.isEnd = True def search(self, word: str) -> bool: def dfs(root, word): curr = root for i in range(len(word)): if word[i] == ".": for l in curr.children.values(): if dfs(l, word[i+1:]) == True: return True return False if word[i] not in curr.children: return False curr = curr.children[word[i]] return curr.isEnd return dfs(self.root, word)
class WordDictionary { private class Node{ boolean last; Node[] sub; Node(){ last = false; sub = new Node[26]; } } Node root; public WordDictionary() { root = new Node(); } public void addWord(String word) { Node temp = root; for(char c : word.toCharArray()){ int index = c-'a'; if(temp.sub[index] == null) temp.sub[index] = new Node(); temp = temp.sub[index]; } temp.last = true; } public boolean search(String word) { Node temp = root; return dfs(temp, word, 0); } private boolean dfs(Node node, String word, int i){ if(i == word.length()) return node.last; int index = word.charAt(i)-'a'; if(word.charAt(i) == '.'){ for(int j = 0; j < 26; j++){ if(node.sub[j] != null) if(dfs(node.sub[j], word, i+1)) return true; } return false; } else if(node.sub[index] == null) return false; return dfs(node.sub[index], word, i+1); } }
class WordDictionary { public: struct tr { bool isword; vector<tr*> next; tr() { next.resize(26, NULL); isword = false; } }; tr *root; WordDictionary() { root = new tr(); } void addWord(string word) { tr *cur = root; for(auto c: word) { if(cur->next[c-'a'] == NULL) { cur->next[c-'a'] = new tr(); } cur = cur->next[c-'a']; } cur->isword = true; } bool dfs(string& word, int i, tr* cur) { if(!cur ){ return false; } if(i == word.size()) { return cur->isword; } for (; i < word.size(); i++) { char c = word[i]; if (c == '.') { for (auto it: cur->next) { if(dfs(word, i+1, it)) { return true; } } return false; } else { if(cur->next[c-'a'] == NULL) { return false; } cur = cur->next[c-'a']; } } return cur->isword; } bool search(string word) { return dfs(word, 0, root); } }; /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */
var WordDictionary = function() { this.aryWordList = []; }; /** * @param {string} word * @return {void} */ WordDictionary.prototype.addWord = function(word) { this.aryWordList.push(word); }; /** * @param {string} word * @return {boolean} */ WordDictionary.prototype.search = function(word) { const isWordsMatch = (first, second) => { if (first.length !== second.length) return false; if (first.length == 0 && second.length == 0) return true; // Exit case for recursion if( first[0] === second[0] || first[0] === "." || second[0] === ".") return isWordsMatch(first.substring(1), second.substring(1)); return false; } const isWordFound = () => { let isFound = false; for(var indexI=0; indexI<this.aryWordList.length; indexI++) { if(isWordsMatch(this.aryWordList[indexI], word)) { isFound = true; break; } } return isFound; } return word.indexOf(".") === -1 ? this.aryWordList.includes(word) : isWordFound(); }; /** * Your WordDictionary object will be instantiated and called as such: * var obj = new WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */
Design Add and Search Words Data Structure
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” &nbsp; Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2,1], p = 2, q = 1 Output: 2 &nbsp; Constraints: The number of nodes in the tree is in the range [2, 105]. -109 &lt;= Node.val &lt;= 109 All Node.val are unique. p != q p and q will exist in the BST.
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)): return root elif (root.val > p.val): return self.lowestCommonAncestor(root.left, p, q) else: return self.lowestCommonAncestor(root.right, p , q)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q)return root; TreeNode left = lowestCommonAncestor(root.left, p , q); TreeNode right = lowestCommonAncestor(root.right, p ,q); if(left == null)return right; if(right == null)return left; else{ return root; } } }
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left,p,q); else if(p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right,p,q); return root; } };
var lowestCommonAncestor = function(root, p, q) { while(root){ if(p.val>root.val && q.val>root.val){ root=root.right }else if(p.val<root.val && q.val<root.val){ root=root.left }else{ return root } } }
Lowest Common Ancestor of a Binary Search Tree
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: m = 1, n = 1 Output: 3 Explanation: The three possible colorings are shown in the image above. Example 2: Input: m = 1, n = 2 Output: 6 Explanation: The six possible colorings are shown in the image above. Example 3: Input: m = 5, n = 5 Output: 580986 &nbsp; Constraints: 1 &lt;= m &lt;= 5 1 &lt;= n &lt;= 1000
class Solution: def colorTheGrid(self, m: int, n: int) -> int: from functools import reduce MOD = 10**9 + 7 sum_mod = lambda x,y: (x+y)%MOD def normalize(pat_var): mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) } mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3 return tuple([ mapping[e] for e in pat_var]) def get_pats(m, i, pat, pats): if i == m-1: pats.append(tuple(pat)) return i_nx = i+1 for p_it_nx in (1,2,3): if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]): pat.append(p_it_nx) get_pats(m, i_nx, pat, pats) pat.pop() return pats def get_trans(pat, i, pat_pre, trans): if i == len(pat)-1: pat_nl = normalize(pat_pre) trans[pat_nl] = trans.get(pat_nl, 0) + 1 return for p_it_pre in (1,2,3): i_nx = i+1 if (p_it_pre != pat[i_nx] and (not pat_pre or p_it_pre != pat_pre[-1])): pat_pre.append(p_it_pre) get_trans(pat, i_nx, pat_pre, trans) pat_pre.pop() return trans pats = get_pats(m, -1, [], []) # {pattern_i: {pattern_pre:count}} pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } p_counts = { pat:1 for pat in pat_trans.keys() } for i in range(n-1): p_counts_new = {} for pat, trans in pat_trans.items(): p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items())) p_counts = p_counts_new res = reduce(sum_mod, (cnt for cnt in p_counts.values())) perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m)))) return (res * perms) % MOD
class Solution { static int mod=(int)(1e9+7); public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][]) { if(n==0) { return 1; } if(dp[n][src]!=-1) { return dp[n][src]; } int val=0; for(Integer ap:arr.get(src)) { val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod; } return dp[n][src]=val; } public static void val(ArrayList<String> arr,int color,int m,String s) { if(m==0) { arr.add(s); return; } for(int i=0;i<3;i++) { if(color!=i) val(arr,i,m-1,s+i); } } public static boolean Match(String s,String s1) { for(int i=0;i<s.length();i++) { if(s.charAt(i)==s1.charAt(i)) { return false; } } return true; } public int colorTheGrid(int m, int n) { ArrayList<String> arr=new ArrayList<String>(); for(int i=0;i<3;i++) { String s=""; val(arr,i,m-1,s+i); } ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>(); for(int i=0;i<arr.size();i++) { adj.add(new ArrayList<Integer>()); } for(int i=0;i<adj.size();i++) { for(int j=0;j<arr.size();j++) { if(Match(arr.get(i),arr.get(j))) { adj.get(i).add(j); } } } int dp[][]=new int[n+1][adj.size()+1]; for(int i=0;i<=n;i++) { Arrays.fill(dp[i],-1); } int sum12=0; for(int i=0;i<arr.size();i++) { sum12=(sum12%mod+dfs(n-1,adj,i,dp)%mod)%mod; } return sum12; } }
vector<string> moves; int MOD = 1e9 + 7; void fill(string s, int n, int p){ if(n==0){ moves.push_back(s); return; } for(int i=1; i<4; i++){ if(p==i){ continue; } string m = to_string(i); fill(s+m, n-1, i); } return; } class Solution { public: vector<vector<int>>memo; int solve(int n, int lastIdx, int m){ if (n == 0) return 1; int ret = 0; if (memo[n][lastIdx] != -1) return memo[n][lastIdx]; string last = moves[lastIdx]; for (int idx = 0; idx<moves.size(); idx++) { string move = moves[idx]; bool same = false; for (int i = 0; i < m; i++) if (move[i] == last[i]) same = true; if (!same) ret = (ret + solve(n - 1, idx, m)%MOD)%MOD; } return memo[n][lastIdx]= ret%MOD; } int colorTheGrid(int m, int n){ moves.clear(); fill("", m, -1); //cout<<moves.size()<<endl; memo.resize(n + 1, vector<int>(moves.size(), -1)); int ret = 0; for (int idx = 0; idx < moves.size(); idx++) ret = (ret + solve(n-1, idx, m)%MOD)%MOD; return ret; } };
// transform any decimal number to its ternary representation let ternary=(num,len)=>{ let A=[],times=0 while(times++<len) A.push(num%3),num= (num-num%3)/3 return A } // deduce whether my array does not contain 2 consecutive elements let adjdiff=Array=>Array.every((d,i)=>i==0||d!==Array[i-1]) //main var colorTheGrid = function(n, m) { let mod=1e9+7,adj=[...Array(3**(n))].map(d=>new Set()), //1.turn every potential state to a ternary(base3) representation base3=[...Array(3**n)].map((d,i)=>ternary(i,n)), //3 conditions such that state a can be previous to state b ok=(a,b)=>adjdiff(base3[a])&& adjdiff(base3[b])&& base3[a].every( (d,i)=>d!==base3[b][i]) //2.determine what are the acceptable adjacent states of any given state for(let m1=0;m1<3**n;m1++) for(let m2=0;m2<3**n;m2++) if(ok(m1,m2)) adj[m1].add(m2),adj[m2].add(m1) //3.do 2-row dp, where dp[state]= the number of colorings where the last line is colored based on state let dp=[...Array(3**n)].map((d,i)=>Number(adjdiff(base3[i]))) for(let i=1,dp2=[...Array(3**n)].map(d=>0);i<m;i++,dp=[...dp2],dp2.fill(0)) for(let m1=0;m1<3**n;m1++) for(let prev of Array.from(adj[m1])) dp2[m1]=(dp2[m1]+dp[prev])%mod return dp.reduce((a,c)=> (a+c) %mod ,0) };
Painting a Grid With Three Different Colors
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process. &nbsp; Example 1: Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"] Output: 2 Explanation: - In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack". - There is no string in startWords that can be used to obtain targetWords[1] = "act". Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it. - In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself. Example 2: Input: startWords = ["ab","a"], targetWords = ["abc","abcd"] Output: 1 Explanation: - In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc". - There is no string in startWords that can be used to obtain targetWords[1] = "abcd". &nbsp; Constraints: 1 &lt;= startWords.length, targetWords.length &lt;= 5 * 104 1 &lt;= startWords[i].length, targetWords[j].length &lt;= 26 Each string of startWords and targetWords consists of lowercase English letters only. No letter occurs more than once in any string of startWords or targetWords.
# Brute Force # O(S * T); S := len(startWors); T := len(targetWords) # TLE class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: cnt = 0 for target in targetWords: for start in startWords: if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1: cnt += 1 break return cnt # Sort + HashSet Lookup # O(S + T) Time class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: # Sort each start word and add it to a hash set startWords_sorted = set() # O(S*26*log(26)) for word in startWords: startWords_sorted.add("".join(sorted(list(word)))) # sort each target word and add it to a list # O(T*26*log(26)) targetWords_sorted = [] for word in targetWords: targetWords_sorted.append(sorted(list(word))) # for each sorted target word, we remove a single character and # check if the resulting word is in the startWords_sorted # if it is, we increment cnt and break the inner loop # otherwise we keep removing until we either find a hit or reach the # end of the string # O(T*26) = O(T) cnt = 0 for target in targetWords_sorted: for i in range(len(target)): w = target[:i] + target[i+1:] w = "".join(w) if w in startWords_sorted: cnt += 1 break return cnt # Using Bit Mask # O(S + T) Time # Similar algorithm as the one above, implemented using a bit mask to avoid the sorts class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: start_set = set() # O(S * 26) for word in startWords: m = 0 for ch in word: i = ord(ch) - ord('a') m |= (1 << i) start_set.add(m) # O(T * 2 * 26) cnt = 0 for word in targetWords: m = 0 for ch in word: i = ord(ch) - ord('a') m |= (1 << i) for ch in word: i = ord(ch) - ord('a') if m ^ (1 << i) in start_set: cnt += 1 break return cnt
class Solution { public int wordCount(String[] startWords, String[] targetWords) { int n = startWords.length; int count = 0; Set<String> set = new HashSet<>(); //1. store lexicographically sorted letters of startword in set for(String start: startWords){ char[] sAr = start.toCharArray(); Arrays.sort(sAr); set.add(new String(sAr)); } int m = targetWords.length; boolean ans = false; for(int i = 0; i < m; i++){ //2. sort lexicographically letters of targetword and store in new string s char[] tAr = targetWords[i].toCharArray(); Arrays.sort(tAr); int k = tAr.length; String s = String.valueOf(tAr); ans = false; for(int j = 0; j < k; j++){ //3. make a new string by omitting one letter from word and check if it is present in set than increase count value String str = s.substring(0,j) + s.substring(j+1); if(set.contains(str)){ count++; break; } } } return count; } }
class Solution { public: int wordCount(vector<string>& startWords, vector<string>& targetWords) { set<vector<int>> hash; for (int i = 0; i < startWords.size(); i++) { vector<int> counter(26, 0); for (char &x : startWords[i]) { counter[x - 'a']++; } hash.insert(counter); } int ans = 0; for (int i = 0; i < targetWords.size(); i++) { vector<int> counter(26, 0); for (char &x : targetWords[i]) { counter[x - 'a']++; } for (int j = 0; j < 26; j++) { if (counter[j] == 1) { counter[j] = 0; if (hash.find(counter) != hash.end()) { ans++; break; } counter[j] = 1; } } } return ans; } };
var wordCount = function(startWords, targetWords) { const startMap = {}; for(let word of startWords) { startMap[word.split('').sort().join('')] = true; } let ans = 0; for(let word of targetWords) { for(let i=0;i<word.length;i++) { let temp = (word.substring(0,i) + word.substring(i+1,word.length)).split('').sort().join(''); if(startMap[temp]) { ans++; break; } } } return ans; };
Count Words Obtained After Adding a Letter
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). &nbsp; Example 1: Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2] Example 3: Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step. &nbsp; Constraints: The number of nodes in the tree is in the range [1, 3000]. 1 &lt;= Node.val, target &lt;= 1000
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: if not root: return None root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) if not root.left and not root.right and root.val == target: return None return root
class Solution { public TreeNode removeLeafNodes(TreeNode root, int target) { if(root==null) return root; root.left = removeLeafNodes(root.left,target); root.right = removeLeafNodes(root.right,target); if(root.left == null && root.right == null && root.val == target) root = null; return root; } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* removeLeafNodes(TreeNode* root, int target) { if(root==NULL || root->left == NULL && root->right == NULL && root->val == target) return NULL; root->left = removeLeafNodes(root->left,target); root->right = removeLeafNodes(root->right,target); if(root->left == NULL && root->right == NULL && root->val == target) { return NULL; } return root; } };
var removeLeafNodes = function(root, target) { const parent = new TreeNode(-1, root, null); const traverse = (r = root, p = parent, child = -1) => { if(!r) return null; traverse(r.left, r, -1); traverse(r.right, r, 1); if(r.left == null && r.right == null && r.val == target) { if(child == -1) p.left = null; else p.right = null; } } traverse(); return parent.left; };
Delete Leaves With a Given Value
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally. &nbsp; Example 1: Input: piles = [[1,100,3],[7,8,9]], k = 2 Output: 101 Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101. Example 2: Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7 Output: 706 Explanation: The maximum total can be obtained if we choose all coins from the last pile. &nbsp; Constraints: n == piles.length 1 &lt;= n &lt;= 1000 1 &lt;= piles[i][j] &lt;= 105 1 &lt;= k &lt;= sum(piles[i].length) &lt;= 2000
class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: n = len(piles) prefixSum = [] for i in range(n): temp = [0] for j in range(len(piles[i])): temp.append(temp[-1] + piles[i][j]) prefixSum.append(temp) dp = [[0] * (k + 1) for _ in range(n)] for j in range(1, k + 1): if j < len(prefixSum[0]): dp[0][j] = prefixSum[0][j] for i in range(1, n): for j in range(1, k + 1): for l in range(len(prefixSum[i])): if l > j: break dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l]) return dp[n - 1][k]
class Solution { public int maxValueOfCoins(List<List<Integer>> piles, int k) { int n = piles.size(); int[][] ans = new int[n+1][2001]; Collections.sort(piles, (List<Integer> a, List<Integer> b) -> b.size() - a.size()); for(int i = 1; i <= k; i++) { for(int j = 1; j <= n; j++) { int sizeOfPile = piles.get(j-1).size(); List<Integer> pile = piles.get(j-1); int sum = 0; ans[j][i] = ans[j-1][i]; for(int l = 1; l <= Math.min(i, sizeOfPile); l++) { // Take K from this pile + remaining from previous piles sum += pile.get(l-1); int rem = i - l; ans[j][i] = Math.max(ans[j][i], sum + ans[j-1][rem]); } } } return ans[n][k]; } }
class Solution { public: int dp[1001][2001]; //Dp array For Memoization. int solve(vector<vector<int>>&v,int index,int coin) { if(index>=v.size()||coin==0) //Base Condition return 0; if(dp[index][coin]!=-1) //Check wheather It is Already Calculated Or not. return dp[index][coin]; /* Our 1st choice :- We not take any Coin from that pile*/ int ans=solve(v,index+1,coin); //Just Call function for next Pile. /*Otherwise we can take Coins from that Pile.*/ int loop=v[index].size()-1; int sum=0; for(int j=0;j<=min(coin-1,loop);j++) // { sum=sum+v[index][j]; ans=max(ans,sum+solve(v,index+1,coin-(j+1))); /*Aove we Pass coin-(j+1). Because till j'th index we have taken j+1 coin from that pile.*/ } return dp[index][coin]=ans; } int maxValueOfCoins(vector<vector<int>>& piles, int k) { memset(dp,-1,sizeof(dp)); return solve(piles,0,k); } };
/** * @param {number[][]} piles * @param {number} k * @return {number} */ var maxValueOfCoins = function(piles, k) { var n = piles.length; var cache = {}; var getMax = function(i, k) { if (i >= n || k <= 0) return 0; var key = i + ',' + k; if (cache[key] !== undefined) return cache[key]; var ans = getMax(i + 1, k); var cur = 0; for (var j = 0; j < piles[i].length && j < k; j++) { cur+=piles[i][j]; ans = Math.max(ans, cur + getMax(i + 1, k - j - 1)); } return cache[key] = ans; } return getMax(0, k); };
Maximum Value of K Coins From Piles
There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. &nbsp; Example 1: Input: row = [0,2,1,3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3,2,0,1] Output: 0 Explanation: All couples are already seated side by side. &nbsp; Constraints: 2n == row.length 2 &lt;= n &lt;= 30 n is even. 0 &lt;= row[i] &lt; 2n All the elements of row are unique.
class Solution: def minSwapsCouples(self, row: List[int]) -> int: count = 0 for i in range(0, len(row)-2, 2): idx = i+1 if(row[i]%2 == 0): n = (row[i] + 2)//2 newNo = 2*n - 1 else: n = (row[i] + 1) //2; newNo = 2*n - 2 for j in range(i, len(row)): if row[j] == newNo: idx = j break if idx != i+1: count += 1 row[idx], row[i+1] = row[i+1], row[idx] return count ```
class Solution { public int minSwapsCouples(int[] row) { // Union -Find pairs for 2 Map<Integer,Integer> parents=new HashMap<>(); int count=0; for(int i=0;i<row.length;i+=2){ int parent=Math.min(row[i],row[i+1]); int child=Math.max(row[i],row[i+1]); parents.put(parent,child); } for(int i=0;i<row.length;i+=2){ if((parents.containsKey(i) && parents.get(i)==(i+1)) || (parents.containsKey(i-1) && parents.get(i-1)==i)) continue; count+=1; int curChild=parents.get(i); int correctChildsChild = parents.get(i+1); parents.remove(i+1); // remove mapping of 1 in eg) //0,2 ; 1,3 parents.put(Math.min(curChild,correctChildsChild),Math.max(curChild,correctChildsChild)); // add mapping 2->7 , also place smaller number as parent for eg)//0,4 ; 1,3 parents.put(i,i+1); } return count; } }
class Solution { public: int minSwapsCouples(vector<int>& row) { int cnt=0,n=row.size(); // first of all making row element equal ex for [0,1],[2,3] --> [0,0] ,[2,2] for(auto &x : row){ if(x&1){ x--; } } for( int i=0; i<n; i+=2){ int ele=row[i]; int j=i+1; // for every num find location of equal one, while(j<n and row[j]!=ele) j++; if(j!=i+1){ // not in same couch then cnt++ , and swap swap(row[j], row[i+1]); cnt++; } } return cnt; } };
/** * @param {number[]} row * @return {number} */ var minSwapsCouples = function(row) { let currentPositions = []; for(let i=0;i<row.length;i++){ currentPositions[row[i]]=i; } let swapCount = 0; for(let j=0;j<row.length;j+=2) // Looping through the couches { let leftPartner = row[j]; let correctRightPartner = getPartner(leftPartner); if(row[j+1] !== correctRightPartner) { console.log("unhappy"); //Swap Positions of positions - Bring the Correct Right Partner in the Couch let tempValue = row[j+1]; row[j+1]=correctRightPartner; let tempPosition = currentPositions[correctRightPartner]; row[tempPosition]=tempValue; //Correct the Hash Table keeping the currentPositions of each Person. currentPositions[correctRightPartner]=j+1; currentPositions[tempValue]=tempPosition; swapCount+=1; } else { console.log("happy"); } } console.log("currentPositions", currentPositions,"Correct Row", row); return swapCount; }; function getPartner(x){ if(x%2 ===0) { return x+1; } else return x-1; }
Couples Holding Hands
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. &nbsp; Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. Example 3: Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths. &nbsp; Constraints: The number of nodes in the tree is in the range [0, 5000]. -1000 &lt;= Node.val &lt;= 1000 -1000 &lt;= targetSum &lt;= 1000
class Solution(object): def hasPathSum(self, root, targetSum): """ :type root: TreeNode :type targetSum: int :rtype: bool """ if not root: return False targetSum -= root.val if not root.left and not root.right: return not targetSum return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)
class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { if(root == null) return false; if(root.left == null && root.right == null) return root.val == targetSum; return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val); } }
class Solution { public: bool ans=false; int sum=0; void recur(TreeNode* root, int target){ if(root==NULL)return; sum+=root->val; recur(root->left,target); recur(root->right,target); if(root->left==NULL && root->right==NULL&&sum == target){ // !!Check only if it is a leaf node.... ans = true; return; } sum-=root->val; //backtracking return; } bool hasPathSum(TreeNode* root, int targetSum) { recur(root,targetSum); return ans; } };
var hasPathSum = function(root, targetSum) { return DFS(root, 0 , targetSum) }; const DFS = (curr, currentSum, targetSum) =>{ if(!curr) return false currentSum += curr.val; if(!curr.left && !curr.right) return currentSum === targetSum; return DFS(curr.left, currentSum, targetSum) || DFS(curr.right, currentSum, targetSum) }
Path Sum
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor. &nbsp; Example 1: Input: n = 3 Output: 3 Explanation: The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 2: Input: n = 4 Output: 3 Explanation: The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. Example 3: Input: n = 10 Output: 6 Explanation: The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side. &nbsp; Constraints: 1 &lt;= n &lt;= 109
class Solution: def minimumBoxes(self, n: int) -> int: r = 0 while (n_upper := r*(r+1)*(r+2)//6) < n: r += 1 m = r*(r+1)//2 for i in range(r, 0, -1): if (n_upper - i) < n: break n_upper -= i m -= 1 return m
class Solution { static final double ONE_THIRD = 1.0d / 3.0d; public int minimumBoxes(int n) { int k = findLargestTetrahedralNotGreaterThan(n); int used = tetrahedral(k); int floor = triangular(k); int unused = (n - used); if (unused == 0) { return floor; } int r = findSmallestTriangularNotLessThan(unused); return (floor + r); } private final int findLargestTetrahedralNotGreaterThan(int te) { int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD)); while (tetrahedral(a) > te) { a--; } return a; } private final int findSmallestTriangularNotLessThan(int t) { int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2))); while (triangular(a) < t) { a++; } return a; } private final int tetrahedral(int a) { return (int) ratio(product(a, a + 1, a + 2), 6); } private final int triangular(int a) { return (int) ratio(product(a, a + 1), 2); } private final long product(long... vals) { long product = 1L; for (long val : vals) { product *= val; } return product; } private final long ratio(long a, long b) { return (a / b); } }
class Solution { public: int minimumBoxes(int n) { // Find the biggest perfect pyramid uint32_t h = cbrt((long)6*n); uint32_t pyramid_box_num = h*(h+1)/2*(h+2)/3; // /6 is split to /2 and /3 to avoid long to save space if ( pyramid_box_num > n ){ h--; pyramid_box_num = h*(h+1)/2*(h+2)/3; // /6 is split to /2 and /3 to avoid long to save space } // Calculate how many floor-touching boxes in the pyramid int pyramid_base_num = (h)*(h+1)/2; // Get the number of boxes to be added to the perfect pyramid n -= pyramid_box_num; // Find how many floor-touching boxes are added int z = sqrt(2*n); int max_box_added = z*(z+1)/2; if ( max_box_added < n) z++; return pyramid_base_num+z; } };
var minimumBoxes = function(n) { //Binary search for the height of the biggest triangle I can create with n cubes available. let lo=1,hi=n,result let totalCubes=x=>x*(x+1)*(x+2)/6 //the total cubes of a triangle with height x while(lo+1<hi){ let mid=lo+hi>>1 if(totalCubes(mid)<=n) lo=mid else hi=mid } let f=(x)=>Math.floor(Math.sqrt(2*x)+1/2)// the i-th element of the sequence 1,2,2,3,3,3,4,4,4,4,5,... result=(lo)*(lo+1)/2// the base of the largest complete triangle 1+2+3+..+H n-=totalCubes(lo) //remove the cubes of the complete triangle return result+f(n) // the base of the largest+ the extra floor cubes };
Building Boxes
Given the root of a binary tree, return the sum of values of its deepest leaves. &nbsp; Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. 1 &lt;= Node.val &lt;= 100
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): """ THOUGHT PROCESS: 1) find the height of the tree, this way we would know how deep we need to go. 2) we need a counter to check how deep we are and this is not available in deepestLeavesSum so we create a new function deepestLeave. 3) now we go in depth, if we are at bottom, we return the value, we recursively visit both left and right nodes. """ def height(self, root): if root is None: return 0 else: x, y = 1, 1 if root.left: x = self.height(root.left)+1 if root.right: y = self.height(root.right)+1 return max(x, y) def deepestLeave(self, root, depth): if root is None: return 0 if root.left is None and root.right is None: if depth == 1: return root.val return self.deepestLeave(root.left, depth-1) + self.deepestLeave(root.right, depth-1) def deepestLeavesSum(self, root): """ :type root: TreeNode :rtype: int """ return self.deepestLeave(root, self.height(root))
class Solution { public int height(TreeNode root) { if(root == null) return 0; return Math.max(height(root.left), height(root.right)) + 1; } public int deepestLeavesSum(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val; Queue<TreeNode> q = new LinkedList<>(); q.add(root); q.add(null); int hght = height(root); int sum = 0; while(q.size()>0 && q.peek()!=null) { TreeNode temp = q.remove(); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); if(q.peek() == null) { q.remove(); q.add(null); hght--; } if(hght == 1) { while(q.size()>0 && q.peek()!=null) { sum+=q.remove().val; } } } return sum; } }
** #Vote if u like ❤️** class Solution { public: void fun(TreeNode *root , int l , map<int , vector<int>> &m) { if(root == NULL) return; //If root is NULL it will return m[l].push_back(root -> val); //With level as key inserting the value to the vector fun(root -> left, l + 1, m); // passing the left with level + 1 fun(root -> right, l + 1 , m); // passing right with level + 1 } int deepestLeavesSum(TreeNode* root) { map<int , vector<int>> m; // Map with key as level and value of vector for storing the values fun(root , 0 , m); // A void fun with map and level as 0 auto itr = m.rbegin(); //Hence we need the leaves node the nodes are present in last level int sum = 0; // Sum Variable for(int i = 0; i < itr-> second.size(); i++) {sum += itr -> second[i];} return sum; } }; -Yash:)
var deepestLeavesSum = function(root) { let queue = []; queue.push([root, 0]); let sum = 0; let curLevel = 0 let i = 0; while(queue.length-i > 0) { let [node, level] = queue[i]; queue[i] = null; i++; if(level > curLevel) { sum = 0; curLevel = level; } sum += node.val; if(node.left != null) queue.push([node.left, level+1]); if(node.right != null) queue.push([node.right, level+1]); } return sum; //time: o(n) //space: o(n) };
Deepest Leaves Sum
Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum&nbsp;index such that j &gt; i and prices[j] &lt;= prices[i], otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. &nbsp; Example 1: Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Explanation:&nbsp; For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.&nbsp; For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.&nbsp; For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.&nbsp; For items 3 and 4 you will not receive any discount at all. Example 2: Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Explanation: In this case, for all items, you will not receive any discount at all. Example 3: Input: prices = [10,1,1,6] Output: [9,0,1,6] &nbsp; Constraints: 1 &lt;= prices.length &lt;= 500 1 &lt;= prices[i] &lt;= 10^3
class Solution: def finalPrices(self, prices: List[int]) -> List[int]: ## RC ## ## APPROACH : STACK ## ## LOGIC ## ## 1. Use Monotonic Increasing Stack Concept ## 2. Main idea is to find the Next Smaller Element in O(N) using #1 stack = [] for i, num in enumerate(prices): while(stack and prices[stack[-1]] >= num): popIndex = stack.pop() prices[popIndex] -= num stack.append(i) return prices
class Solution { public int[] finalPrices(int[] prices) { for(int i = 0; i < prices.length; i++){ for(int j = i + 1; j < prices.length; j++){ if(j > i && prices[j] <= prices[i]){ prices[i] -= prices[j]; break; } } } return prices; } }
class Solution { public: vector<int> finalPrices(vector<int>& prices) { vector<int>sk; for(int i=0;i<prices.size();i++){ int discount=prices[i]; for(int j=i+1;j<prices.size();j++){ if(prices[i]>=prices[j]){ discount=prices[i]-prices[j]; break; } } sk.push_back(discount); } return sk; } };
var finalPrices = function(prices) { let adjPrices = []; while(prices.length) { let currentPrice = prices[0]; // Remove first price in original array // Since we're looking for a price less than or equal to prices.shift(); let lowerPrice = prices.find((a) => a <= currentPrice); adjPrices.push(lowerPrice ? currentPrice - lowerPrice : currentPrice); } return adjPrices; };
Final Prices With a Special Discount in a Shop
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). &nbsp; Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. &nbsp; Constraints: nums1.length == m nums2.length == n 0 &lt;= m &lt;= 1000 0 &lt;= n &lt;= 1000 1 &lt;= m + n &lt;= 2000 -106 &lt;= nums1[i], nums2[i] &lt;= 106
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): lis = nums1 + nums2 lis.sort() hi = len(lis) print(5/2) if hi%2 == 0: if (lis[hi/2] + lis[hi/2-1])%2 == 0: return (lis[hi/2] + lis[hi/2-1] )/2 return (lis[hi/2] + lis[hi/2-1])/2 + 0.5 else: return lis[hi//2]
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0; int i = 0; int j = 0; int k = 0; int nums[] = new int[nums1.length + nums2.length]; if(nums1.length !=0 && nums2.length != 0){ while(i < nums1.length && j < nums2.length){ if(nums1[i] < nums2[j]){ nums[k] = nums1[i]; i++; k++; }else{ nums[k] = nums2[j]; j++; k++; } } while(i < nums1.length){ nums[k] = nums1[i]; i++; k++; } while(j < nums2.length){ nums[k] = nums2[j]; j++; k++; } } if(nums1.length==0){ for(int h: nums2){ nums[k] = h; k++; } } if(nums2.length==0){ for(int d : nums1){ nums[k] = d; k++; } } int mid = (nums.length / 2); if (nums.length % 2 == 0) { return ((double) nums[mid] + (double) nums[mid - 1]) / 2.0; } else { return nums[mid]; } } }
class Solution { public: //Merging two arrays :- vector<int> mergeSortedArrays(vector<int>&arr1,vector<int>&arr2){ int n = arr1.size(); int m = arr2.size(); vector<int> ans(m+n); int i = 0; int j = 0; int mainIndex = 0; while( i < n && j < m ){ if(arr1[i] <= arr2[j])ans[mainIndex++] = arr1[i++]; else ans[mainIndex++] = arr2[j++]; } while( i < n){ ans[mainIndex++] = arr1[i++]; } while( j < m){ ans[mainIndex++] = arr2[j++]; } return ans; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> ans = mergeSortedArrays(nums1,nums2); float median = 0; int n = ans.size()-1; if(n%2 != 0) median=(ans[n/2]+ans[(n/2)+1])/2.0; else median=ans[n/2]; return median; } };
var findMedianSortedArrays = function(nums1, nums2) { let nums3 = nums1.concat(nums2).sort((a,b) => a - b) if(nums3.length % 2 !== 0) return nums3[(nums3.length-1)/2] return (nums3[nums3.length/2] + nums3[nums3.length/2 - 1])/2 };
Median of Two Sorted Arrays
You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed. &nbsp; Example 1: Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" Output: [ ["mobile","moneypot","monitor"], ["mobile","moneypot","monitor"], ["mouse","mousepad"], ["mouse","mousepad"], ["mouse","mousepad"] ] Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"] After typing m and mo all products match and we show user ["mobile","moneypot","monitor"] After typing mou, mous and mouse the system suggests ["mouse","mousepad"] Example 2: Input: products = ["havana"], searchWord = "havana" Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] Example 3: Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags" Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]] &nbsp; Constraints: 1 &lt;= products.length &lt;= 1000 1 &lt;= products[i].length &lt;= 3000 1 &lt;= sum(products[i].length) &lt;= 2 * 104 All the strings of products are unique. products[i] consists of lowercase English letters. 1 &lt;= searchWord.length &lt;= 1000 searchWord consists of lowercase English letters.
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: sorted_products = sorted(products) res = [] prefix = '' for letter in searchWord: prefix += letter words = [] for product in sorted_products: if len(words) == 3: break if product.startswith(prefix): words.append(product) res.append(words) return res
class Solution { public List<List<String>> suggestedProducts(String[] products, String searchWord) { PriorityQueue<String> pq= new PriorityQueue<String>(); List<List<String>> res= new LinkedList<List<String>>(); List<String> segment= new LinkedList<String>(); for(int i=0;i<products.length;i++) pq.offer(products[i]); for(int j=0;j<searchWord.length();j++) { segment= new LinkedList<String>(); pq= reduce(pq,searchWord.substring(0,j+1)); PriorityQueue<String> pri= new PriorityQueue<>(pq); int p=0; while(p<pq.size()&&p<3) { segment.add(pri.poll()); p++; } res.add(segment); } return res; } public PriorityQueue<String> reduce(PriorityQueue<String> pr, String filter) { PriorityQueue<String> p= new PriorityQueue<>(); String s=""; while(!pr.isEmpty()) { s=pr.poll(); if(s.startsWith(filter)) p.add(s); } return p; } }
class Solution { public: vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) { map<int, vector<string>> m; vector<vector<string>> res; for (int i = 0; i < products.size(); i++) { int j = 0; while (products[i][j] == searchWord[j] && j < searchWord.size()) { if (m.count(j) == 0) { vector<string> v; v.push_back(products[i]); m.insert(make_pair(j, v)); } else { m[j].push_back(products[i]); } j++; } } for (int i = 0; i < searchWord.size(); i++) { if (i < m.size()) { sort(m[i].begin(), m[i].end()); int a; if (3 <= m[i].size()) { a = 3; } else { a = m[i].size(); } m[i].resize(a); res.push_back(m[i]); } else { res.push_back({}); } } return res; } };
function TrieNode(key) { this.key = key this.parent = null this.children = {} this.end = false this.getWord = function() { let output = [] let node = this while(node !== null) { output.unshift(node.key) node = node.parent } return output.join('') } } function Trie() { this.root = new TrieNode(null) this.insert = function(word) { let node = this.root for (let i = 0; i < word.length; i++) { if (!node.children[word[i]]) { node.children[word[i]] = new TrieNode(word[i]) node.children[word[i]].parent = node } node = node.children[word[i]] if (i === word.length - 1) { node.end = true } } } this.findAllWords = function (node, arr) { if (node.end) { arr.unshift(node.getWord()); } for (let child in node.children) { this.findAllWords(node.children[child], arr); } } this.find = function(prefix) { let node = this.root let output = [] for(let i = 0; i < prefix.length; i++) { if (node.children[prefix[i]]) { node = node.children[prefix[i]] } else { return output } } this.findAllWords(node, output) output.sort() return output.slice(0, 3) } this.search = function(word) { let node = this.root let output = [] for (let i = 0; i < word.length; i++) { output.push(this.find(word.substring(0, i + 1))) } return output } } /** * @param {string[]} products * @param {string} searchWord * @return {string[][]} */ var suggestedProducts = function(products, searchWord) { let trie = new Trie() for (let product of products) { trie.insert(product) } return trie.search(searchWord) };
Search Suggestions System
A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. &nbsp; Example 1: Input: sentence = "thequickbrownfoxjumpsoverthelazydog" Output: true Explanation: sentence contains at least one of every letter of the English alphabet. Example 2: Input: sentence = "leetcode" Output: false &nbsp; Constraints: 1 &lt;= sentence.length &lt;= 1000 sentence consists of lowercase English letters.
class Solution: def checkIfPangram(self, sentence: str) -> bool: return len(set(sentence))==26
class Solution { public boolean checkIfPangram(String sentence) { int seen = 0; for(char c : sentence.toCharArray()) { int ci = c - 'a'; seen = seen | (1 << ci); } return seen == ((1 << 26) - 1); } }
class Solution { public: bool checkIfPangram(string sentence) { vector<int> v(26,0); for(auto x:sentence) { v[x-'a'] = 1; } return accumulate(begin(v),end(v),0) == 26; } };
var checkIfPangram = function(sentence) { return new Set(sentence.split("")).size == 26; };
Check if the Sentence Is Pangram
On an alphabet board, we start at position (0, 0), corresponding to character&nbsp;board[0][0]. Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. We may make the following moves: 'U' moves our position up one row, if the position exists on the board; 'D' moves our position down one row, if the position exists on the board; 'L' moves our position left one column, if the position exists on the board; 'R' moves our position right one column, if the position exists on the board; '!'&nbsp;adds the character board[r][c] at our current position (r, c)&nbsp;to the&nbsp;answer. (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target&nbsp;in the minimum number of moves.&nbsp; You may return any path that does so. &nbsp; Example 1: Input: target = "leet" Output: "DDR!UURRR!!DDD!" Example 2: Input: target = "code" Output: "RR!DDRR!UUL!R!" &nbsp; Constraints: 1 &lt;= target.length &lt;= 100 target consists only of English lowercase letters.
class Solution: def alphabetBoardPath(self, target: str) -> str: def shortestPath(r,c,tr,tc): path = "" pr = r while r > tr: path += 'U' r -= 1 while r < tr: path += 'D' r += 1 if tr == 5 and pr != tr: path = path[:len(path) - 1] while c > tc: path += 'L' c -= 1 while c < tc: path += 'R' c += 1 if tr == 5 and pr != tr: path = path + 'D' return path table = ['abcde','fghij','klmno','pqrst','uvwxy','z'] r,c = 0,0 ans = "" for character in target: t_row = None for i,word in enumerate(table): if character in word: t_row = i break t_col = table[i].index(character) ans += shortestPath(r,c,t_row,t_col) + '!' r,c = t_row,t_col return ans
class Solution { public String alphabetBoardPath(String target) { int x = 0, y = 0; StringBuilder sb = new StringBuilder(); for(int i = 0; i < target.length(); i++){ char ch = target.charAt(i); int x1 = (ch - 'a') / 5; int y1 = (ch - 'a') % 5; while(x1 < x) {x--; sb.append('U');} while(y1 > y) {y++; sb.append('R');} while(y1 < y) {y--; sb.append('L');} while(x1 > x) {x++; sb.append('D');} sb.append('!'); } return sb.toString(); } }
class Solution { public: string alphabetBoardPath(string target) { string ans = ""; int prevRow = 0; int prevCol = 0; int curRow = 0; int curCol = 0; for(int i = 0; i < target.length(); i++){ prevCol = curCol; prevRow = curRow; curRow = (target[i] - 'a')/5; curCol = (target[i] - 'a')%5; if(curRow == 5 and abs(curCol - prevCol) > 0){ curRow--; } if(curRow - prevRow > 0){ ans += string((curRow - prevRow), 'D'); }else{ ans += string((prevRow - curRow), 'U'); } if(curCol - prevCol > 0){ ans += string((curCol - prevCol), 'R'); }else{ ans += string((prevCol - curCol), 'L'); } if(((target[i] - 'a')/5) == 5 and abs(curCol - prevCol) > 0){ ans += 'D'; curRow++; } ans += '!'; } return ans; } };
var alphabetBoardPath = function(target) { var result = ""; var list = "abcdefghijklmnopqrstuvwxyz"; var curr = 0; for(i=0;i<target.length;i++){ let next = list.indexOf(target[i]); if(next!==curr){ if(curr===25) curr-=5, result+="U"; if(next%5!==curr%5){ diff = next%5-curr%5; if(diff>0) curr+=diff, result+="R".repeat(diff); else curr+=diff, result+="L".repeat(-diff); } diff = (next-curr)/5; if(diff>0) curr+=diff*5, result+="D".repeat(diff); else curr+=diff*5, result+="U".repeat(-diff); } result+='!'; } return result; };
Alphabet Board Path
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: 1 &lt;= pivot &lt; n nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged. Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element. &nbsp; Example 1: Input: nums = [2,-1,2], k = 3 Output: 1 Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2]. There is one way to partition the array: - For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2. Example 2: Input: nums = [0,0,0], k = 1 Output: 2 Explanation: The optimal approach is to leave the array unchanged. There are two ways to partition the array: - For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0. - For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0. Example 3: Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 Output: 4 Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14]. There are four ways to partition the array. &nbsp; Constraints: n == nums.length 2 &lt;= n &lt;= 105 -105 &lt;= k, nums[i] &lt;= 105
class Solution: def waysToPartition(self, nums: List[int], k: int) -> int: prefix_sums = list(accumulate(nums)) total_sum = prefix_sums[-1] best = 0 if total_sum % 2 == 0: best = prefix_sums[:-1].count(total_sum // 2) # If no change after_counts = Counter(total_sum - 2 * prefix_sum for prefix_sum in prefix_sums[:-1]) before_counts = Counter() best = max(best, after_counts[k - nums[0]]) # If we change first num for prefix, x in zip(prefix_sums, nums[1:]): gap = total_sum - 2 * prefix after_counts[gap] -= 1 before_counts[gap] += 1 best = max(best, after_counts[k - x] + before_counts[x - k]) return best
class Solution { //time - O(n), space - O(n) public int waysToPartition(int[] nums, int k) { int n = nums.length; int[] pref = new int[n]; pref[0] = nums[0]; Map<Integer, Integer> count = new HashMap<>(); //contribution of prefixes without changing count.put(pref[0], 1); for (int i = 1; i < n - 1; i++){ pref[i] += pref[i - 1] + nums[i]; count.put(pref[i], count.getOrDefault(pref[i], 0) + 1); } pref[n - 1] += pref[n - 2] + nums[n - 1]; //last step doesn't add into 'count' map, because we're trying to find at least two parts. int sum = pref[n - 1]; int max = 0; if (sum % 2 == 0) max = count.getOrDefault(sum / 2, 0); //max without changing Map<Integer, Integer> countPrev = new HashMap<>(); //contribution of prefixes before current step for (int i = 0; i < n; i++){ int diff = k - nums[i]; int changedSum = sum + diff; if (changedSum % 2 == 0) max = Math.max(max, count.getOrDefault(changedSum / 2 - diff, 0) + countPrev.getOrDefault(changedSum / 2, 0)); count.put(pref[i], count.getOrDefault(pref[i], 0) - 1); countPrev.put(pref[i], countPrev.getOrDefault(pref[i], 0) + 1); } return max; } }
class Solution { public: int waysToPartition(vector<int>& nums, int k) { unordered_map<long long int,int> left; unordered_map<long long int,int> right; long long int sum=accumulate(nums.begin(),nums.end(),0L); long long int leftSum=0; int n=nums.size(); for(int i=0;i<n-1;i++){ leftSum+=nums[i]; long long int rightSum=sum-leftSum; long long int difference=leftSum-rightSum; right[difference]++; //storing difference count in right, since no difference exist in left } int res=right[0]; // Point Zero difference are the partition points leftSum=0; for(int i=0;i<n;i++){ long long int D=k-nums[i]; res=max(res,right[-D]+left[D]); // We can run a few test cases and see that if we replace arr[i] by k, the difference D, the left side including i,each element decreases by D while the right Side each element increases by D, so we find -D on right Side... WHY?? if right side is increasing by D, we need to find -D since this will result in -D+D=0, which are our partition points, since point 0 signifies a partition where leftSum==rightSum, similarly, left side decreases by D, so we find +D on left since this will result in zero as well. leftSum+=nums[i]; long long int rightSum=sum-leftSum; left[leftSum-rightSum]++; //Now since we are moving our i forward, we are gonna change the next i point, so we are placing leftSum-RightSum on left side right[leftSum-rightSum]--; // From right we are gonna decrease it and transfer to left side if(right[leftSum-rightSum]==0){ right.erase(leftSum-rightSum); } } return res; } };
/** * @param {number[]} nums * @param {number} k * @return {number} */ var waysToPartition = function(nums, k) { let totalSum=nums.reduce((acc, curr) => acc+curr) let left=0; let rightDiff={} let leftDiff={} for(let i=0; i<nums.length-1; i++) { left+=nums[i] const right=totalSum-left if(rightDiff[left-right]) rightDiff[left-right]++ else rightDiff[left-right]=1 } let maxPartition=rightDiff[0] ? rightDiff[0] : 0 left=0 for(let i=0; i<nums.length; i++) { left+=nums[i] let diff=k-nums[i] const right=totalSum-left let leftVal=leftDiff[`${diff}`] ? leftDiff[`${diff}`] : 0 let rightVal=rightDiff[`${-diff}`] ? rightDiff[`${-diff}`] : 0 maxPartition=Math.max(maxPartition, leftVal+rightVal) if(leftDiff[left-right]) leftDiff[left-right]++ else leftDiff[left-right]=1 rightDiff[left-right]-- } return maxPartition }; ```
Maximum Number of Ways to Partition an Array
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values&nbsp;along the path equals&nbsp;targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). &nbsp; Example 1: Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: 3 &nbsp; Constraints: The number of nodes in the tree is in the range [0, 1000]. -109 &lt;= Node.val &lt;= 109 -1000 &lt;= targetSum &lt;= 1000
class Solution: def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: def util(node: TreeNode, sum_array) -> int: t = [e - node.val for e in sum_array] zeroes = t.count(0) if node.left is None and node.right is None: return zeroes ansl, ansr = 0, 0 if node.left: ansl = util(node.left, t + [targetSum]) if node.right: ansr = util(node.right, t + [targetSum]) return ansl + ansr + zeroes return util(root, [targetSum]) if root is not None else 0
class Solution { public int pathSum(TreeNode root, int targetSum) { HashMap<Long, Integer> hm = new HashMap<>(); //hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum int res = solve(hm, root, targetSum, 0); return res; } public int solve(HashMap<Long, Integer> hm, TreeNode node, long tgt, long c_sum) { if(node == null) return 0; c_sum += node.val; int res = 0; if(c_sum == tgt) //--> either this condition or the above commented condition. res++; if(hm.containsKey(c_sum-tgt)){ res += hm.get(c_sum-tgt); } hm.put(c_sum, hm.getOrDefault(c_sum,0)+1); int left = solve(hm, node.left, tgt, c_sum); int right = solve(hm, node.right, tgt, c_sum); res += (left+right); hm.put(c_sum, hm.getOrDefault(c_sum,0)-1); //remove the calculated cumulative sum return res; } }
class Solution { public: int ans = 0,t; void dfs(unordered_map<long long,int> &curr,TreeNode* node,long long sm){ if(!node){ return; } sm += (long long) node->val; ans += curr[sm-t]; curr[sm]++; dfs(curr,node->left,sm); dfs(curr,node->right,sm); curr[sm]--; } int pathSum(TreeNode* root, int targetSum) { if(!root){ return 0; } t = targetSum; unordered_map<long long,int> curr; curr[0] = 1; long long sm = 0; dfs(curr,root,sm); return ans; } };
var pathSum = function(root, targetSum) { let count = 0; let hasSum = (node, target) => { //helper function, calculates number of paths having sum equal to target starting from given node if(node===null){// base case return; } if(node.val===target){// if at any point path sum meets the requirement count++; } //recursive call hasSum(node.left, target-node.val); hasSum(node.right, target-node.val); } let dfs = (node) => {//dfs on every node and find sum equal to target starting from every node if(node===null) return; dfs(node.left); dfs(node.right); hasSum(node,targetSum);// find sum of path starting on this point } dfs(root); return count; };
Path Sum III
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n. &nbsp; Example 1: Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". Example 2: Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1. Example 3: Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab" &nbsp; Constraints: 1 &lt;= n &lt;= 10 1 &lt;= k &lt;= 100
class Solution: def getHappyString(self, n: int, k: int) -> str: ans = [] letters = ['a','b','c'] def happystr(n,prev,temp): if n==0: ans.append("".join(temp)) return for l in letters: if l!=prev: happystr(n-1,l,temp+[l]) happystr(n,"",[]) if len(ans)<k: return "" return ans[k-1]
class Solution { public String getHappyString(int n, int k) { List<String> innerList = new ArrayList<>(); getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList); if (innerList.size() < k) return ""; return innerList.get(k - 1); } public void getHappyStringUtil(int n, int k, char[] letter, StringBuilder tempString, List<String> innerList) { // Base case if (tempString.length() == n) { innerList.add(tempString.toString()); return; } // Recursive call for (int i = 0; i < 3; i++) { if (tempString.length() > 0 && tempString.charAt(tempString.length() - 1) == letter[i]) continue; tempString.append(letter[i]); getHappyStringUtil(n, k, letter, tempString, innerList); tempString.deleteCharAt(tempString.length() - 1); } } }
class Solution { private: void happy(string s, vector<char> &v, int n, vector<string> &ans){ if(s.size() == n){ ans.push_back(s); return; } for(int i=0; i<3; i++){ if(s.back() != v[i]){ s.push_back(v[i]); happy(s,v,n,ans); s.pop_back(); } } } public: string getHappyString(int n, int k) { vector<char> v = {'a', 'b', 'c'}; vector<string> ans; string s = ""; happy(s,v,n,ans); if(ans.size() < k){ return ""; } else{ return ans[k-1]; } } };
var getHappyString = function(n, k) { const arr = ['a','b','c'], finalArr = ['a','b','c']; let chr = '', str = ''; if(finalArr[finalArr.length-1].length === n && finalArr[0].length === n ) { return finalArr[k-1] && finalArr[k-1].length === n ? finalArr[k-1] : ''; } for(; finalArr.length < k || finalArr[0].length <= n;) { str = finalArr.shift(); for(let index2 = 0; index2 < 3; index2++){ chr = str[str.length-1]; if(chr !== arr[index2]) { finalArr.push(str+arr[index2]); } } if(finalArr[finalArr.length-1].length === n && finalArr[0].length === n ) break; } return finalArr[k-1] ? finalArr[k-1] : ''; };
The k-th Lexicographical String of All Happy Strings of Length n
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) In addition, the spell checker operates under the following precedence rules: When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. When the query matches a word up to capitlization, you should return the first such match in the wordlist. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. If the query has no matches in the wordlist, you should return the empty string. Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. &nbsp; Example 1: Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] Example 2: Input: wordlist = ["yellow"], queries = ["YellOw"] Output: ["yellow"] &nbsp; Constraints: 1 &lt;= wordlist.length, queries.length &lt;= 5000 1 &lt;= wordlist[i].length, queries[i].length &lt;= 7 wordlist[i] and queries[i] consist only of only English letters.
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: n = len(wordlist) d = {} sd = {} vd = {} cd = {} for i in range(n): d[wordlist[i]] = i s = wordlist[i].lower() if s not in sd:sd[s] = i m = len(wordlist[i]) tmp = [] emp = "" for j in range(m): if wordlist[i][j] in 'aeiouAEIOU': tmp.append(j) else:emp+=wordlist[i][j].lower() cd[i] = emp vd[i] = tmp ans = [] for word in queries: word_lower = word.lower() if word in d: ans.append(word) continue elif word_lower in sd: ans.append(wordlist[sd[word_lower]]) continue else: vow_word = [] con_word = "" m = len(word) for i in range(m): if word[i] in 'aeiouAEIOU' : vow_word.append(i) else: con_word += word[i].lower() if vow_word == []: ans.append("") continue flag = False for i in range(n): vow_tmp = vd[i] con_tmp = cd[i] if vow_tmp == vow_word and con_tmp == con_word: ans.append(wordlist[i]) flag = True break if flag == True:continue ans.append("") return ans
class Solution { public String[] spellchecker(String[] wordlist, String[] queries) { String[] ans = new String[queries.length]; Map<String, String>[] map = new HashMap[3]; Arrays.setAll(map, o -> new HashMap<>()); String pattern = "[aeiou]"; for (String w : wordlist){ String lo = w.toLowerCase(); map[0].put(w, ""); map[1].putIfAbsent(lo, w); map[2].putIfAbsent(lo.replaceAll(pattern, "."), map[1].getOrDefault(w, w)); } int i = 0; for (String q : queries){ String lo = q.toLowerCase(); String re = lo.replaceAll(pattern, "."); if (map[0].containsKey(q)){ ans[i] = q; }else if (map[1].containsKey(lo)){ ans[i] = map[1].get(lo); }else if (map[2].containsKey(re)){ ans[i] = map[2].get(re); }else{ ans[i] = ""; } i++; } return ans; } }
class Solution { public: vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) { unordered_map<string, vector<int>> umap; // step 1: add info in umap; for(int curr = 0; curr < wordlist.size(); curr++){ // case 1: add same; umap[wordlist[curr]].push_back({curr}); // notice that the lowercase may appear; // case 2: add lowercase; string tmp = wordlist[curr]; transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); if(umap.find(tmp) == umap.end() && tmp != wordlist[curr]) umap[tmp].push_back({curr}); // case 3: add vowel errors; // convert aeiou to _; for(int c_index = 0; c_index < tmp.size(); c_index++){ char c = tmp[c_index]; if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_'; } if(umap.find(tmp) == umap.end()) umap[tmp].push_back({curr}); } // step 2: convert queries; for(int curr = 0; curr < queries.size(); curr++){ string tmp = queries[curr]; transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); // case 1: check same; if(umap.find(queries[curr]) != umap.end()){ queries[curr] = (umap[queries[curr]].size() == 1) ? wordlist[umap[queries[curr]][0]] : wordlist[umap[queries[curr]][1]]; continue; } // case 2: check lowercase; if(umap.find(tmp) != umap.end() && tmp != queries[curr]){ queries[curr] = wordlist[umap[tmp][0]]; continue; } // case 3: check vowel errors; // convert aeiou to _; for(int c_index = 0; c_index < tmp.size(); c_index++){ char c = tmp[c_index]; if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_'; } if(umap.find(tmp) != umap.end()){ queries[curr] = wordlist[umap[tmp][0]]; continue; } // case 4: not found; queries[curr] = ""; } return queries; } }; // 1. When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. // 2. When the query matches a word up to capitlization, you should return the first such match in the wordlist. // 3. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. // 4. If the query has no matches in the wordlist, you should return the empty string.
var spellchecker = function(wordlist, queries) { const baseList = new Set(wordlist.reverse()); const loweredList = wordlist.reduce((map, word) => (map[normalize(word)] = word, map), {}); const replacedList = wordlist.reduce((map, word) => (map[repVowels(word)] = word, map), {}); return queries.map(word => ( baseList.has(word) && word || loweredList[normalize(word)] || replacedList[repVowels(word)] || '' )); }; var normalize = function(word) { return word.toLowerCase() }; var repVowels = function(word) { return normalize(word).replace(/[eiou]/g, 'a') };
Vowel Spellchecker
There are n bulbs that are initially off. You first turn on all the bulbs, then&nbsp;you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. &nbsp; Example 1: Input: n = 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After the first round, the three bulbs are [on, on, on]. After the second round, the three bulbs are [on, off, on]. After the third round, the three bulbs are [on, off, off]. So you should return 1 because there is only one bulb is on. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 1 &nbsp; Constraints: 0 &lt;= n &lt;= 109
class Solution: def bulbSwitch(self, n: int) -> int: return int(sqrt(n))
class Solution { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } }
class Solution { public: int bulbSwitch(int n) { return sqrt(n); } };
var bulbSwitch = function(n) { return Math.floor(Math.sqrt(n)); };
Bulb Switcher
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits. &nbsp; Example 1: Input: time = "2?:?0" Output: "23:50" Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50. Example 2: Input: time = "0?:3?" Output: "09:39" Example 3: Input: time = "1?:22" Output: "19:22" &nbsp; Constraints: time is in the format hh:mm. It is guaranteed that you can produce a valid time from the given string.
class Solution: def maximumTime(self, time: str) -> str: memo = {"0":"9", "1":"9", "?":"3", "2":"3"} answer = "" for idx, val in enumerate(time): if val == "?": if idx == 0: if time[idx+1] == "?": answer += "2" else: if int(time[idx+1]) >= 4: answer += "1" else: answer += "2" if idx == 1: answer += memo[time[idx-1]] if idx == 3: answer += "5" if idx == 4: answer += "9" else: answer += val return answer
class Solution { public String maximumTime(String time) { char[] times = time.toCharArray(); //for times[0] //if both characters of hour is ?, then hour is 23 then times[0] should be '2'("??:3?)". //if 2nd character of hour is <= 3, then hour can be in 20s then times[0] should be '2'. //if 2nd character of hour is >3, then hour can only be in 10s then times[0] should be '1'. if(times[0]=='?') times[0]= (times[1]<='3' || times[1]=='?') ? '2' : '1'; //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then times[1] should be '9'. //if 1st character of hour is 2, then hour can be 23 then times[1] should be '3'. if(times[1]=='?') times[1]= times[0]=='2' ? '3' : '9'; //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so times[3] is always '5'. if(times[3]=='?') times[3]='5'; //if 2nd character of minute is ?, then times[4] is '9'. if(times[4]=='?') times[4]='9'; return new String(times); } }
class Solution { public: string maximumTime(string time) { //for time[0] //if both characters of hour is ?, then hour is 23 then time[0] should be '2'("??:3?)". //if 2nd character of hour is <= 3, then hour can be in 20s then time[0] should be '2'. //if 2nd character of hour is >3, then hour can only be in 10s then time[0] should be '1'. if(time[0]=='?') time[0]= (time[1]<='3' || time[1]=='?') ? '2' : '1'; //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then time[1] should be '9'. //if 1st character of hour is 2, then hour can be 23 then time[1] should be '3'. if(time[1]=='?') time[1]= time[0]=='2' ? '3' : '9'; //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so time[3] is always '5'. if(time[3]=='?') time[3]='5'; //if 2nd character of minute is ?, then time[4] is '9'. if(time[4]=='?') time[4]='9'; return time; } };
var maximumTime = function(time) { time = time.split('') if (time[0] === "?") time[0] = time[1] > 3 ? "1" : "2" if (time[1] === "?") time[1] = time[0] > 1 ? "3" : "9" if (time[3] === "?") time[3] = "5" if (time[4] === "?") time[4] = "9" return time.join('') };
Latest Time by Replacing Hidden Digits
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1. &nbsp; Example 1: Input: expression = "-1/2+1/2" Output: "0/1" Example 2: Input: expression = "-1/2+1/2+1/3" Output: "1/3" Example 3: Input: expression = "1/3-1/2" Output: "-1/6" &nbsp; Constraints: The input string only contains '0' to '9', '/', '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1, 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
""" approach: first replace - with +- in the string so that implementation gets a little easy """ class Solution: def fractionAddition(self, expression: str) -> str: expression = expression.replace('-', '+-') parts = [item for item in expression.split('+') if item != ''] numes, denoms, denom_set, lcm = [], [], set(), 1 def get_lcm(a, b): if a == 1: return b if b == 1: return a if a < b: if b % a == 0: return a * get_lcm(1, b/a) else: return a * get_lcm(1, b) else: if a % b == 0: return b * get_lcm(a/b, 1) else: return b * get_lcm(a, 1) for part in parts: num, den = part.split('/') numes.append(int(num)) denoms.append(int(den)) lcm = get_lcm(lcm, int(den)) result = 0 for num, den in zip(numes, denoms): result +=num * int(lcm/den) def get_gcd(a, b): if a == 0: return b if b == 0: return a if a == b: return a elif a < b: return get_gcd(a, b-a) else: return get_gcd(a-b, b) gcd = get_gcd(abs(result), lcm) return str(int(result/gcd)) + '/' + str(int(lcm/gcd))
class Solution { private int gcd(int x, int y){ return x!=0?gcd(y%x, x):Math.abs(y); } public String fractionAddition(String exp) { Scanner sc = new Scanner(exp).useDelimiter("/|(?=[-+])"); int A=0, B=1; while(sc.hasNext()){ int a = sc.nextInt(), b=sc.nextInt(); A = A * b + B * a; B *= b; int gcdX = gcd(A, B); A/=gcdX; B/=gcdX; } return A+"/"+B; } }
class Solution { public: string fractionAddition(string expression) { int res_num = 0; //keep track of numerator int res_denom = 1; //keep track of denominator char sign = '+'; //keep track of sign for(int i = 0; i < expression.size(); i++){ //parse the expression string int next_num = 0; int next_denom = 0; if(expression[i] == '+' || expression[i] == '-') //updating sign = expression[i]; else{ int j = i+1; while(j < expression.size() && expression[j] != '/') j++; build next numerator next_num = stoi(expression.substr(i, j-i)); int k = j+1; while(k < expression.size() && expression[k] >= '0' && expression[k] <= '9') k++; //build next denominator next_denom = stoi(expression.substr(j+1, k-(j+1))); if(res_denom != next_denom){ //update result numerator and denominator res_num *= next_denom; next_num *= res_denom; res_denom *= next_denom; } if(sign == '+') res_num += next_num; else res_num -= next_num; i = k-1; } } return lowestFraction(res_num, res_denom); //put the fraction into lowest terms and return as string } private: int findGCD(int a, int b) { //find Greatest Common Denominator if(b == 0) return a; return findGCD(b, a % b); } string lowestFraction(int num, int denom){ //use GCD to put fraction into lowest terms and return as string int gcd; gcd = findGCD(num, denom); num /= gcd; denom /= gcd; if(denom < 0){ denom *= -1; num *= -1; } return to_string(num) + '/' + to_string(denom); } };
var fractionAddition = function(expression) { const fractions = expression.split(/[+-]/).filter(Boolean); const operator = expression.split(/[0-9/]/).filter(Boolean); expression[0] !== '-' && operator.unshift('+'); const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); const lcm = fractions.reduce((result, fraction) => { const denominator = fraction.split('/')[1]; return result * denominator / gcd(result, denominator); }, 1); const molecularSum = fractions.reduce((total, fraction, index) => { const [molecular, denominator] = fraction.split('/'); const multiple = lcm / denominator * (operator[index] === '+' ? 1 : -1); return total + molecular * multiple; }, 0); const resultGcd = gcd(Math.abs(molecularSum), lcm); return `${molecularSum / resultGcd}/${lcm / resultGcd}`; };
Fraction Addition and Subtraction
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. &nbsp; Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. &nbsp; Constraints: 1 &lt;= nums.length &lt;= 104 -231 &lt;= nums[i] &lt;= 231 - 1 &nbsp; Follow up: Can you find an O(n) solution?
class Solution: def thirdMax(self, nums: List[int]) -> int: nums_set = set(nums) sorted_set = sorted(nums_set) return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1] #use set() to remove dups #if len of nums after dups have been removed is at least 2, a third max val must exist #if not, just return the max #you can do it in 1 line like this but then you have to call the same functions repeatedly #return sorted(set(nums))[-3] if len(set(nums)) > 2 else sorted(set(nums))[-1]
class Solution { public int thirdMax(int[] nums) { Integer first = null, second = null, third = null; for(Integer num: nums){ if(num.equals(first) || num.equals(second) || num.equals(third)) continue; if(first == null || num > first){ third = second; second = first; first = num; continue; } if(second == null || num > second){ third = second; second = num; continue; } if(third == null || num > third){ third = num; } } return (third != null) ? third : first; } }
class Solution { public: int thirdMax(vector<int>& nums) { set<int>s; for(int i=0;i<nums.size();i++){ s.insert(nums[i]); } if(s.size()>=3){ // when set size >=3 means 3rd Maximum exist(because set does not contain duplicate element) int Third_index_from_last=s.size()-3; auto third_maximum=next(s.begin(),Third_index_from_last); return *third_maximum; } return *--s.end(); // return maximum if 3rd maximum not exist } };
var thirdMax = function(nums) { nums.sort((a,b) => b-a); //remove duplicate elements for(let i=0; i<nums.length;i++){ if(nums[i] === nums[i+1]){ nums.splice(i+1, 1); i-- } } return nums[2] !=undefined?nums[2]: nums[0] };
Third Maximum Number
You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: Choose array nums1 or nums2 to traverse (from index-0). Traverse the current array from left to right. If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path). The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7. &nbsp; Example 1: Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9] Output: 30 Explanation: Valid paths: [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1) [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2) The maximum is obtained with the path in green [2,4,6,8,10]. Example 2: Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100] Output: 109 Explanation: Maximum sum is obtained with the path [1,3,5,100]. Example 3: Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] Output: 40 Explanation: There are no common elements between nums1 and nums2. Maximum sum is obtained with the path [6,7,8,9,10]. &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 105 1 &lt;= nums1[i], nums2[i] &lt;= 107 nums1 and nums2 are strictly increasing.
from itertools import accumulate class Solution: def maxSum(self, nums1: List[int], nums2: List[int]) -> int: acc1 = list(accumulate(nums1, initial = 0)) acc2 = list(accumulate(nums2, initial = 0)) i, j = len(nums1)-1, len(nums2)-1 previ, prevj = len(nums1), len(nums2) prev_maxscore = 0 while i >= 0 and j >= 0: while i >= 0 and j >= 0 and nums1[i] < nums2[j]: j -= 1 if i >= 0 and j >= 0 and nums1[i] == nums2[j]: prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j]) previ, prevj = i, j i -= 1 j -= 1 while i >= 0 and j >= 0 and nums2[j] < nums1[i]: i -= 1 if i >= 0 and j >= 0 and nums1[i] == nums2[j]: prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j]) previ, prevj = i, j i -= 1 j -= 1 prev_maxscore += max(acc1[previ]-acc1[0], acc2[prevj]-acc2[0]) return prev_maxscore % (10**9 + 7)
class Solution { public int maxSum(int[] nums1, int[] nums2) { long currSum = 0, sum1 = 0, sum2 = 0; int i = 0; int j = 0; while(i < nums1.length && j < nums2.length){ if(nums1[i] == nums2[j]) { currSum += Math.max(sum1, sum2) + nums2[j]; sum1 = 0; sum2 = 0; i++; j++; } else if(nums1[i] < nums2[j]){ sum1 += nums1[i++]; } else { sum2 += nums2[j++]; } } while(i < nums1.length){ sum1 += nums1[i++]; } while(j < nums2.length){ sum2 += nums2[j++]; } return (int)((currSum + Math.max(sum1, sum2)) % 1000000007); } }
#define ll long long class Solution { public: ll dp1[100005]; ll dp2[100005]; ll mod=1e9+7; ll func(vector<int> &nums1 , vector<int> &nums2 , unordered_map< int , int> &mp1, unordered_map< int , int> &mp2 , int i1 , int i2 , int n1 , int n2 , bool f1) { if(i1>=n1 || i2>=n2) { return 0; } ll sum1=0; ll sum2=0; ll ans=0; if(f1==true) { if(dp1[i1]!=-1) { return dp1[i1]; } } else { if(dp2[i2]!=-1) { return dp2[i2]; } } if(f1==true) { sum1=(sum1 + nums1[i1]); auto it=mp2.find(nums1[i1]); sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , i1+1 , i2 , n1 , n2 , true)); if(it!=mp2.end()) { int idx=mp2[nums1[i1]]; sum2=(sum2 + nums2[idx]); sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , idx+1 , n1 , n2 , false )); } ans=max(sum1 , sum2); dp1[i1]=ans; } else { sum2=(sum2 + nums2[i2]); auto it=mp1.find(nums2[i2]); sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , i2+1 , n1 , n2 , false)); if(it!=mp1.end()) { int idx=mp1[nums2[i2]]; sum1= (sum1 + nums1[idx]); sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , idx+1 , i2 , n1 , n2 , true)); } ans=max(sum1 , sum2); dp2[i2]=ans; } return ans; } int maxSum(vector<int>& nums1, vector<int>& nums2) { // at every equal value we can switch // the elements from array1 to array2 unordered_map< int , int> mp1 , mp2; int n1=nums1.size() , n2=nums2.size(); for(int i=0;i<nums1.size();i++) { mp1[nums1[i]]=i; } for(int i=0;i<nums2.size();i++) { mp2[nums2[i]]=i; } // start from both array as nums1 & nums2 , nums2 & nums1 memset(dp1 , -1 , sizeof(dp1)); memset(dp2 , -1 , sizeof(dp2)); bool f1=true; ll ans1=func(nums1 , nums2 , mp1 , mp2 , 0 , 0 ,n1 , n2 , f1); memset(dp1 , -1 , sizeof(dp1)); memset(dp2 , -1 , sizeof(dp2)); ll ans2=func(nums2 , nums1 , mp2 , mp1 , 0 , 0 , n2 , n1 , f1); ans1=ans1%mod; ans2=ans2%mod; return max(ans1 , ans2); }
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var maxSum = function(nums1, nums2) { let MODULO_AMOUNT = 10 ** 9 + 7; let result = 0; let ptr1 = 0; let ptr2 = 0; let n1 = nums1.length; let n2 = nums2.length; let section_sum1 = 0; let section_sum2 = 0; while(ptr1 < n1 || ptr2 < n2){ if(ptr1 < n1 && ptr2 < n2 && nums1[ptr1] == nums2[ptr2]){ result += Math.max(section_sum1, section_sum2) + nums1[ptr1]; result %= MODULO_AMOUNT; section_sum1 = 0; section_sum2 = 0; ptr1 += 1; ptr2 += 1; continue; } if(ptr1 == n1 || (ptr2 != n2 && nums1[ptr1] > nums2[ptr2])){ section_sum2 += nums2[ptr2]; ptr2 += 1; }else{ section_sum1 += nums1[ptr1]; ptr1 += 1; } } result += Math.max(section_sum1, section_sum2); return result % MODULO_AMOUNT; };
Get the Maximum Score
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words. For example, if words = ["abc", "xyz"]&nbsp;and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters "axyz" matches "xyz" from words. Implement the StreamChecker class: StreamChecker(String[] words) Initializes the object with the strings array words. boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words. &nbsp; Example 1: Input ["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"] [[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]] Output [null, false, false, false, true, false, true, false, false, false, false, false, true] Explanation StreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]); streamChecker.query("a"); // return False streamChecker.query("b"); // return False streamChecker.query("c"); // return False streamChecker.query("d"); // return True, because 'cd' is in the wordlist streamChecker.query("e"); // return False streamChecker.query("f"); // return True, because 'f' is in the wordlist streamChecker.query("g"); // return False streamChecker.query("h"); // return False streamChecker.query("i"); // return False streamChecker.query("j"); // return False streamChecker.query("k"); // return False streamChecker.query("l"); // return True, because 'kl' is in the wordlist &nbsp; Constraints: 1 &lt;= words.length &lt;= 2000 1 &lt;= words[i].length &lt;= 200 words[i] consists of lowercase English letters. letter is a lowercase English letter. At most 4 * 104 calls will be made to query.
class TrieNode: def __init__(self): self.children = {} self.endOfWord = False class StreamChecker: def __init__(self, words: List[str]): self.root = TrieNode() self.qCur = self.root self.stream = collections.deque() cur = self.root for word in words: for i in range(len(word) - 1, -1, -1): ch = word[i] if ch not in cur.children: cur.children[ch] = TrieNode() cur = cur.children[ch] cur.endOfWord = True cur = self.root def query(self, letter: str) -> bool: self.stream.appendleft(letter) cur = self.root for ch in self.stream: if ch not in cur.children: return False else: cur = cur.children[ch] if cur.endOfWord: return True return False
class StreamChecker { class TrieNode { boolean isWord; TrieNode[] next = new TrieNode[26]; } TrieNode root = new TrieNode(); StringBuilder sb = new StringBuilder(); public StreamChecker(String[] words) { createTrie(words); } public boolean query(char letter){ sb.append(letter); TrieNode node = root; for(int i=sb.length()-1; i>=0 && node!=null; i--){ char ch = sb.charAt(i); node = node.next[ch - 'a']; if(node != null && node.isWord){ return true; } } return false; } private void createTrie(String words[]){ for(String s : words){ TrieNode node = root; int len = s.length(); for(int i = len-1; i>=0; i--){ char ch = s.charAt(i); if(node.next[ch-'a'] == null){ node.next[ch - 'a'] = new TrieNode(); } node = node.next[ch - 'a']; } node.isWord = true; } } }
class StreamChecker { struct Trie { Trie* suffixLink; //this is where it will fallback to when a letter can't be matched int id = -1; //this id will be 0 or greater if it matches a word map<char, Trie*> next; }; public: Trie* root; Trie* queryPtr; int uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system StreamChecker(vector<string>& words) { root = new Trie(); //standard trie traversal but keeping track of new words via id system for (string& word: words) { Trie* p = root; for (char c: word) { if (p->next.find(c) == p->next.end()) { p->next.insert({ c, new Trie() }); } p = p->next.at(c); } if (p->id == -1) { p->id = uniqueIds++; } } queue<Trie*> q; for (pair<char, Trie*> itr: root->next) { q.push(itr.second); itr.second->suffixLink = root; } //BFS traversal to build the automaton while (q.size()) { Trie* curr = q.front(); q.pop(); for (pair<char, Trie*> e: curr->next) { char c = e.first; Trie* node = e.second; Trie* ptr = curr->suffixLink; while (ptr != root && ptr->next.find(c) == ptr->next.end()) { ptr = ptr->suffixLink; } //find the next suffixLink if it matches the current character or fallback to the root node->suffixLink = ptr->next.find(c) != ptr->next.end() ? ptr->next.at(c) : root; //if the current suffixLink happens to also be a word we should store its id to make it quick to find if (node->suffixLink->id != -1) { node->id = node->suffixLink->id; } q.push(node); } } //the query ptr will now track every new streamed character and can be used to quickly find words queryPtr = root; } bool query(char letter) { //if the next letter can't be found and we're not at the root, we'll trace back until we find the longest suffix that matches while (queryPtr != root && queryPtr->next.find(letter) == queryPtr->next.end()) { queryPtr = queryPtr->suffixLink; } queryPtr = queryPtr->next.find(letter) != queryPtr->next.end() ? queryPtr->next.at(letter) : root; //if any word is found it will have an id that isn't -1 return queryPtr->id != -1; } };
var StreamChecker = function(words) { function Trie() { this.suffixLink = null; //this is where it will fallback to when a letter can't be matched this.id = -1; //this id will be 0 or greater if it matches a word this.next = new Map(); //map of <char, Trie*> } this.root = new Trie(); this.uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system //standard trie traversal but keeping track of new words via id system for (const word of words) { let ptr = this.root; for (const c of word) { if (!ptr.next.has(c)) { ptr.next.set(c, new Trie()); } ptr = ptr.next.get(c); } if (ptr.id === -1) { ptr.id = this.uniqueIds++; } } //BFS traversal to build the automaton const q = []; for (const [c, node] of this.root.next) { //all first level children should point back to the root when a match to a character fails node.suffixLink = this.root; q.push(node); } while (q.length) { const curr = q.shift(); for (const [c, node] of curr.next) { let ptr = curr.suffixLink; while (ptr !== this.root && !ptr.next.has(c)) { ptr = ptr.suffixLink; } //find the next suffixLink if it matches the current character or fallback to the root node.suffixLink = ptr.next.get(c) ?? this.root; //if the current suffixLink happens to also be a word we should store its id to make it quick to find if (node.suffixLink.id !== -1) { node.id = node.suffixLink.id; } q.push(node); } } //the query ptr will now track every new streamed character and use it to match this.queryPtr = this.root; }; StreamChecker.prototype.query = function(letter) { //the query ptr will now track every new streamed character and can be used to quickly find words while (this.queryPtr !== this.root && !this.queryPtr.next.has(letter)) { this.queryPtr = this.queryPtr.suffixLink; } this.queryPtr = this.queryPtr.next.get(letter) ?? this.root; //if any word is found it will have an id that isn't -1 return this.queryPtr.id !== -1; };
Stream of Characters
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat. &nbsp; Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Explanation: - Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. Hence all students are able to eat. Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3 &nbsp; Constraints: 1 &lt;= students.length, sandwiches.length &lt;= 100 students.length == sandwiches.length sandwiches[i] is 0 or 1. students[i] is 0 or 1.
class Solution(object): def countStudents(self, students, sandwiches): """ :type students: List[int] :type sandwiches: List[int] :rtype: int """ while sandwiches: if sandwiches[0] in students: students.remove(sandwiches[0]) sandwiches.pop(0) else: break return len(sandwiches)
class Solution { public int countStudents(int[] students, int[] sandwiches) { int ones = 0; //count of students who prefer type1 int zeros = 0; //count of students who prefer type0 for(int stud : students){ if(stud == 0) zeros++; else ones++; } // for each sandwich in sandwiches for(int sandwich : sandwiches){ if(sandwich == 0){ // if sandwich is of type0 if(zeros == 0){ // if no student want a type0 sandwich return ones; } zeros--; } else{ // if sandwich is of type1 if(ones == 0){ // if no student want a type1 sandwich return zeros; } ones--; } } return 0; } }
class Solution { public: int countStudents(vector<int>& students, vector<int>& sandwiches) { int size = students.size(); queue<int> student_choice; for(int i = 0 ; i < size ; ++i){ student_choice.push(students[i]); } int rotations = 0 , i = 0; while(student_choice.size() && rotations < student_choice.size()){ if(student_choice.front() == sandwiches[i]){ student_choice.pop(); i++; rotations = 0; } else { int choice = student_choice.front(); student_choice.pop(); student_choice.push(choice); rotations++; } } return student_choice.size(); } };
var countStudents = function(students, sandwiches) { while (students.length>0 && students.indexOf(sandwiches[0])!=-1) { if (students[0] == sandwiches[0]) { students.shift(); sandwiches.shift(); } else students.push(students.shift()); } return students.length };
Number of Students Unable to Eat Lunch
Given a string s.&nbsp;Return&nbsp;all the words vertically in the same order in which they appear in s. Words are returned as a list of strings, complete with&nbsp;spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. &nbsp; Example 1: Input: s = "HOW ARE YOU" Output: ["HAY","ORO","WEU"] Explanation: Each word is printed vertically. "HAY" &nbsp;"ORO" &nbsp;"WEU" Example 2: Input: s = "TO BE OR NOT TO BE" Output: ["TBONTB","OEROOE"," T"] Explanation: Trailing spaces is not allowed. "TBONTB" "OEROOE" " T" Example 3: Input: s = "CONTEST IS COMING" Output: ["CIC","OSO","N M","T I","E N","S G","T"] &nbsp; Constraints: 1 &lt;= s.length &lt;= 200 s&nbsp;contains only upper case English letters. It's guaranteed that there is only one&nbsp;space between 2 words.
class Solution: def getMaxLen(self, words): max_len = 0 for word in words: max_len = max(max_len, len(word)) return max_len def printVertically(self, s: str) -> List[str]: words = s.split() max_len = self.getMaxLen(words) res = list() for i in range(max_len): s = "" for word in words: if i < len(word): s += word[i] else: s += " " s = s.rstrip() res.append(s) return res
class Solution { public List<String> printVertically(String s) { s = s.replace(" ",","); String str=""; List<String> a=new ArrayList<>(); int max=0; for(int i =0;i<s.length();i++){ char ch=s.charAt(i); if(ch==','){ a.add(str); max=Math.max(max,str.length()); str=""; continue; } else if(i==s.length()-1){ str+=ch; a.add(str); max=Math.max(max,str.length()); str=""; continue; } str+=ch; } String [] arr=new String[max]; for(int i =0;i<max;i++){ arr[i]=""; } for(int i =0;i<a.size();i++){ String x=a.get(i); for(int j=0;j<max;j++){ if(j<x.length()){ arr[j]+=x.charAt(j); } else{ arr[j]+=" "; } } } a=new ArrayList<>(); for(int i=0;i<arr.length;i++){ String x=arr[i]; x=trim(x); a.add(x); } return a; } public String trim(String str) { int len = str.length(); int st = 0; char[] val = str.toCharArray(); while ((st < len) && (val[len - 1] <= ' ')) { len--; } return str.substring(st, len); } }
class Solution { public: vector<string> printVertically(string s) { int row = 0, col = 0; stringstream sso(s); string buffer; while (sso >> buffer) { row++; col = max((int)buffer.size(),col); } vector<vector<char>> matrix(row, vector<char>(col,' ')); sso = stringstream(s); int i = 0; while (sso >> buffer) { for (int j = 0; j < buffer.size(); j++) matrix[i][j] = buffer[j]; i++; } vector<string> res; for (int j = 0; j < col; j++) { string item; for (int i = 0; i < row; i++) item.push_back(matrix[i][j]); for (int i = item.size()-1; i >= 0; i--) { if (item[i] != ' ') { item.erase(item.begin()+i+1,item.end()); break; } } res.push_back(item); } return res; } };
/** * @param {string} s * @return {string[]} */ var printVertically = function(s) { let arr = s.split(' '), max = arr.reduce((last, curr) => Math.max(last, curr.length), 0), ans = []; arr = arr.map(el => el + ' '.repeat(max - el.length)); for (let i = 0; i < max; i++) { let word = ''; for (let j = 0; j < arr.length; j++) word += arr[j][i]; ans.push(word.replace(new RegExp('\\s+$'), '')); } return ans; };
Print Words Vertically
Given two arrays nums1&nbsp;and nums2. Return the maximum dot product&nbsp;between&nbsp;non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,&nbsp;[2,3,5]&nbsp;is a subsequence of&nbsp;[1,2,3,4,5]&nbsp;while [1,5,3]&nbsp;is not). &nbsp; Example 1: Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6] Output: 18 Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2. Their dot product is (2*3 + (-2)*(-6)) = 18. Example 2: Input: nums1 = [3,-2], nums2 = [2,-6,7] Output: 21 Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2. Their dot product is (3*7) = 21. Example 3: Input: nums1 = [-1,-1], nums2 = [1,1] Output: -1 Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2. Their dot product is -1. &nbsp; Constraints: 1 &lt;= nums1.length, nums2.length &lt;= 500 -1000 &lt;= nums1[i], nums2[i] &lt;= 1000
class Solution: def maxDotProduct(self, A, B): dp = [float('-inf')] * (len(B)+1) for i in range(len(A)): prev = float('-inf') for j in range(len(B)): product = A[i] * B[j] prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product) return dp[-1]
class Solution { public int maxDotProduct(int[] nums1, int[] nums2) { int N = nums1.length, M = nums2.length; int[][] dp = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { dp[i][j] = nums1[i] * nums2[j]; if (i > 0 && j > 0 && dp[i - 1][j - 1] > 0) { dp[i][j] += dp[i - 1][j - 1]; } if (i > 0 && dp[i - 1][j] > dp[i][j]) { dp[i][j] = dp[i - 1][j]; } if (j > 0 && dp[i][j - 1] > dp[i][j]) { dp[i][j] = dp[i][j - 1]; } } } return dp[N - 1][M - 1]; } }
class Solution { public: const int NEG_INF = -10e8; int maxDotProduct(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int m = nums2.size(); // NOTE : we can't initialize with INT_MIN because adding any val with it will give overflow // that is why we prefer 10^7 or 10^8 vector<vector<int>> dp(n+1, vector<int>(m+1, NEG_INF)); for (int i=1; i<=n; i++) { for (int j=1; j<=m; j++) { int temp_p = nums1[i-1]*nums2[j-1]; // Although it is a variation of LCS but here we need to check for all answers we already know in dp // Why only temp_p ? -> suppose in dp[i-1][j-1] is -10^7 + temp_p is 2 == gives nearly -10^7(which is wrong ans) // For Remaining comparisons we already know why ! dp[i][j] = max({ dp[i-1][j-1] + temp_p, temp_p, dp[i-1][j], dp[i][j-1] }); } } return dp[n][m]; } };
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var maxDotProduct = function(nums1, nums2) { var m = nums1.length; var n = nums2.length; if (!m || !n) return 0; var dp = [[nums1[0] * nums2[0]]]; for (var i = 1; i < m; i++) { dp[i] = []; dp[i][0] = Math.max(nums1[i] * nums2[0], dp[i-1][0]); } for (var i = 1; i < n; i++) dp[0][i] = Math.max(nums1[0] * nums2[i], dp[0][i-1]); for (var i = 1; i < m; i++) { for (var j = 1; j < n; j++) { var val = nums1[i] * nums2[j]; dp[i][j] = Math.max(val, val + dp[i-1][j-1], dp[i][j-1], dp[i-1][j]); } } return dp[m - 1][n - 1]; };
Max Dot Product of Two Subsequences
A string is considered beautiful if it satisfies the following conditions: Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.). For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string. &nbsp; Example 1: Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" Output: 13 Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. Example 2: Input: word = "aeeeiiiioooauuuaeiou" Output: 5 Explanation: The longest beautiful substring in word is "aeiou" of length 5. Example 3: Input: word = "a" Output: 0 Explanation: There is no beautiful substring, so return 0. &nbsp; Constraints: 1 &lt;= word.length &lt;= 5 * 105 word consists of characters 'a', 'e', 'i', 'o', and 'u'.
class Solution: def longestBeautifulSubstring(self, word: str) -> int: g = '' count = m = 0 for x in word: if g and x < g[-1]: count = 0 g = '' if not g or x > g[-1]: g += x count += 1 if g == 'aeiou': m = max(m, count) return m
class Solution { public int longestBeautifulSubstring(String word) { int max = 0; for(int i = 1;i<word.length();i++){ int temp = 1; Set<Character> verify = new HashSet<>(); verify.add(word.charAt(i-1)); while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){ temp++; verify.add(word.charAt(i)); i++; } max = verify.size() == 5 ? Math.max(max,temp) : max ; } return max; } }
class Solution { public: int longestBeautifulSubstring(string word) { const auto n = word.size(); int cnt = 1; int len = 1; int max_len = 0; for (int i = 1; i != n; ++i) { if (word[i - 1] == word[i]) { ++len; } else if (word[i - 1] < word[i]) { ++len; ++cnt; } else { cnt = 1; len = 1; } if (cnt == 5) { max_len = max(max_len, len); } } return max_len; } };
/** * @param {string} word * @return {number} */ var longestBeautifulSubstring = function(word) { let obj = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 } let seq = 0 let maxstrcount = 0, strcount = "" for (let i = 0; i <= word.length; i++) { if (seq <= obj[word[i]]) { strcount += word[i] seq = obj[word[i]] } else { let set = new Set() for (let i = 0; i < strcount.length; i++) { set.add(strcount[i]) } if (set.size == 5) { maxstrcount = Math.max(strcount.length, maxstrcount) } if (i < word.length - 1) i-- strcount = "" seq = 0 } } return maxstrcount };
Longest Substring Of All Vowels in Order
You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 &lt;= i &lt; n. Every arr[i] is divisible by arr[i - 1], for 0 &lt; i &lt; n. Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7. &nbsp; Example 1: Input: n = 2, maxValue = 5 Output: 10 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5] - Arrays starting with the value 2 (2 arrays): [2,2], [2,4] - Arrays starting with the value 3 (1 array): [3,3] - Arrays starting with the value 4 (1 array): [4,4] - Arrays starting with the value 5 (1 array): [5,5] There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays. Example 2: Input: n = 5, maxValue = 3 Output: 11 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (9 arrays): - With no other distinct values (1 array): [1,1,1,1,1] - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] - Arrays starting with the value 2 (1 array): [2,2,2,2,2] - Arrays starting with the value 3 (1 array): [3,3,3,3,3] There are a total of 9 + 1 + 1 = 11 distinct ideal arrays. &nbsp; Constraints: 2 &lt;= n &lt;= 104 1 &lt;= maxValue &lt;= 104
from math import sqrt class Solution: def primesUpTo(self, n): primes = set(range(2, n + 1)) for i in range(2, n): if i in primes: it = i * 2 while it <= n: if it in primes: primes.remove(it) it += i return primes def getPrimeFactors(self, n, primes): ret = {} sq = int(math.sqrt(n)) for p in primes: if n in primes: ret[n] = 1 break while n % p == 0: ret[p] = ret.get(p, 0) + 1 n //= p if n <= 1: break return ret def idealArrays(self, n: int, maxValue: int) -> int: mod = 10**9 + 7 ret = 0 primes = self.primesUpTo(maxValue) for num in range(1, maxValue + 1): # find number of arrays that can end with num # for each prime factor, we can add it at any index i that we want pf = self.getPrimeFactors(num, primes) cur = 1 for d in pf: ct = pf[d] v = n # there are (n + 1) choose k ways to add k prime factors for add in range(1, ct): v *= (n + add) v //= (add + 1) cur = (cur * v) % mod ret = (ret + cur) % mod return ret
class Solution { int M =(int)1e9+7; public int idealArrays(int n, int maxValue) { long ans = 0; int N = n+maxValue; long[] inv = new long[N]; long[] fact = new long[N]; long[] factinv = new long[N]; inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1; for (int i = 2; i < N; i++){ // mod inverse inv[i]=M-M/i*inv[M%i]%M; fact[i]=fact[i-1]*i%M; factinv[i]=factinv[i-1]*inv[i]%M; } for (int i = 1; i <= maxValue; i++){ int tmp = i; Map<Integer, Integer> map = new HashMap<>(); for (int j = 2; j*j<= tmp; j++){ while(tmp%j==0){ // prime factorization. tmp/=j; map.merge(j, 1, Integer::sum); } } if (tmp>1){ map.merge(tmp, 1, Integer::sum); } long gain=1; for (int val : map.values()){ // arranges all the primes. gain *= comb(n+val-1, val, fact, factinv); gain %= M; } ans += gain; ans %= M; } return (int)ans; } private long comb(int a, int b, long[] fact, long[] factinv){ return fact[a]*factinv[b]%M*factinv[a-b]%M; } }
int comb[10001][14] = { 1 }, cnt[10001][14] = {}, mod = 1000000007; class Solution { public: int idealArrays(int n, int maxValue) { if (comb[1][1] == 0) { // one-time computation. for (int s = 1; s <= 10000; ++s) // nCr (comb) for (int r = 0; r < 14; ++r) comb[s][r] = r == 0 ? 1 : (comb[s - 1][r - 1] + comb[s - 1][r]) % mod; for (int div = 1; div <= 10000; ++div) { // Sieve of Eratosthenes ++cnt[div][0]; for (int i = 2 * div; i <= 10000; i += div) for (int bars = 0; cnt[div][bars]; ++bars) cnt[i][bars + 1] += cnt[div][bars]; } } int res = 0; for (int i = 1; i <= maxValue; ++i) for (int bars = 0; bars < min(14, n) && cnt[i][bars]; ++bars) res = (1LL * cnt[i][bars] * comb[n - 1][bars] + res) % mod; return res; } };
/** * @param {number} n * @param {number} maxValue * @return {number} */ var idealArrays = function(n, maxValue) { const mod = 1e9 + 7; let cur = 0; let arr = Array(2).fill().map(() => Array(maxValue).fill(1)); for (let l = 2; l <= n; l++) { const prev = arr[cur]; const next = arr[1-cur]; for (let s = 1; s <= maxValue; s++) { let res = 0; for (let m = 1; m * s <= maxValue; m++) { res = (res + prev[m * s - 1]) % mod; } next[s-1] = res; } cur = 1 - cur; } const res = arr[cur].reduce((a, b) => (a + b) % mod, 0); return res; };
Count the Number of Ideal Arrays
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with the maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins that you can have. &nbsp; Example 1: Input: piles = [2,4,1,2,7,8] Output: 9 Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. Example 2: Input: piles = [2,4,5] Output: 4 Example 3: Input: piles = [9,8,7,6,5,1,2,3,4] Output: 18 &nbsp; Constraints: 3 &lt;= piles.length &lt;= 105 piles.length % 3 == 0 1 &lt;= piles[i] &lt;= 104
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() n = len(piles) k = n // 3 i, j = 0, 2 ans = 0 while i < k: ans += piles[n-j] j += 2 i +=1 return ans
class Solution { public int maxCoins(int[] piles) { Arrays.sort(piles); int s=0,n=piles.length; for(int i=n/3;i<n;i+=2) s+=piles[i]; return s; } }
class Solution { public: int maxCoins(vector<int>& piles) { sort(piles.begin(),piles.end(),greater<int>()); int myPilesCount=0; int myPilesSum=0; int PilesSize=piles.size(); int i=1; while(myPilesCount<(PilesSize/3)) { myPilesSum+=piles[i]; myPilesCount++; i+=2; } return myPilesSum; } };
var maxCoins = function(piles) { let count = 0, i = 0, j = piles.length - 1; piles.sort((a, b) => b - a); while(i < j) { count += piles[i + 1]; i += 2; j--; } return count; };
Maximum Number of Coins You Can Get
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). For example, "Hello World", "HELLO", and "hello world hello world" are all sentences. You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it. &nbsp; Example 1: Input: s = "Hello how are you Contestant", k = 4 Output: "Hello how are you" Explanation: The words in s are ["Hello", "how" "are", "you", "Contestant"]. The first 4 words are ["Hello", "how", "are", "you"]. Hence, you should return "Hello how are you". Example 2: Input: s = "What is the solution to this problem", k = 4 Output: "What is the solution" Explanation: The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. The first 4 words are ["What", "is", "the", "solution"]. Hence, you should return "What is the solution". Example 3: Input: s = "chopper is not a tanuki", k = 5 Output: "chopper is not a tanuki" &nbsp; Constraints: 1 &lt;= s.length &lt;= 500 k is in the range [1, the number of words in s]. s consist of only lowercase and uppercase English letters and spaces. The words in s are separated by a single space. There are no leading or trailing spaces.
class Solution: def truncateSentence(self, s: str, k: int) -> str: words = s.split(" ") return " ".join(words[0:k])
class Solution { public String truncateSentence(String s, int k) { int n = s.length(); int count = 0; int i = 0; while(i<n){ if(s.charAt(i)==' '){ count++; if(count==k) return s.substring(0,i); } i++; } return s; } }
class Solution { public: string truncateSentence(string s, int k) { int n = s.size(); string ans; int cnt = 0; for(int i=0 ; i<n ; i++){ if(s[i] == ' '){ cnt++; } if(k == cnt){ return ans; } ans += s[i]; } return ans; } };
/** * @param {string} s * @param {number} k * @return {string} */ var truncateSentence = function(s, k) { return s.split(" ").slice(0,k).join(" ") };
Truncate Sentence
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. &nbsp; Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true Example 2: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 Output: false &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= n, m &lt;= 300 -109 &lt;= matrix[i][j] &lt;= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 &lt;= target &lt;= 109
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ found=False for X in matrix: for M in X: if M==target: found=True return found
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int rows = matrix.length; int cols = matrix[0].length; int lo = 0, hi = rows; while(lo + 1 < hi) { int mid = lo + (hi - lo) / 2; if (matrix[mid][0] <= target) { lo = mid; } else { hi = mid; } } int[] prospect; for (int i = 0; i <= lo; i++) { prospect = matrix[i]; int l = 0; int h = cols; while (l + 1 < h) { int mid = l + (h - l) / 2; if (prospect[mid] <= target) { l = mid; } else { h = mid; } } if (prospect[l] == target) { return true; } } return false; } }
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for(int i=0;i<matrix.size();++i) { int s=0,e=matrix[0].size()-1; while(s<=e) { int mid=(s+e)/2; if(matrix[i][mid]>target) { e=mid-1; } else if(matrix[i][mid]<target) { s=mid+1; } else { return true; } } } return false; } };
function binarySearch(arr, target) { let low = 0; let high = arr.length - 1; while (low <= high) { let mid = parseInt((low + high) / 2); if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { low = mid + 1; } else if (arr[mid] > target) { high = mid - 1; } } return -1; } var searchMatrix = function(matrix, target) { for (let i = 0; i < matrix.length; i++) { let check = binarySearch(matrix[i], target); if (check != -1) { return true } } return false };
Search a 2D Matrix II
Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -&gt; aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aacabb -&gt; bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary. Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. &nbsp; Example 1: Input: word1 = "abc", word2 = "bca" Output: true Explanation: You can attain word2 from word1 in 2 operations. Apply Operation 1: "abc" -&gt; "acb" Apply Operation 1: "acb" -&gt; "bca" Example 2: Input: word1 = "a", word2 = "aa" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. Example 3: Input: word1 = "cabbba", word2 = "abbccc" Output: true Explanation: You can attain word2 from word1 in 3 operations. Apply Operation 1: "cabbba" -&gt; "caabbb" Apply Operation 2: "caabbb" -&gt; "baaccc" Apply Operation 2: "baaccc" -&gt; "abbccc" &nbsp; Constraints: 1 &lt;= word1.length, word2.length &lt;= 105 word1 and word2 contain&nbsp;only lowercase English letters.
from collections import Counter class Solution: def closeStrings(self, word1: str, word2: str) -> bool: return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())
class Solution { private int N = 26; public boolean closeStrings(String word1, String word2) { // count the English letters int[] arr1 = new int[N], arr2 = new int[N]; for (char ch : word1.toCharArray()) arr1[ch - 'a']++; for (char ch : word2.toCharArray()) arr2[ch - 'a']++; // if one has a letter which another one doesn't have, dont exist for (int i = 0; i < N; i++) { if (arr1[i] == arr2[i]) { continue; } if (arr1[i] == 0 || arr2[i] == 0) { return false; } } Arrays.sort(arr1); Arrays.sort(arr2); for (int i = 0; i < N; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } }
class Solution { public: bool closeStrings(string word1, string word2) { set<int> w1_letters, w2_letters, w1_freq, w2_freq; unordered_map<char, int> w1_m, w2_m; for (auto a : word1) { w1_letters.insert(a); w1_m[a]++; } for (auto a : word2) { w2_letters.insert(a); w2_m[a]++; } for (auto [k, v] : w1_m) w1_freq.insert(v); for (auto [k, v] : w2_m) w2_freq.insert(v); return w1_letters == w2_letters && w1_freq == w2_freq; } };
var closeStrings = function(word1, word2) { if (word1.length != word2.length) return false; let map1 = new Map(), map2 = new Map(),freq1=new Set(),freq2=new Set(); for (let i = 0; i < word1.length; i++) map1.set(word1[i],map1.get(word1[i])+1||1),map2.set(word2[i],map2.get(word2[i])+1||1); if (map1.size != map2.size) return false; for (const [key,value] of map1) { if (!map2.has(key)) return false freq1.add(value); freq2.add(map2.get(key)); } if (freq1.size != freq2.size) return false; for (const freq of freq1) if (!freq2.has(freq)) return false return true; };
Determine if Two Strings Are Close
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Example 2: Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. -231 &lt;= Node.val &lt;= 231 - 1
# 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: # O(n) || O(h) where h is the height of the tree def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: queue = deque([root]) result = [] while queue: runningSum = 0 newLevelSize = 0 for i in range(len(queue)): currNode = queue.popleft() runningSum += currNode.val newLevelSize += 1 if currNode.left: queue.append(currNode.left) if currNode.right: queue.append(currNode.right) secretFormula = (runningSum/newLevelSize) result.append(secretFormula) return result
class Solution { public List<Double> averageOfLevels(TreeNode root) { Queue<TreeNode> q = new LinkedList<>(List.of(root)); List<Double> ans = new ArrayList<>(); while (q.size() > 0) { double qlen = q.size(), row = 0; for (int i = 0; i < qlen; i++) { TreeNode curr = q.poll(); row += curr.val; if (curr.left != null) q.offer(curr.left); if (curr.right != null) q.offer(curr.right); } ans.add(row/qlen); } return ans; } }
/** * 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: // Pre-Requisite for this solution: Level order traversal of a BT Line by Line vector<double> averageOfLevels(TreeNode* root) { // vector to store the result vector<double> avgVal; avgVal.push_back(root->val); // Queue for level order traversal Line by Line queue<TreeNode*> q; q.push(root); q.push(NULL); // To store values for levels double levelSum = 0; double levelCount = 0; // Standard Level order traversal Line by Line code while(q.empty() == false){ TreeNode* curr = q.front(); q.pop(); if(curr == NULL){ if(q.empty()==true){ break; } else{ // Here we know that we are at the end of a line // So we push the result into the vector avgVal.push_back(levelSum/levelCount); // Reset the counters and push End of Level into the queue. levelSum = 0; levelCount = 0; q.push(NULL); continue; } } // Note that when we are traversing one level // we are getting sum and count of the next level // Hence, we are moving one level ahead if(curr->left){ q.push(curr->left); levelSum += curr->left->val; levelCount++; } if(curr->right){ q.push(curr->right); levelSum += curr->right->val; levelCount++; } } return avgVal; } };
var averageOfLevels = function(root) { let avg = [root.val]; let level = []; let queue = [root]; while(queue.length>0){ let curr = queue.shift(); if(curr.left){ level.push(curr.left) } if(curr.right){ level.push(curr.right); } if(queue.length===0){ queue.push(...level); avg.push(level.reduce((a,b) => a+b.val,0)/level.length); level = []; } } avg.pop() return avg; };
Average of Levels in Binary Tree
Given an input string s&nbsp;and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). &nbsp; Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". &nbsp; Constraints: 1 &lt;= s.length&nbsp;&lt;= 20 1 &lt;= p.length&nbsp;&lt;= 30 s contains only lowercase English letters. p contains only lowercase English letters, '.', and&nbsp;'*'. It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
class Solution: def isMatch(self, s, p): n = len(s) m = len(p) dp = [[False for _ in range (m+1)] for _ in range (n+1)] dp[0][0] = True for c in range(1,m+1): if p[c-1] == '*' and c > 1: dp[0][c] = dp[0][c-2] for r in range(1,n+1): for c in range(1,m+1): if p[c-1] == s[r-1] or p[c-1] == '.': dp[r][c] = dp[r-1][c-1] elif c > 1 and p[c-1] == '*': if p[c-2] =='.' or s[r-1]==p[c-2]: dp[r][c] =dp[r][c-2] or dp[r-1][c] else: dp[r][c] = dp[r][c-2] return dp[n][m]
class Solution { public boolean isMatch(String s, String p) { if (p == null || p.length() == 0) return (s == null || s.length() == 0); boolean dp[][] = new boolean[s.length()+1][p.length()+1]; dp[0][0] = true; for (int j=2; j<=p.length(); j++) { dp[0][j] = p.charAt(j-1) == '*' && dp[0][j-2]; } for (int j=1; j<=p.length(); j++) { for (int i=1; i<=s.length(); i++) { if (p.charAt(j-1) == s.charAt(i-1) || p.charAt(j-1) == '.') dp[i][j] = dp[i-1][j-1]; else if(p.charAt(j-1) == '*') dp[i][j] = dp[i][j-2] || ((s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == '.') && dp[i-1][j]); } } return dp[s.length()][p.length()]; } }
class Solution { public: bool isMatch(string s, string p) { return helper(s,p,0,0); } bool helper(string s, string p, int i, int j) { if(j==p.length()) return i==s.length(); bool first_match=(i<s.length() && (s[i]==p[j] || p[j]=='.' )); if(j+1<p.length() && p[j+1]=='*') { return (helper(s,p,i,j+2)|| (first_match && helper(s,p,i+1,j) )); } else { return (first_match && helper(s,p,i+1,j+1)); } } };
/** * @param {string} s * @param {string} p * @return {boolean} */ var isMatch = function(s, p) { const pattern = new RegExp('^'+p+'$'); // ^ means start of string, $ means end of the string, these are to prevent certain pattern that match a part of the string to be returned as true. return pattern.test(s); };
Regular Expression Matching
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: 0 represents a wall that you cannot pass through. 1 represents an empty cell that you can freely move to and from. All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank). Price (lower price has a higher rank, but it must be in the price range). The row number (smaller row number has a higher rank). The column number (smaller column number has a higher rank). Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them. &nbsp; Example 1: Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3 Output: [[0,1],[1,1],[2,1]] Explanation: You start at (0,0). With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2). The ranks of these items are: - (0,1) with distance 1 - (1,1) with distance 2 - (2,1) with distance 3 - (2,2) with distance 4 Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1). Example 2: Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2 Output: [[2,1],[1,2]] Explanation: You start at (2,3). With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1). The ranks of these items are: - (2,1) with distance 2, price 2 - (1,2) with distance 2, price 3 - (1,1) with distance 3 - (0,1) with distance 4 Thus, the 2 highest ranked items in the price range are (2,1) and (1,2). Example 3: Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3 Output: [[2,1],[2,0]] Explanation: You start at (0,0). With a price range of [2,3], we can take items from (2,0) and (2,1). The ranks of these items are: - (2,1) with distance 5 - (2,0) with distance 6 Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). Note that k = 3 but there are only 2 reachable items within the price range. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 105 1 &lt;= m * n &lt;= 105 0 &lt;= grid[i][j] &lt;= 105 pricing.length == 2 2 &lt;= low &lt;= high &lt;= 105 start.length == 2 0 &lt;= row &lt;= m - 1 0 &lt;= col &lt;= n - 1 grid[row][col] &gt; 0 1 &lt;= k &lt;= m * n
class Solution: def highestRankedKItems(self, G, pricing, start, k): m, n = len(G), len(G[0]) row, col = start node = (0, G[row][col], row, col) visited = set() visited.add((row, col)) d = deque([node]) ans = [] while d: dist, cost, row, col = d.popleft() if pricing[0] <= cost <= pricing[1]: ans += [(dist, cost, row, col)] for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= x <= m-1 and 0 <= y <= n-1 and (x, y) not in visited and G[x][y] != 0: d.append((dist + 1, G[x][y], x, y)) visited.add((x, y)) ans = sorted(ans) return [[x, y] for _, _, x, y in ans[:k]]
class Solution { static class Quad { int x,y,price,dist; Quad(int x,int y,int price,int dist) { this.x=x; this.y=y; this.price=price; this.dist=dist; } } public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) { List<List<Integer>> ans=new LinkedList<>(); PriorityQueue<Quad> pq=new PriorityQueue<>((a,b)->{ if(a.dist!=b.dist) return a.dist-b.dist; if(a.price!=b.price) return a.price-b.price; if(a.x!=b.x) return a.x-b.x; return a.y-b.y; }); bfs(grid,start[0],start[1],pricing[0],pricing[1],pq); while(!pq.isEmpty()&&k-->0) { Quad quad=pq.poll(); List<Integer> temp=new LinkedList<>(); temp.add(quad.x); temp.add(quad.y); ans.add(temp); } return ans; } void bfs(int[][] grid,int i,int j,int low,int high,PriorityQueue<Quad> pq) { Queue<int[]> queue=new LinkedList<>(); int m=grid.length,n=grid[0].length; if(grid[i][j]>=low&&grid[i][j]<=high) pq.add(new Quad(i,j,grid[i][j],0)); grid[i][j]=0; queue.add(new int[]{i,j}); int dist=0; int dirs[][]={{1,0},{-1,0},{0,1},{0,-1}}; while(!queue.isEmpty()) { ++dist; int size=queue.size(); while(size-->0) { int[] p=queue.poll(); for(int[] dir:dirs) { int newX=dir[0]+p[0]; int newY=dir[1]+p[1]; if(newX>=0&&newY>=0&&newX<m&&newY<n&&grid[newX][newY]!=0) { if(grid[newX][newY]>=low&&grid[newX][newY]<=high) pq.add(new Quad(newX,newY,grid[newX][newY],dist)); queue.add(new int[]{newX,newY}); grid[newX][newY]=0; } } } } } }
class Solution { public: struct cell { int dist; int cost; int row; int col; }; struct compare { bool operator()(const cell &a, const cell &b) { if(a.dist != b.dist) return a.dist < b.dist; else if(a.cost != b.cost) return a.cost < b.cost; else if(a.row != b.row) return a.row < b.row; else return a.col < b.col; } }; vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid, vector<int>& pricing, vector<int>& start, int k) { int m=grid.size(); int n=grid[0].size(); queue<pair<int,int>>q; q.push({start[0],start[1]}); vector<vector<bool>> vis(m,vector<bool>(n,false)); vis[start[0]][start[1]]=true; int dx[4]={-1,0,1,0}; int dy[4]={0,-1,0,1}; int dist=0; priority_queue<cell,vector<cell>,compare> pq; while(!q.empty()) { int size=q.size(); while(size--) { pair<int,int> p=q.front(); q.pop(); if(grid[p.first][p.second]!=1 && grid[p.first][p.second]>=pricing[0] && grid[p.first][p.second]<=pricing[1]) { pq.push({dist,grid[p.first][p.second],p.first,p.second}); if(pq.size()>k) pq.pop(); } for(int k=0;k<4;k++) { int x=p.first+dx[k]; int y=p.second+dy[k]; if(x>=0 && x<m && y>=0 && y<n && vis[x][y]==false && grid[x][y]!=0) { vis[x][y]=true; q.push({x,y}); } } } dist++; } vector<vector<int>> ans; while(!pq.empty()) { ans.push_back({pq.top().row,pq.top().col}); pq.pop(); } reverse(ans.begin(),ans.end()); return ans; } };
var highestRankedKItems = function(grid, pricing, start, k) { const m = grid.length; const n = grid[0].length; const dirs = [-1, 0, 1, 0, -1]; const visited = []; for (let i = 0; i < m; ++i) { visited[i] = new Array(n).fill(false); } const [low, high] = pricing; const queue = []; queue.push([...start, 0]); const items = []; while (queue.length > 0) { const [row, col, dist] = queue.shift(); if (visited[row][col]) continue; visited[row][col] = true; const price = grid[row][col]; if (withinRange(price, low, high)) { items.push({ dist, price, row, col }); } for (let i = 0; i < dirs.length - 1; ++i) { const neiRow = row + dirs[i]; const neiCol = col + dirs[i + 1]; if (withinBound(neiRow, neiCol) && !visited[neiRow][neiCol] && grid[neiRow][neiCol] != 0) { queue.push([neiRow, neiCol, dist + 1]); } } } items.sort(compareFunc); const res = []; for (let i = 0; i < Math.min(k, items.length); ++i) { const { dist, price, row, col } = items[i]; res.push([row, col]); } return res; function withinRange(price, low, high) { return low <= price && price <= high; } function withinBound(row, col) { return row >= 0 && col >= 0 && row < m && col < n; } function compareFunc(a, b) { return a.dist - b.dist || a.price - b.price || a.row - b.row || a.col - b.col; } };
K Highest Ranked Items Within a Price Range
You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". A word chain is a sequence of words [word1, word2, ..., wordk] with k &gt;= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words. &nbsp; Example 1: Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. Example 2: Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. Example 3: Input: words = ["abcd","dbqca"] Output: 1 Explanation: The trivial word chain ["abcd"] is one of the longest word chains. ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. &nbsp; Constraints: 1 &lt;= words.length &lt;= 1000 1 &lt;= words[i].length &lt;= 16 words[i] only consists of lowercase English letters.
class Solution: def longestStrChain(self, words: List[str]) -> int: words.sort(key=len) dic = {} for i in words: dic[ i ] = 1 for j in range(len(i)): # creating words by deleting a letter successor = i[:j] + i[j+1:] if successor in dic: dic[ i ] = max (dic[i], 1 + dic[successor]) res = max(dic.values()) return res
class Solution { Boolean compareForIncreaseByOne(String str1,String str2){ //str 1 will be long than str2 int first=0; int second=0; if(str1.length() != (str2.length() + 1)){ return false; } while(first < str1.length()){ if(second < str2.length() && str1.charAt(first) == str2.charAt(second)){ first++; second++; }else{ first++; } } if(first == str1.length() && second == str2.length()){ return true; } return false; } public int longestStrChain(String[] words) { int N = words.length; Arrays.sort(words,(a,b) -> a.length()-b.length()); //as Sequence/Subset are not ordered int []dp =new int[N]; Arrays.fill(dp,1); int maxi = 1; for(int i=0;i<N;i++){ for(int j=0;j<i;j++){ if(compareForIncreaseByOne(words[i],words[j]) && dp[j]+1 > dp[i]){ dp[i] = dp[j] + 1; maxi = Math.max(maxi,dp[i]); } } }//for neds return maxi; } }
class Solution { int dfs(unordered_map<string, int>& m, unordered_set<string>& setWords, const string& w) { if (m.count(w)) return m[w]; int maxLen = 1; for(int i=0;i<w.size();++i) { auto preWord = w.substr(0, i) + w.substr(i+1); if(setWords.count(preWord)) { int newLen = 1 + dfs(m, setWords, preWord); maxLen = max(newLen, maxLen); } } m[w] = maxLen; return maxLen; } public: int longestStrChain(vector<string>& words) { unordered_map<string, int> m; unordered_set<string> setWords(words.begin(), words.end()); int res = 0; for(auto& w:words) { res = max(res, dfs(m, setWords, w)); } return res; } };
/** * @param {string[]} words * @return {number} */ var longestStrChain = function(words) { let tiers = new Array(16); for(let i=0; i<tiers.length; i++) tiers[i] = []; for(let word of words) tiers[word.length-1].push({word,len:1}); const isPredecessor = function(word1,word2) // Assumes word2.length = word1.length+1 { let w1p = 0, misses = 0; for(let w2p = 0; w2p < word2.length; w2p++) { if(word2[w2p] !== word1[w1p]) { if(misses === 1) return false; misses = 1; } else { w1p++; if(w1p === word1.length) return true; } } return true; }; for(let i=tiers.length-1; i>0; i--) { for(let w2=0; w2<tiers[i].length; w2++) { for(let w1 = 0; w1 < tiers[i-1].length; w1++) { if(tiers[i-1][w1].len >= tiers[i][w2].len+1) continue; if(isPredecessor(tiers[i-1][w1].word, tiers[i][w2].word)) tiers[i-1][w1].len = tiers[i][w2].len+1; } } } let max = 0; for(let i=0; i<tiers.length; i++) { for(let j=0; j<tiers[i].length; j++) max = Math.max(max,tiers[i][j].len); } return max; };
Longest String Chain
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way. &nbsp; Example 1: Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: group1 [1,4] and group2 [2,3]. Example 2: Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Example 3: Input: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] Output: false &nbsp; Constraints: 1 &lt;= n &lt;= 2000 0 &lt;= dislikes.length &lt;= 104 dislikes[i].length == 2 1 &lt;= dislikes[i][j] &lt;= n ai &lt; bi All the pairs of dislikes are unique.
class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: def dfs(i, c): if color[i] != 0: if color[i] != c: return False return True color[i] = c for u in e[i]: if not dfs(u, 3 - c): return False return True e = [[] for _ in range(n)] for u, v in dislikes: u -= 1 v -= 1 e[u].append(v) e[v].append(u) color = [0] * n for i in range(n): if color[i] == 0: if not dfs(i, 1): return False return True
class Solution { int[] rank; int[] parent; int[] rival; public boolean possibleBipartition(int n, int[][] dislikes) { rank = new int[n+1]; rival = new int[n+1]; parent = new int[n+1]; for(int i = 1;i <= n;i++){ rank[i] = 1; parent[i] = i; } for(int[] dis : dislikes){ int x = dis[0], y = dis[1]; if(find(x) == find(y)) return false; if(rival[x] != 0) union(rival[x], y); else rival[x] = y; if(rival[y] != 0) union(rival[y], x); else rival[y] = x; } return true; } public int find(int x){ if(parent[x] == x) return x; return parent[x] = find(parent[x]); } public void union(int x, int y){ int x_set = find(x); int y_set = find(y); if(x_set == y_set) return; if(rank[x_set] < rank[y_set]) parent[x_set] = y_set; else if(rank[y_set] < rank[x_set]) parent[y_set] = x_set; else{ parent[x_set] = y_set; rank[y_set]++; } } }
class Solution { public: bool dfs(vector<int>adj[], vector<int>& color, int node){ for(auto it: adj[node]){ //dfs over adjacent nodes if(color[it]==-1){ //not visited yet color[it]=1-color[node]; //set different color of adjacent nodes if(!dfs(adj,color,it)) return false; } else if(color[it]!=1-color[node]) return false; //if adjacent nodes have same color } return true; } bool possibleBipartition(int n, vector<vector<int>>& dislikes) { vector<int>adj[n+1]; for(int i=0;i<dislikes.size();i++){//undirected graph adj[dislikes[i][0]].push_back(dislikes[i][1]); adj[dislikes[i][1]].push_back(dislikes[i][0]); } vector<int>color(n+1,-1); //-1 i.e. not visited yet for(int i=1;i<=n;i++){ if(color[i]==-1){ color[i]=0; if(!dfs(adj,color,i)) return false; } } return true; } };
var possibleBipartition = function(n, dislikes) { const g = new Map(); dislikes.forEach(([a, b]) => { const aDis = g.get(a) || []; const bDis = g.get(b) || []; g.set(a, aDis.concat(b)); g.set(b, bDis.concat(a)); }); const vis = new Array(n+1).fill(false); const col = new Array(n+1).fill(-1); const dfs = (n, c = 0) => { if(vis[n]) return true; col[n] = c; vis[n] = true; const nodes = g.get(n) || []; for(let node of nodes) { if(!vis[node]) { if(!dfs(node, 1 - c)) return false; } if(node != n && col[node] == c) return false; } return true; }; let canBi = true; for(let i = 1; i <= n; i++) { canBi &= dfs(i); } return canBi; };
Possible Bipartition
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i &lt; j) in the following way: During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] &lt;= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] &gt;= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j. It may be the case that for some index i, there are no legal jumps. A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices. &nbsp; Example 1: Input: arr = [10,13,12,14,15] Output: 2 Explanation: From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. Example 2: Input: arr = [2,3,1,1,4] Output: 3 Explanation: From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. Example 3: Input: arr = [5,1,3,4,2] Output: 3 Explanation: We can reach the end from starting indices 1, 2, and 4. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 2 * 104 0 &lt;= arr[i] &lt; 105
class Solution: def oddEvenJumps(self, arr: List[int]) -> int: l = len(arr) res = [False]*l res[-1] = True # for odd jump: for i, get next larger one odd_next = [i for i in range(l)] stack = [] # mono inc for ind for n, i in sorted([(arr[i], i) for i in range(l)]): while stack and stack[-1]<i: odd_next[stack.pop()] = i stack.append(i) # for even jump: for i, get next smaller one even_next = [i for i in range(l)] stack = [] # mono inc for ind for n, i in sorted([(-arr[i], i) for i in range(l)]): while stack and stack[-1]<i: even_next[stack.pop()] = i stack.append(i) # dp @lru_cache(None) def dp(i, odd): if i == l-1: return True ind = odd_next[i] if odd else even_next[i] if ind == i: return False return dp(ind, not odd) for i in range(l-1): res[i] = dp(i, True) return sum(res)
class Solution { public int oddEvenJumps(int[] arr) { int len = arr.length; int minjmp[] = new int[len]; int maxjmp[] = new int[len]; TreeMap<Integer, Integer> map = new TreeMap<>(); int evjmp, oddjmp; for(int i = len-1; i>=0; i--) { Integer minpos = map.floorKey(arr[i]); evjmp = (minpos != null)?map.get(minpos):len; //default len, to show not possible if(evjmp != len && (evjmp == len-1 || maxjmp[evjmp] == len-1)) evjmp = len-1; //check the last pos reachability Integer maxpos = map.ceilingKey(arr[i]); oddjmp = (maxpos != null) ? map.get(maxpos):len; if(oddjmp != len && (oddjmp == len-1 || minjmp[oddjmp] == len-1)) oddjmp = len-1;//check the last pos reachability minjmp[i] = evjmp; //specify possible jump path, if not possible assign len maxjmp[i] = oddjmp;//specify possible jump path, if not possible assign len map.put(arr[i],i); //put the current index } int res = 0; for(int i = 0; i< len-1; i++) { if(maxjmp[i] == len-1) res++; } return res+1; //since last position will always be the answer } }
class Solution { private: void tryOddJump(const int idx, const int val, std::map<int, int>& visitedNode, vector<int>& oddJumpsDP, vector<int>& evenJumpsDP) { // looking for equal or bigger element and it's going to be smallest posible auto jumpPoint = visitedNode.lower_bound(val); // If from jumpPoint exists even jump further, then odd jump will have some value if(jumpPoint != visitedNode.end()) oddJumpsDP[idx] = evenJumpsDP[jumpPoint->second]; } void tryEvenJump(const int idx, const int val, std::map<int, int>& visitedNode, vector<int>& oddJumpsDP, vector<int>& evenJumpsDP) { //looking for strictly bigger element because then I can be sure that previous will be equal or less that val for sure auto jumpPoint = visitedNode.upper_bound(val); // if it's first element, then there is no equal or less option, so no even jump possible if(jumpPoint != visitedNode.begin()) evenJumpsDP[idx] = oddJumpsDP[std::prev(jumpPoint)->second]; // (jumpPoint-1) check if further odd jump is possible from largest element that is <= val } public: int oddEvenJumps(vector<int>& arr) { const size_t n = arr.size(); vector<int> oddJumpsDP(n, 0); vector<int> evenJumpsDP(n, 0); oddJumpsDP[n-1] = 1; evenJumpsDP[n-1] = 1; std::map<int, int> visitedNode; visitedNode[arr[n-1]] = n-1; /* Idea is to move backward and keep track of posibility of odd and even jumps from each cell. This way at any jump we could check if further jumps is possible. Example 1: v arr = [10,13,12,14,15] odd = [ -, -, 0, 1, 1] even= [ -, -, -, 0, 1] Let's say we curently have answers for 14 and 15 and trying to work on 12: tryOddJump() -> will give us 14 as only possible odd jump(arr[i] <= arr[j] and arr[j] is the smallest possible value), but there is no EVEN jump from 14 further, so we cache odd jump for 12 as 0 as well. That's why I called thouse variables as oddJumpsDP/evenJumpsDP, they are caches for subproblems that helps in later computations. Without them we would need to check entire further path starting from each cell and it's not efficient. */ int res = 1; for(int i=n-2; i>=0; --i) { tryOddJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP); tryEvenJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP); // we alwayse start from 1st jump that is odd jump, so we can add index to the result if odd jump from it is possible if(oddJumpsDP[i] == 1) ++res; visitedNode[arr[i]] = i; } return res; } };
/** * @param {number[]} arr * @return {number} */ var oddEvenJumps = function(arr) { let result = 0; const len = arr.length const map = {} // { value: index } const memo = new Array(2).fill(null).map(i => new Array(len).fill(false)) // Build a BST to maintain logN search/Insert function treeNode(value) { this.val = value; this.left = null; this.right = null; } const root = new TreeNode(arr[len - 1]) function InsertToBST(val) { function dfs(node){ if(node.val < val) { if(!node.right) node.right = new TreeNode(val); else dfs(node.right); } if(node.val > val) { if(!node.left) node.left = new TreeNode(val); else dfs(node.left); } } dfs(root); } memo[0][len - 1] = memo[1][len - 1] = true; map[arr[len - 1]] = len - 1; //memo[0] odd jumps //memo[1] even jumps function getNextBig(base) { // odd jump if(map[base] !== undefined) { return base } let result = Infinity function dfs(node) { if(!node) return; if(node.val > base && node.val < result) { result = node.val; dfs(node.left) } if(node.val < base) { dfs(node.right); } } dfs(root) return result === Infinity ? false : result; } function getNextSmall(base) { //even jump if(map[base] !== undefined) { return base } let result = -Infinity function dfs(node) { if(!node) return; if(node.val < base && node.val > result) { result = node.val; dfs(node.right) } if(node.val > base) { dfs(node.left); } } dfs(root) return result === -Infinity ? false : result; } for(let i = len - 2; i >= 0; i--) { let nextBig = getNextBig(arr[i]) let nextSmall = getNextSmall(arr[i]) memo[0][i] = nextBig ? memo[1][map[nextBig]] : nextBig; memo[1][i] = nextSmall ? memo[0][map[nextSmall]] : nextSmall; map[arr[i]] = i; InsertToBST(arr[i]) } return memo[0].filter(boo => boo).length };
Odd Even Jump
Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced. &nbsp; Example 1: Input: s = "(()))" Output: 1 Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced. Example 2: Input: s = "())" Output: 0 Explanation: The string is already balanced. Example 3: Input: s = "))())(" Output: 3 Explanation: Add '(' to match the first '))', Add '))' to match the last '('. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s consists of '(' and ')' only.
class Solution: def minInsertions(self, s: str) -> int: leftbrackets = insertions = 0 i, n = 0, len(s) while i < n: if s[i] == '(': leftbrackets += 1 elif s[i] == ')': if i == n-1 or s[i+1] != ')': insertions += 1 else: i += 1 if not leftbrackets: insertions += 1 else: leftbrackets -= 1 i += 1 return leftbrackets * 2 + insertions
class Solution { public int minInsertions(String s) { int open=0; int ans=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ open++; } else{ if(i+1<s.length() && s.charAt(i+1)==')'){ i++; if(open>0){ open--; } else{ ans++; } } else{ if(open>0){ open--; ans++; } else{ ans+=2; } } } } ans+=2*open; return ans; } }
class Solution { public: int minInsertions(string s) { stack<int> st; int n = s.size(); int insert = 0; for(int i = 0; i < n; i++) { if(s[i] == '(') { if(st.empty()) { st.push(2); } else { if(st.top() != 2) { st.pop(); insert++; } st.push(2); } } else { if(st.empty()) { insert++; st.push(1); } else { int dummy = st.top(); st.pop(); dummy--; if(dummy) st.push(dummy); } } } while(!st.empty()) { insert += st.top(); st.pop(); } return insert; } };
var minInsertions = function(s) { let rightNeeded = 0; let leftNeeded = 0; for (const char of s) { if (char === "(") { if (rightNeeded % 2 === 0) { rightNeeded += 2; } else { rightNeeded++; leftNeeded++; } } else { rightNeeded--; if (rightNeeded === -1 ){ leftNeeded++; rightNeeded = 1; } } } return leftNeeded + rightNeeded; };
Minimum Insertions to Balance a Parentheses String
Reversing an integer means to reverse all its digits. For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. &nbsp; Example 1: Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num. Example 2: Input: num = 1800 Output: false Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num. Example 3: Input: num = 0 Output: true Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num. &nbsp; Constraints: 0 &lt;= num &lt;= 106
class Solution(object): def isSameAfterReversals(self, num): # All you have to do is check the Trailing zeros return num == 0 or num % 10 # num % 10 means num % 10 != 0
class Solution { public boolean isSameAfterReversals(int num) { return (num%10!=0||num<10); } }
class Solution { public: bool isSameAfterReversals(int num) { return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros } };
/** * @param {number} num * @return {boolean} */ var isSameAfterReversals = function(num) { if(num == 0) return true; if(num % 10 == 0) return false; return true; };
A Number After a Double Reversal
Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 &lt;= i &lt;= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. Return the string after making it good. The answer is guaranteed to be unique under the given constraints. Notice that an empty string is also good. &nbsp; Example 1: Input: s = "leEeetcode" Output: "leetcode" Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". Example 2: Input: s = "abBAcC" Output: "" Explanation: We have many possible scenarios, and all lead to the same answer. For example: "abBAcC" --&gt; "aAcC" --&gt; "cC" --&gt; "" "abBAcC" --&gt; "abBA" --&gt; "aA" --&gt; "" Example 3: Input: s = "s" Output: "s" &nbsp; Constraints: 1 &lt;= s.length &lt;= 100 s contains only lower and upper case English letters.
class Solution: def makeGood(self, s: str) -> str: while True: for i in range(len(s)-1): if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()): s = s[:i]+s[i+2:] break else: break return s
class Solution { public String makeGood(String s) { char[] res = s.toCharArray(); int i = 0; for( char n: s.toCharArray()) { res[i] = n; if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32) { i-=2; } i++; } return new String(res, 0, i); } }
class Solution { public: string makeGood(string s) { stack<char>st; st.push(s[0]); string ans=""; for(int i=1;i<s.size();++i){ if(!st.empty() and (st.top()==s[i]+32 or st.top()==s[i]-32)){ cout<<"top :"<<st.top()<<endl; st.pop(); } else { st.push(s[i]); } } while(!st.empty()){ // cout<<st.top()<<""; ans+=st.top(); st.pop(); } reverse(ans.begin(),ans.end()); return ans; } };
var makeGood = function(s) { const sArr = [] for(let i = 0; i < s.length; i++) { sArr.push(s[i]) } const popper = function() { let counter = 0 for(let i = 0; i < sArr.length; i++) { if(sArr[i] !== sArr[i + 1]) { if(sArr[i].toUpperCase() === sArr[i + 1] || sArr[i].toLowerCase() === sArr[i + 1]) { sArr.splice(i,2) counter++ } } } if(counter > 0) { popper() } } popper() return sArr.join(''); }; convert string to array to allow access to splice method. iterate over array checking for eqality between i and i +1 in the array. if equal, do nothing. if not equal convert to lower/uppercase and again check for equality. if equal splice those two from the array. counter checks if anything has been removed, if it has it iterates over the array again
Make The String Great
Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. &nbsp; Example 1: Input: s = "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. Example 2: Input: s = "10101" Output: 4 Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s[i] is either '0' or '1'.
class Solution: def countBinarySubstrings(self, s: str) -> int: # previous continuous occurrence, current continuous occurrence pre_cont_occ, cur_cont_occ = 0, 1 # counter for binary substrings with equal 0s and 1s counter = 0 # scan each character pair in s for idx in range(1, len(s)): if s[idx] == s[idx-1]: # update current continuous occurrence cur_cont_occ += 1 else: # update counter of binary substrings between prevous character group and current character group counter += min(pre_cont_occ, cur_cont_occ) # update previous as current's continuous occurrence pre_cont_occ = cur_cont_occ # reset current continuous occurrence to 1 cur_cont_occ = 1 # update for last time counter += min(pre_cont_occ, cur_cont_occ) return counter
class Solution { public int countBinarySubstrings(String s) { int i , prevRunLength = 0 , curRunLength = 1 , count = 0 ; for ( i = 1 ; i < s.length() ; i++ ) { if( s.charAt(i) == s.charAt( i - 1 ) ) { curRunLength++; } else { prevRunLength = curRunLength; curRunLength = 1; } if(prevRunLength >= curRunLength) { count++ ; } } return count ; } }
class Solution { public: int countBinarySubstrings(string s) { int prev=0; int curr=1; int sum=0; for(int i=1;i<s.length();i++){ if(s[i]==s[i-1]){ curr++; } else{ sum+= min(prev, curr); prev=curr; curr=1; } } sum+= min(prev, curr); return sum; } };
/** * find all bit switches '01' and '10'. * From each one expand sideways: i goes left, j goes right * Until: * if '01' -> i,j != 0,1 * if '10' -> i,j != 1,0 * and within input boundaries */ var countBinarySubstrings = function(s) { let i = 0; const n = s.length; let count = 0; while (i < n-1) { if (s[i] != s[i+1]) { if (s[i] === '0') { count += countZeroOnes(s, i, true); } else { count += countZeroOnes(s, i, false); } } i++; } return count; // count the number of valid substrings substrings function countZeroOnes(s, start, startsWithZero) { let count = 0; let i = start; let j = start+1; const n = s.length; if (startsWithZero) { while(i >= 0 && j < n && s[i] === '0' && s[j] === '1') { count++; i--; j++; } } else { while(i >= 0 && j < n && s[i] === '1' && s[j] === '0') { count++; i--; j++; } } return count; } }
Count Binary Substrings
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day. Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49". Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically. Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period. &nbsp; Example 1: Input: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"] Output: ["daniel"] Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00"). Example 2: Input: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"] Output: ["bob"] Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30"). &nbsp; Constraints: 1 &lt;= keyName.length, keyTime.length &lt;= 105 keyName.length == keyTime.length keyTime[i] is in the format "HH:MM". [keyName[i], keyTime[i]] is unique. 1 &lt;= keyName[i].length &lt;= 10 keyName[i] contains only lowercase English letters.
class Solution: # 668 ms, 99.52%. Time: O(NlogN). Space: O(N) def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]: def is_within_1hr(t1, t2): h1, m1 = t1.split(":") h2, m2 = t2.split(":") if int(h1) + 1 < int(h2): return False if h1 == h2: return True return m1 >= m2 records = collections.defaultdict(list) for name, time in zip(keyName, keyTime): records[name].append(time) rv = [] for person, record in records.items(): record.sort() # Loop through 2 values at a time and check if they are within 1 hour. if any(is_within_1hr(t1, t2) for t1, t2 in zip(record, record[2:])): rv.append(person) return sorted(rv)
class Solution { public List<String> alertNames(String[] keyName, String[] keyTime) { Map<String, PriorityQueue<Integer>> map = new HashMap<>(); // for every entry in keyName and keyTime, add that time to a priorityqueue for that name for(int i=0;i<keyName.length;i++){ PriorityQueue<Integer> pq = map.getOrDefault(keyName[i], new PriorityQueue<Integer>()); //convert the time to an integer (0- 2359 inclusive) for easy comparisons pq.add(Integer.parseInt(keyTime[i].substring(0,2))*100+Integer.parseInt(keyTime[i].substring(3))); map.put(keyName[i],pq); } // Generate the "answer" list List<String> ans = new ArrayList<>(); for(String s: map.keySet()){ // For each name in the map, determine if that name used the keycard within 1 hour PriorityQueue<Integer> pq = map.get(s); if(active(pq)){ ans.add(s); } } // Sort the names alphabetically Collections.sort(ans); return ans; } // Greedy function to determine if there were 3 uses within an hour private boolean active(PriorityQueue<Integer> pq){ // If there are two or less entries, the user could not have entered 3 times, return false if(pq.size()<3) return false; // Create rolling data // Using PriorityQueues, the lowest number is removed first by default int a = pq.poll(); int b = pq.poll(); int c = pq.poll(); // Test if two entrances are within 1 hour (100 in integer) if(c-a <=100) return true; while(pq.size()>0){ a = b; b = c; c = pq.poll(); if(c-a <=100) return true; } // If the full Queue has been checked, return false return false; } }
class Solution { public: bool timeDiff(vector<string> timestamp, int index){ int time1 = ((timestamp[index][0]-'0') * 10 + (timestamp[index][1]-'0')) * 60 + ((timestamp[index][3]-'0') * 10 + (timestamp[index][4]-'0')); int time2 = ((timestamp[index+2][0]-'0') * 10 + (timestamp[index+2][1]-'0')) * 60 + ((timestamp[index+2][3]-'0') * 10 + (timestamp[index+2][4]-'0')); if(abs(time2-time1)<=60) return true; return false; } vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) { unordered_map<string, vector<string>> ht; for(int i=0; i<keyName.size(); i++) ht[keyName[i]].push_back(keyTime[i]); vector<string> result; for(auto time : ht){ sort(time.second.begin(), time.second.end()); for(int i=0; i+2<time.second.size(); i++) if(timeDiff(time.second, i)){ result.push_back(time.first); break; } } sort(result.begin(), result.end()); return result; } }; /* Algorithm Outline 1. store in HT as vector 2. Check for each, 1st & 3rd in range. True if Yes */
/** * @param {string[]} keyName * @param {string[]} keyTime * @return {string[]} */ var alertNames = function(keyName, keyTime) { // so we don't keep duplicates const abusers = new Set(); // map: name->times[] (sorted) const times = {}; for (let i=0; i<keyName.length; i++) { const name = keyName[i]; const time = keyTime[i]; if (times[name] == null) times[name] = []; times[name].push(time); if (times[name].length > 2) { times[name].sort(); const len = times[name].length; // we check all triples for a time difference below 1 hour. // as times are sorted, we need to check all i and i+2 for (let i=0; i<len-2; i++) { if (belowHour(times[name][i], times[name][i+2])) { abusers.add(name); } } } } const ar = Array.from(abusers); // sort them lexicographically ar.sort(); return ar; /* same hour: true hour diff is above 1: false hour diff is 1: m2 must be <= m1 */ function belowHour(t1, t2) { const [h1, m1] = t1.split(':').map(num => parseInt(num)); const [h2, m2] = t2.split(':').map(num => parseInt(num)); if (h1 === h2) return true; if (h2-h1 > 1) return false; if (m2 <= m1) return true; } };
Alert Using Same Key-Card Three or More Times in a One Hour Period
Given 2 integers n and start. Your task is return any permutation p&nbsp;of (0,1,2.....,2^n -1) such that : p[0] = start p[i] and p[i+1]&nbsp;differ by only one bit in their binary representation. p[0] and p[2^n -1]&nbsp;must also differ by only one bit in their binary representation. &nbsp; Example 1: Input: n = 2, start = 3 Output: [3,2,0,1] Explanation: The binary representation of the permutation is (11,10,00,01). All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2] Example 2: Input: n = 3, start = 2 Output: [2,6,7,5,4,0,1,3] Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011). &nbsp; Constraints: 1 &lt;= n &lt;= 16 0 &lt;= start&nbsp;&lt;&nbsp;2 ^ n
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: gray_code = [x ^ (x >> 1) for x in range(2 ** n)] start_i = gray_code.index(start) return gray_code[start_i:] + gray_code[:start_i]
class Solution { public List<Integer> circularPermutation(int n, int start) { List<Integer> l = new ArrayList<Integer>(); int i=0; int len = (int)Math.pow(2,n); int[] arr = new int[len]; while(i<len){ arr[i]=(i)^(i/2); i++; } i=0; while(arr[i]!=start)i++; while(i<arr.length){ l.add(arr[i]); i++; } i=0; while(i<arr.length && arr[i]!=start){ l.add(arr[i]); i++; } return l; } }
class Solution { public: vector<string> get_val(int n) { if(n==1)return {"0","1"}; vector<string> v = get_val(n-1); vector<string> ans; for(int i = 0;i<v.size();i++) { ans.push_back("0" + v[i]); } for(int i = v.size()-1;i>=0;i--) { ans.push_back("1" + v[i]); } return ans; } vector<int> solve(int n) { vector<string> v = get_val(n); vector<int> ans; for(int i = 0;i<v.size();i++) { string s = v[i]; int x = 0; for(int j = 0;j<s.size();j++) { x = x*2 + s[j]-'0'; } ans.push_back(x); } return ans; } vector<int> circularPermutation(int n, int start) { vector<int> v = solve(n); int ind; for(int i = 0;i<v.size();i++) { if(v[i]==start) { ind = i; break; } } vector<int> ans; for(int i = ind;i<v.size();i++) { ans.push_back(v[i]); } for(int i = 0;i<ind;i++) { ans.push_back(v[i]); } return ans; } };
var circularPermutation = function(n, start) { const grayCodes = []; let startIdx = -1; for (let i = 0; i <= 2**n - 1; i++) { grayCodes[i] = i ^ (i >> 1); if (grayCodes[i] == start) startIdx = i; } const res = []; for (let i = 0; i <= 2**n - 1; i++) { res[i] = grayCodes[startIdx]; startIdx++; if (startIdx == grayCodes.length) startIdx = 0; } return res; };
Circular Permutation in Binary Representation
You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers. 1 &lt;= arr[i] &lt;= m where (0 &lt;= i &lt; n). After applying the mentioned algorithm to arr, the value search_cost is equal to k. Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7. &nbsp; Example 1: Input: n = 2, m = 3, k = 1 Output: 6 Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] Example 2: Input: n = 5, m = 2, k = 3 Output: 0 Explanation: There are no possible arrays that satisify the mentioned conditions. Example 3: Input: n = 9, m = 1, k = 1 Output: 1 Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1] &nbsp; Constraints: 1 &lt;= n &lt;= 50 1 &lt;= m &lt;= 100 0 &lt;= k &lt;= n
class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: @cache def dp(a,b,c): if a==n: return c==k return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1)) return dp(0,0,0)%(10**9+7)
class Solution { public int numOfArrays(int n, int m, int k) { int M = (int)1e9+7, ans = 0; int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side for (int i = 1; i <= m; i++){ dp[i][1]=1; // base case } for (int i = 2; i <= n; i++){ int[][] next = new int[m+1][k+1]; for (int j = 1; j <= m; j++){ // for the current max value for (int p = 1; p <= m; p++){ // previous max value for (int w = 1; w <= k; w++){ // for all possible k if (j>p){ // if current max is larger, update next[j][w] from dp[p][w-1] next[j][w]+=dp[p][w-1]; next[j][w]%=M; }else{ // otherwise, update next[p][w] from dp[p][w] next[p][w]+=dp[p][w]; next[p][w]%=M; } } } } dp=next; } for (int i = 1; i <= m; i++){ // loop through max that has k and sum them up. ans += dp[i][k]; ans %= M; } return ans; } }
class Solution { public: int numOfArrays(int n, int m, int k) { if(m<k)return 0; int dp[2][m+1][k+1],mod=1e9+7; memset(dp,0,sizeof(dp)); for(int j=1;j<=m;++j) dp[0][j][1]=j; for(int i=1;i<n;++i) for(int j=1;j<=m;++j) for(int l=1;l<=min(i+1,min(j,k));++l) dp[i&1][j][l]=(dp[i&1][j-1][l]+(long)(dp[(i-1)&1][j][l]-dp[(i-1)&1][j-1][l])*j+dp[(i-1)&1][j-1][l-1])%mod; return (dp[(n-1)&1][m][k]+mod)%mod; } };
var numOfArrays = function(n, m, k){ let mod=1e9+7, // dp[i][c][j] the number of arrays of length i that cost c and their max element is j dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0))), // prefix[i][k][j] holds the prefix sum of dp[i][k][:j] prefix=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0))) //basecases dp[0][0][0] = 1 prefix[0][0].fill(1) for(var i = 1; i <= n; i++) //length of array for(var x = 1; x <= k; x++) //curcost for(var j = 1; j <= m; j++) //curmax // the previous max can be anything <j with a cost of x-1, to which we append j dp[i][x][j] += prefix[i-1][x-1][j-1], // we can also append any number <=j to an array of length i-1 that already costs x, //therefore not increasing the cost dp[i][x][j] += dp[i - 1][x][j] *j , dp[i][x][j] %= mod, prefix[i][x][j]=(prefix[i][x][j-1]+dp[i][x][j])%mod return dp[n][k].reduce((a,c)=>(a+c)%mod) };
Build Array Where You Can Find The Maximum Exactly K Comparisons
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally. &nbsp; Example 1: Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 43 Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1]. - The road (0,1) has an importance of 2 + 4 = 6. - The road (1,2) has an importance of 4 + 5 = 9. - The road (2,3) has an importance of 5 + 3 = 8. - The road (0,2) has an importance of 2 + 5 = 7. - The road (1,3) has an importance of 4 + 3 = 7. - The road (2,4) has an importance of 5 + 1 = 6. The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43. It can be shown that we cannot obtain a greater total importance than 43. Example 2: Input: n = 5, roads = [[0,3],[2,4],[1,3]] Output: 20 Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1]. - The road (0,3) has an importance of 4 + 5 = 9. - The road (2,4) has an importance of 2 + 1 = 3. - The road (1,3) has an importance of 3 + 5 = 8. The total importance of all roads is 9 + 3 + 8 = 20. It can be shown that we cannot obtain a greater total importance than 20. &nbsp; Constraints: 2 &lt;= n &lt;= 5 * 104 1 &lt;= roads.length &lt;= 5 * 104 roads[i].length == 2 0 &lt;= ai, bi &lt;= n - 1 ai != bi There are no duplicate roads.
class Solution: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: Arr = [0] * n # i-th city has Arr[i] roads for A,B in roads: Arr[A] += 1 # Each road increase the road count Arr[B] += 1 Arr.sort() # Cities with most road should receive the most score summ = 0 for i in range(len(Arr)): summ += Arr[i] * (i+1) # Multiply city roads with corresponding score return summ
class Solution { public long maximumImportance(int n, int[][] roads) { long ans = 0, x = 1; long degree[] = new long[n]; for(int road[] : roads){ degree[road[0]]++; degree[road[1]]++; } Arrays.sort(degree); for(long i : degree) ans += i * (x++) ; return ans; } }
class Solution { public: long long maximumImportance(int n, vector<vector<int>>& roads) { vector<int>ind(n,0); for(auto it:roads) { ind[it[0]]++; ind[it[1]]++; } priority_queue<long long> pq; long long val = n,ans=0; for(int i=0;i<n;i++) pq.push(ind[i]); while(!pq.empty()) { ans += pq.top() * val; val--; pq.pop(); } return ans; } };
var maximumImportance = function(n, roads) { const connectionCount = Array(n).fill(0) // Count the connections from each city // e.g. the 0th city's count will be stored at index zero in the array for (let [cityTo, cityFrom] of roads) { connectionCount[cityTo]++ connectionCount[cityFrom]++ } let cityToConnectionCount = [] for (let city = 0; city < n; city++) { cityToConnectionCount.push([city, connectionCount[city]])// Store the [city, numberOfConnections] } // Created new array(sortedCities) for readability const sortedCities = cityToConnectionCount.sort((a,b) => b[1] - a[1])// sort by number of connections, the city with the greatest number of connections should be // the city with the greatest importance const values = Array(n).fill(0) let importance = n for (let i = 0; i < sortedCities.length; i++) { const [city, connectionCount] = cityToConnectionCount[i] values[city] = importance// City at the 0th position array is should be the city with the greatest importance importance-- } // Sum the importance of each city, toCity => fromCity let res = 0 for (let [to, from] of roads) { res += values[to] + values[from] } return res };```
Maximum Total Importance of Roads
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed). Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table. &nbsp; Example 1: Input: m = 3, n = 3, k = 5 Output: 3 Explanation: The 5th smallest number is 3. Example 2: Input: m = 2, n = 3, k = 6 Output: 6 Explanation: The 6th smallest number is 6. &nbsp; Constraints: 1 &lt;= m, n &lt;= 3 * 104 1 &lt;= k &lt;= m * n
class Solution: def numSmaller(self, x, m, n): res = 0 for i in range(1, m + 1): res += min(x // i, n) return res def findKthNumber(self, m: int, n: int, k: int) -> int: beg = 1 end = m * n while beg < end: mid = (beg + end) // 2 curr = self.numSmaller(mid, m, n) if curr < k: beg = mid + 1 else: end = mid return beg
class Solution { public int findKthNumber(int m, int n, int k) { int lo = 1; int hi = m * n; while(lo < hi){ int mid = lo + (hi - lo) / 2; if(count(mid, m, n) < k){ lo = mid + 1; } else if(count(mid, m, n) >= k){ hi = mid; } } return lo; } private int count(int mid, int m, int n){ int ans = 0; for(int i = 1; i <= m; i++){ int res = Math.min(mid / i, n); ans += res; } return ans; } }
class Solution { public: int findKthNumber(int m, int n, int k) { int high=m*n ,low=1; int mid=0, ans=1e9; while(low<=high) { mid=low+(high-low)/2; int temp=0; // for each i find the max value ,less than or equal to n , such that // i*j<=mid // add j to answer for(int i=1;i<=m;i++) temp+=min(mid/i,n); if(temp>=k) { ans=min(ans,mid); high=mid-1; } else low=mid+1; } return ans; } };
/** * @param {number} m * @param {number} n * @param {number} k * @return {number} */ var findKthNumber = function(m, n, k) { // lo always points to a value which is // not going to be our answer let lo = 0; let hi = m * n; // the loop stops when lo and hi point to two adjascent numbers // because lo is always incorrect, hi will contain our final answer while (lo + 1 < hi) { // As a general practice don't do a (lo + hi) / 2 because that // might cause integer overflow const mid = lo + Math.floor((hi - lo) / 2); const count = countLessThanEqual(mid, m, n); // Find the minimum mid, such that count >= k if (count >= k) { hi = mid; } else { lo = mid; } } return hi; }; function countLessThanEqual(target, rows, cols) { let count = 0; // we move row by row in the multiplication table // Each row contains at max (target / rowIndex) elements less than // or equal to target. The number of cols would limit it though. for (let i = 1; i <= rows; i++) { count += Math.min(Math.floor(target / i), cols); } return count; }
Kth Smallest Number in Multiplication Table
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). &nbsp; Example 1: Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2: Input: prices = [1] Output: 0 &nbsp; Constraints: 1 &lt;= prices.length &lt;= 5000 0 &lt;= prices[i] &lt;= 1000
class Solution: def maxProfit(self, prices: List[int]) -> int: cache = {} def dfs(i, buying): if i >= len(prices): return 0 if (i, buying) in cache: return cache[(i, buying)] if buying: # if have sell the share in previous step # then currently we have two options # either buy or not buy(cooldown) # we have bought so, increment the index and set buying flag to not buying # and don't forget that we bought so, we have to reduce that share amount from profit buy = dfs(i+1, not buying) - prices[i] cooldown = dfs(i+1, buying) profit = max( buy, cooldown ) cache[(i, buying)] = profit else: # we have sell the share so, # we cannot buy next share we have to skip the next price(cooldown for one day) # set (not buying) flag to buying # we also have to add that share price to profit sell = dfs(i+2, not buying) + prices[i] cooldown = dfs(i+1, buying) profit = max( sell, cooldown ) cache[(i, buying)] = profit return cache[(i, buying)] return dfs(0, True)
class Solution { public int maxProfit(int[] prices) { int n = prices.length; int[][] dp = new int[n+2][2]; for(int index = n-1; index>=0; index--){ for(int buy = 0; buy<=1; buy++){ int profit = 0; if(buy == 0){ // buy stocks profit = Math.max(-prices[index] + dp[index+1][1], 0 + dp[index+1][0]); } if(buy == 1){ // we can sell stocks profit = Math.max(prices[index] + dp[index+2][0], 0 + dp[index+1][1]); } dp[index][buy] = profit; } } return dp[0][0]; } }
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); int ans = 0; vector<int> dp(n, 0); for (int i = 1; i < n; ++i) { int max_dp = 0; for (int j = 0; j < i; ++j) { dp[i] = max(dp[i], prices[i] - prices[j] + max_dp); max_dp = max(max_dp, j > 0 ? dp[j - 1] : 0); } ans = max(ans, dp[i]); } return ans; } };
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { let dp = {}; let recursiveProfit = (index,buy) =>{ if(index>=prices.length){ return 0; } if(dp[index+'_'+buy]) return dp[index+'_'+buy] if(buy){ dp[index+'_'+buy] = Math.max(-prices[index]+recursiveProfit(index+1,0), 0+recursiveProfit(index+1,1)) return dp[index+'_'+buy]; } else{ dp[index+'_'+buy]= Math.max(prices[index]+recursiveProfit(index+2,1),0+recursiveProfit(index+1,0)) return dp[index+'_'+buy]; } } return recursiveProfit(0,1); };
Best Time to Buy and Sell Stock with Cooldown
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. &nbsp; Example 1: Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False &nbsp; Constraints: 1 &lt;= x &lt;= 9 At most 100 calls will be made to push, pop, top, and empty. All the calls to pop and top are valid. &nbsp; Follow-up: Can you implement the stack using only one queue?
class MyStack: def __init__(self): self.q1 = deque() self.q2 = deque() def push(self, x: int) -> None: self.q1.append(x) def pop(self) -> int: while len(self.q1) > 1: self.q2.append(self.q1.popleft()) popped_element = self.q1.popleft() # Swap q1 and q2 self.q1, self.q2 = self.q2, self.q1 return popped_element def top(self) -> int: while len(self.q1) > 1: self.q2.append(self.q1.popleft()) top_element = self.q1[0] self.q2.append(self.q1.popleft()) # Swap q1 and q2 self.q1, self.q2 = self.q2, self.q1 return top_element def empty(self) -> bool: return len(self.q1) == 0
class MyStack { Queue<Integer> queue = null; public MyStack() { queue = new LinkedList<>(); } public void push(int x) { Queue<Integer> tempQueue = new LinkedList<>(); tempQueue.add(x); while(!queue.isEmpty()){ tempQueue.add(queue.remove()); } queue = tempQueue; } public int pop() { return queue.remove(); } public int top() { return queue.peek(); } public boolean empty() { return queue.isEmpty(); } }
class MyStack { public: queue<int> q1; queue<int> q2; MyStack() { } void push(int x) { q1.push(x); } int pop() { while(q1.size() !=1){ int temp = q1.front(); q1.pop(); q2.push(temp); } int temp = q1.front(); q1.pop(); while(!q2.empty()){ int tp = q2.front(); q2.pop(); q1.push(tp); } return temp; } int top() { while(q1.size() !=1){ int temp = q1.front(); q1.pop(); q2.push(temp); } int temp = q1.front(); q1.pop(); q2.push(temp); while(!q2.empty()){ int tp = q2.front(); q2.pop(); q1.push(tp); } return temp; } bool empty() { if(q1.empty()){ return true; } return false; } }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */
var MyStack = function() { this.stack = []; }; /** * @param {number} x * @return {void} */ MyStack.prototype.push = function(x) { this.stack.push(x); }; /** * @return {number} */ MyStack.prototype.pop = function() { return this.stack.splice([this.stack.length-1], 1) }; /** * @return {number} */ MyStack.prototype.top = function() { return this.stack[this.stack.length-1] }; /** * @return {boolean} */ MyStack.prototype.empty = function() { return this.stack.length === 0 ? true : false; }; /** * Your MyStack object will be instantiated and called as such: * var obj = new MyStack() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.top() * var param_4 = obj.empty() */
Implement Stack using Queues
Given the root of a binary tree, return the leftmost value in the last row of the tree. &nbsp; Example 1: Input: root = [2,1,3] Output: 1 Example 2: Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7 &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. -231 &lt;= Node.val &lt;= 231 - 1
# 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int: res = root.val stack = [(0, root)] prev_d = 0 while stack: curr_d, curr_v = stack.pop(0) if curr_v.left: stack.append((curr_d+1, curr_v.left)) if prev_d != curr_d + 1: res = curr_v.left.val prev_d = curr_d+1 if curr_v.right: stack.append((curr_d+1, curr_v.right)) if prev_d != curr_d + 1: res = curr_v.right.val prev_d = curr_d+1 return res # An Upvote will be encouraging
class Solution { int max = Integer.MIN_VALUE; int res = -1; public int findBottomLeftValue(TreeNode root) { check(root,0); return res; } void check(TreeNode root, int h){ if(root==null) return; if(h>max){ max=h; res = root.val; } check(root.left,h+1); check(root.right,h+1); } }
class Solution { public: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q; q.push(root); int ans=root->val; while(!q.empty()){ int n=q.size(); for(int i=0;i<n;i++){ TreeNode* curr= q.front(); q.pop(); if(i==0) ans=curr->val; if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } } return ans; } };
var findBottomLeftValue = function(root) { let arr=[]; let q=[root]; while(q.length!==0){ let current=q.shift(); arr.push(current.val) if(current.right){ q.push(current.right) } if(current.left){ q.push(current.left); } } return arr[arr.length-1] };
Find Bottom Left Tree Value
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. &nbsp; Example 1: Input: left = 5, right = 7 Output: 4 Example 2: Input: left = 0, right = 0 Output: 0 Example 3: Input: left = 1, right = 2147483647 Output: 0 &nbsp; Constraints: 0 &lt;= left &lt;= right &lt;= 231 - 1
class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: if not left: return 0 i = 0 cur = left while cur + (cur & -cur) <= right: cur += cur & -cur left &= cur return left
class Solution { public int rangeBitwiseAnd(int left, int right) { int count=0; while(left!=right){ left>>=1; right>>=1; count++; } return right<<=count; }
class Solution { public: int rangeBitwiseAnd(int left, int right) { int t=0; while(left!=right){ left= left>>1; right= right>>1; t++; } int ans= left; while(t--){ ans= ans<<1; } return ans; } };
var rangeBitwiseAnd = function(left, right) { const a = left.toString(2); const b = right.toString(2); if (a.length !== b.length) { return 0; } let match = 0; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { break; } match++; } return parseInt(b.substring(0, match).padEnd(b.length, '0'), 2); };
Bitwise AND of Numbers Range
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note:&nbsp;A leaf is a node with no children. &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5 &nbsp; Constraints: The number of nodes in the tree is in the range [0, 105]. -1000 &lt;= Node.val &lt;= 1000
class Solution(object): def minDepth(self, root): # Base case... # If the subtree is empty i.e. root is NULL, return depth as 0... if root is None: return 0 # Initialize the depth of two subtrees... leftDepth = self.minDepth(root.left) rightDepth = self.minDepth(root.right) # If the both subtrees are empty... if root.left is None and root.right is None: return 1 # If the left subtree is empty, return the depth of right subtree after adding 1 to it... if root.left is None: return 1 + rightDepth # If the right subtree is empty, return the depth of left subtree after adding 1 to it... if root.right is None: return 1 + leftDepth # When the two child function return its depth... # Pick the minimum out of these two subtrees and return this value after adding 1 to it... return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); if(root.left == null) return right+1; if(root.right == null) return left+1; return Math.min(left, right)+1; } }
class Solution { public: void maxlevel(TreeNode* root,int level,int &ans){ if(!root) return ; if(!root->left && !root->right){ ans=min(level,ans); return ; } maxlevel(root->left,level+1,ans); maxlevel(root->right,level+1,ans); } int minDepth(TreeNode* root) { if(!root) return 0; int ans=INT_MAX; maxlevel(root,0,ans); return ans+1; } };
var minDepth = function(root) { if (!root){ return 0 } if(root.left && root.right){ return Math.min(minDepth(root.left), minDepth(root.right)) + 1 } if(root.right){ return minDepth(root.right) + 1 } if(root.left){ return minDepth(root.left) + 1 } return 1 };
Minimum Depth of Binary Tree
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in&nbsp;O(n)&nbsp;time and uses O(1) extra space.&nbsp; &nbsp; Example 1: Input: n = 13 Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] Example 2: Input: n = 2 Output: [1,2] &nbsp; Constraints: 1 &lt;= n &lt;= 5 * 104
class Solution: def lexicalOrder(self, n: int) -> List[int]: result = [] orderDic = {} for i in range(1, n + 1): strI = str(i) level = orderDic for char in strI: if char not in level: level[char] = {} level = level[char] self.traverse(orderDic, "", result) return result def traverse(self, dic, temp, result): for key in dic: result.append(int(temp + key)) self.traverse(dic[key], temp + key, result)
class Solution { private final TrieNode trie = new TrieNode(' '); class TrieNode{ private Character digit; private String value; private boolean isWord; private Map<Character, TrieNode> children; TrieNode(Character c){ this.digit = c; this.isWord = false; this.children = new HashMap<>(); } void insert(String s){ TrieNode current = this; for(Character c : s.toCharArray()){ current = current.children.computeIfAbsent(c, k -> new TrieNode(c)); } current.value = s; current.isWord = true; } List<Integer> getWordsPreOrder(){ return getWordsPreOrder(this); } private List<Integer> getWordsPreOrder(TrieNode root){ List<Integer> result = new ArrayList<>(); if(root == null){ return result; } if(root.isWord){ result.add(Integer.parseInt(root.value)); } for(TrieNode node : root.children.values()){ result.addAll(getWordsPreOrder(node)); } return result; } } public List<Integer> lexicalOrder(int n) { for(int i = 1 ; i<=n;i++){ trie.insert(String.valueOf(i)); } return trie.getWordsPreOrder(); } }
class Solution { private: void dfs(int i, int n, vector<int> &ans){ if(i > n) return; ans.push_back(i); for(int j = 0; j< 10; ++j) dfs(i * 10 + j, n, ans); } public: vector<int> lexicalOrder(int n) { vector<int> ans; for(int i =1; i<10; ++i) dfs(i, n, ans); return ans; } };
/** * @param {number} n * @return {number[]} */ var lexicalOrder = function(n) { const arr = []; function dfs(baseIndex) { if (baseIndex * 10 > n) { return; } for(let i = baseIndex * 10; i < baseIndex * 10 + 10 && i <= n; i++) { arr.push(i); dfs(i); } } let stack = []; for(let i = 1; i <= 9 && i <= n; i++) { arr.push(i); dfs(i); } return arr; };
Lexicographical Numbers
Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. &nbsp; Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 2500 -104 &lt;= nums[i] &lt;= 104 &nbsp; Follow up:&nbsp;Can you come up with an algorithm that runs in&nbsp;O(n log(n)) time complexity?
class Solution: def lengthOfLIS(self, nums: list[int]) -> int: # Initialize the result res = [] # Binary search to find the index of the smallest number in result that is greater than or equal to the target def binarySearch(l, r, target): nonlocal res # If the left and right pointers meet, we have found the smallest number that is greater than the target if l == r: return l # Find the mid pointer m = (r - l) // 2 + l # If the number at the mid pointer is equal to the target, we have found a number that is equal to the target if res[m] == target: return m # Else if the number at the mid poitner is less than the target, we search the right side elif res[m] < target: return binarySearch(m + 1, r, target) # Else, we search the left side including the number at mid pointer because it is one of the possible solution since it is greater than the target else: return binarySearch(l, m, target) # Iterate through all numbers for n in nums: # If the last number in the result is less than the current number if not res or res[-1] < n: # Append the current number to the result res.append(n) continue # Else, find the index of the smallest number in the result that is greater than or equal to the current number i = binarySearch(0, len(res) - 1, n) # Replace the current number at such index res[i] = n return len(res)
class Solution { public int lengthOfLIS(int[] nums) { ArrayList<Integer> lis = new ArrayList<>(); for(int num:nums){ int size = lis.size(); if(size==0 ||size>0 && num>lis.get(size-1)){ lis.add(num); }else{ int insertIndex = bs(lis,num); lis.set(insertIndex,num); } } return lis.size(); } int bs(List<Integer> list, int target){ int lo = 0; int hi = list.size()-1; while(lo<hi){ int mid = (lo+hi)/2; if(list.get(mid)<target){ lo=mid+1; }else{ hi=mid; } } return lo; } }
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); vector<int>dp(n,1); for(int i=n-2;i>=0;i--){ for(int j=i+1;j<n;j++){ if(nums[j]>nums[i])dp[i]=max(dp[i],1+dp[j]); } } int mx=0; for(int i=0;i<n;i++)mx=max(mx,dp[i]); return mx; } };
var lengthOfLIS = function(nums) { let len = nums.length; let dp = Array.from({length: len}, v => 1); for (let i = 1 ; i < len; i++) { for (let j = 0; j < i; j++) { if (nums[i] > nums[j] && dp[i] <= dp[j]) { dp[i] = dp[j] + 1; } } } return Math.max(...dp); };
Longest Increasing Subsequence
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. &nbsp; Example 1: Input: nums = [10,5,2,6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. Example 2: Input: nums = [1,2,3], k = 0 Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 3 * 104 1 &lt;= nums[i] &lt;= 1000 0 &lt;= k &lt;= 106
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k==0 or k==1: return 0 p=1 ini=0 fin=0 n=len(nums) c=0 while fin<n: p=p*nums[fin] while p>=k : p=p//nums[ini] ini+=1 n1=fin-ini+1 c+=n1 fin+=1 return c
class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { //if k=0 then ans will always be zero as we have positive integers array only. if(k==0) return 0; int length = 0; long product = 1; int i = 0; int j = 0; int n = nums.length; int ans = 0; while(j<n){ product*=nums[j]; //Add the number to current window if the product is less than k and calculate no of subarrays using length only. if(product<k){ length+=1; ans+=length; } else{ //Remove element one by one till product becomes less than k. while(i<=j && product>=k){ product/=nums[i]; i++; } //As we have added only 1 element to the window and this element can make subarray to j-i element along with itself. ans+=(j-i)+1; //Update the current subarray length. length=j-i+1; } j++; } return ans; } }
class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { int start = 0; long prod = 1; int count =0; // count of subarray prod less than k for(int end =0; end< nums.size(); end++){ prod *= nums[end]; while(prod >= k && start < nums.size()){ prod = prod/nums[start];// divide product by nums at start pointer t reduce the prod start++;//move start pointer because no longer nums at start can give us prod < k } if(prod < k) count += end - start +1; } return count; } };
var numSubarrayProductLessThanK = function(nums, k) { var used = new Array(nums.length).fill(0); var l, r, runsum=1; let ans=0; l = 0; r = 0; while( r < nums.length ) { if( r < nums.length && runsum * nums[r] >= k ) { if( r != l ) runsum /= nums[l]; else r++; l++; } else if( l <= r ) { runsum *= nums[r]; r++; ans += (r-l); } else break; } return ans; };
Subarray Product Less Than K
Given two non-negative integers low and high. Return the count of odd numbers between low and high&nbsp;(inclusive). &nbsp; Example 1: Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7]. Example 2: Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9]. &nbsp; Constraints: 0 &lt;= low &lt;= high&nbsp;&lt;= 10^9
class Solution: def countOdds(self, low: int, high: int) -> int: total_nums = high - low answer = total_nums // 2 if low % 2 == 1 and high % 2 == 1: return answer + 1 if low % 2 == 1: answer = answer + 1 if high % 2 == 1: answer = answer + 1 return answer
class Solution { public int countOdds(int low, int high) { if(low%2==0 && high%2==0){ return (high-low)/2; } return (high-low)/2+1; } }
class Solution { public: int countOdds(int low, int high) { if (low%2 == 0 && high%2 == 0 ){ return (high - low)/2; } else{ return (high - low)/2 + 1; } } };
var countOdds = function(low, high) { let total = 0; for (let i = low; i <= high; i++) { if (i % 2 !== 0) { total++; } } return total; };
Count Odd Numbers in an Interval Range
There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen. &nbsp; Example 1: Input: n = 3 Output: 3 Explanation: Initially, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'. Example 2: Input: n = 1 Output: 0 &nbsp; Constraints: 1 &lt;= n &lt;= 1000
class Solution: def minSteps(self, n: int) -> int: # at every step we can copy or paste # paste -> we need to know the current clipboard content (count) # copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste) memo = {} def dfs(clipboard_count, screen_count): if (clipboard_count, screen_count) in memo: return memo[(clipboard_count, screen_count)] # we reached n, this is a valid option if screen_count == n: return 0 # we passed n, not a valid option if screen_count > n: return float('inf') # paste or copy copy_opt = paste_opt = float('inf') # we should only paste if clipboard is not empty if clipboard_count > 0: paste_opt = dfs(clipboard_count, screen_count + clipboard_count) # we should consider copy only if the last operation was paste if screen_count > clipboard_count: copy_opt = dfs(screen_count, screen_count) # save to memo memo[(clipboard_count, screen_count)] = 1 + min(paste_opt, copy_opt) return memo[(clipboard_count, screen_count)] return dfs(0, 1)
class Solution { public int minSteps(int n) { int rem = n-1, copied = 0, ans = 0, onScreen = 1; while(rem>0){ if(rem % onScreen == 0){ ans++; // copy operation copied = onScreen; } rem-=copied; ans++; // paste operation onScreen = n-rem; // no. of characters on screen currently that can be copied in next copy operation } return ans; } }
class Solution { public: //See the solution for this explanation int byPrimeFactorization(int n) { if(n == 1) return 0; if(n == 2) return 2; int factor = 2, ans = 0; while(n > 1) { while(n % factor == 0) { ans += factor; n /= factor; } factor++; } return ans; } int byDp(int n) { vector<int> dp(1001, INT_MAX); dp[0] = dp[1] = 0; dp[2] = 2, dp[3] = 3; for(int i = 4; i <= n; i++) { dp[i] = i; //maximum number of operations required will be i for(int j = 2; j <= i / 2; j++) { //we copy and paste j A's till we have i A's int x = i - j; //we already have j A's in our stream, so remaining = i - j if(x % j == 0) { //if remaining number of A's is a multiple of J dp[i] = min(dp[i], dp[j] + 1 + (x / j)); //1 operation to copy, x / j to paste, dp[j] for getting j A's } } } return dp[n]; } int minSteps(int n) { return byPrimeFactorization(n); } };
var minSteps = function(n) { let result = 0; for (let index = 2; index <= n; index++) { while (n % index === 0) { result += index; n /= index; } } return result; };
2 Keys Keyboard
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). &nbsp; Example 1: Input: root = [1,3,2,5,3,null,9] Output: [1,3,9] Example 2: Input: root = [1,2,3] Output: [1,3] &nbsp; Constraints: The number of nodes in the tree will be in the range [0, 104]. -231 &lt;= Node.val &lt;= 231 - 1
class Solution(object): def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] ans=[] q=[] q.append(root) while q: s=len(q) t=[] for i in range(s): n=q.pop(0) t.append(n.val) if n.left: q.append(n.left) if n.right: q.append(n.right) ans.append(max(t)) return ans
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private List<Integer> li=new ArrayList<>(); public List<Integer> largestValues(TreeNode root) { if(root==null) return li; //if root is NULL //using bfs(level-order) Queue<TreeNode> q=new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size=q.size(); int res=Integer.MIN_VALUE; while(size-->0){ TreeNode temp=q.poll(); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); res =Math.max(res,temp.val); //comparing every node in each level to get max } li.add(res); //adding each level Max value to the list } return li; } }
class Solution { public: vector<int>res; vector<int> largestValues(TreeNode* root) { if(!root) return {}; if(!root->left && !root->right) return {root->val}; TreeNode*temp; int mx = INT_MIN; queue<TreeNode*>q; q.push(root); while(!q.empty()){ int sz = q.size(); while(sz--){ temp = q.front(); if(temp->val > mx) mx = temp->val; q.pop(); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } res.push_back(mx); mx = INT_MIN; } return res; } };
var largestValues = function(root) { if(!root) return []; const op = []; const Q = [[root, 1]]; while(Q.length) { const [r, l] = Q.shift(); if(op.length < l) op.push(-Infinity); op[l-1] = Math.max(op[l-1], r.val); if(r.left) Q.push([r.left, l + 1]); if(r.right) Q.push([r.right, l + 1]); } return op; };
Find Largest Value in Each Tree Row
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container. Remove the smallest k elements and the largest k elements from the container. Calculate the average value for the rest of the elements rounded down to the nearest integer. Implement the MKAverage class: MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k. void addElement(int num) Inserts a new element num into the stream. int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer. &nbsp; Example 1: Input ["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"] [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []] Output [null, null, null, -1, null, 3, null, null, null, 5] Explanation MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5 &nbsp; Constraints: 3 &lt;= m &lt;= 105 1 &lt;= k*2 &lt; m 1 &lt;= num &lt;= 105 At most 105 calls will be made to addElement and calculateMKAverage.
from sortedcontainers import SortedList class MKAverage: MAX_NUM = 10 ** 5 def __init__(self, m: int, k: int): self.m = m self.k = k # sorted list self.sl = SortedList([0] * m) # sum of k smallest elements self.sum_k = 0 # sum of m - k smallest elements self.sum_m_k = 0 # queue for the last M elements if the stream self.q = deque([0] * m) def addElement(self, num: int) -> None: # Time: O(logm) m, k, q, sl = self.m, self.k, self.q, self.sl # update q q.append(num) old = q.popleft() # remove the old num r = sl.bisect_right(old) # maintain sum_k if r <= k: self.sum_k -= old self.sum_k += sl[k] # maintain sum_m_k if r <= m - k: self.sum_m_k -= old self.sum_m_k += sl[m-k] # remove the old num sl.remove(old) # add the new num r = sl.bisect_right(num) if r < k: self.sum_k -= sl[k-1] self.sum_k += num if r < m - k: self.sum_m_k -= sl[m - k - 1] self.sum_m_k += num sl.add(num) return def calculateMKAverage(self) -> int: # Time: O(1) if self.sl[0] == 0: return -1 return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)
class MKAverage { class Node implements Comparable<Node> { int val; int time; Node(int val, int time) { this.val = val; this.time = time; } @Override public int compareTo(Node other) { return (this.val != other.val ? this.val - other.val : this.time - other.time); } } private TreeSet<Node> set = new TreeSet<>(); // natural order private Deque<Node> queue = new LinkedList<>(); private Node kLeft; private Node kRight; private int m, k; private int time = 0; private int sum = 0; public MKAverage(int m, int k) { this.m = m; this.k = k; } public void addElement(int num) { Node node = new Node(num, time++); addNode(node); removeNode(); if (time == m) init(); } private void init() { int i = 0; for (Node node : set) { if (i < k-1); else if (i == k-1) kLeft = node; else if (i < m-k) sum += node.val; else if (i == m-k) { kRight = node; return; } i++; } return; } private void addNode(Node node) { queue.offerLast(node); set.add(node); if (queue.size() <= m) return; if (node.compareTo(kLeft) < 0) { sum += kLeft.val; kLeft = set.lower(kLeft); } else if (node.compareTo(kRight) > 0) { sum += kRight.val; kRight = set.higher(kRight); } else { sum += node.val; } } private void removeNode() { if (queue.size() <= m) return; Node node = queue.pollFirst(); if (node.compareTo(kLeft) <= 0) { kLeft = set.higher(kLeft); sum -= kLeft.val; } else if (node.compareTo(kRight) >= 0) { kRight = set.lower(kRight); sum -= kRight.val; } else { sum -= node.val; } set.remove(node); } public int calculateMKAverage() { return (queue.size() < m ? -1 : sum / (m - 2 * k)); } }
/* Time: addElement: O(logm) | calculateMKAverage: O(1) Space: O(m) Tag: TreeMap, Sorting, Queue Difficulty: H */ class MKAverage { map<int, int> left, middle, right; queue<int> q; int sizeofLeft, sizeofMiddle, sizeofRight; int k; long long mkSum; int m; void addToSet1(int num) { left[num]++; sizeofLeft++; } void deleteFromSet1(int num) { left[num]--; if (left[num] == 0) left.erase(num); sizeofLeft--; } void addToSet2(int num) { middle[num]++; sizeofMiddle++; mkSum += num; } void deleteFromSet2(int num) { middle[num]--; if (middle[num] == 0) middle.erase(num); sizeofMiddle--; mkSum -= num; } void addToSet3(int num) { right[num]++; sizeofRight++; } void deleteFromSet3(int num) { right[num]--; if (right[num] == 0) right.erase(num); sizeofRight--; } public: MKAverage(int m, int k) { sizeofLeft = 0, sizeofMiddle = 0, sizeofRight = 0; mkSum = 0; this->k = k; this->m = m; } void addElement(int num) { if (sizeofLeft < k) { addToSet1(num); q.push(num); } else if (sizeofMiddle < (m - (2 * k))) { int lastEle = prev(left.end())->first; if (num >= lastEle) { addToSet2(num); } else { deleteFromSet1(lastEle); addToSet1(num); addToSet2(lastEle); } q.push(num); } else if (sizeofRight < k) { int last1 = prev(left.end())->first; int last2 = prev(middle.end())->first; if (num >= last1 && num >= last2) { addToSet3(num); } else if (num >= last1 && num < last2) { deleteFromSet2(last2); addToSet2(num); addToSet3(last2); } else { deleteFromSet2(last2); addToSet3(last2); deleteFromSet1(last1); addToSet2(last1); addToSet1(num); } q.push(num); } else { int toErase = q.front(); q.pop(); int first3 = right.begin()->first; int first2 = middle.begin()->first; int first1 = left.begin()->first; if (toErase >= first3) { deleteFromSet3(toErase); } else if (toErase >= first2) { deleteFromSet3(first3); deleteFromSet2(toErase); addToSet2(first3); } else { deleteFromSet3(first3); deleteFromSet2(first2); deleteFromSet1(toErase); addToSet1(first2); addToSet2(first3); } addElement(num); } } int calculateMKAverage() { if (q.size() < m) return -1; return mkSum / (m - (2 * k)); } };
class ArraySegTree{ // Array to perfrom operations on, range query operation, PointUpdate operation constructor(A,op=(a,b)=>a+b,upOp=(a,b)=>a+b,opSentinel=0){ this.n=A.length,this.t=[...Array(4*this.n+1)],this.op=op,this.upOp=upOp,this.opSentinel=opSentinel //root's idx =1 this.build(A,1,0,this.n-1) } left=x=>this.t[2*x];right=x=>this.t[2*x+1] build(A,idx,left,right){ if(left==right) return this.t[idx]=A[left] let mid=(left+right)>>1 this.build(A,2*idx,left,mid) //go left this.build(A,2*idx+1,mid+1,right) //go right this.t[idx]=this.op(this.left(idx),this.right(idx)) //merge } //just specify l,r on actual queries //Here queries use the actul indices of the starting array A, so rangeQuery(0,n-1) returns the whole array rangeQuery=(l,r,tl=0,tr=this.n-1,idx=1)=>{ if(l>r) return this.opSentinel if(l===tl&&r===tr) return this.t[idx] let mid=(tl+tr)>>1 return this.op( this.rangeQuery(l,Math.min(r,mid),tl,mid,idx*2), this.rangeQuery(Math.max(l,mid+1),r,mid+1,tr,idx*2+1) ) } //just specify arrIdx,newVal on actual pointUpdates pointUpdate=(arrIdx,newVal,tl=0,tr=this.n-1,idx=1)=>{ if(tl==tr) return this.t[idx]=this.upOp(this.t[idx],newVal) let mid=(tl+tr)>>1 if(arrIdx<=mid) this.pointUpdate(arrIdx,newVal,tl,mid,2*idx) else this.pointUpdate(arrIdx,newVal,mid+1,tr,2*idx+1) this.t[idx]=this.op(this.left(idx),this.right(idx)) } seachPrefixIndex=(x,start=0,end=this.n-1)=>{ let s=this.rangeQuery(start,end) if(s<x) return -1 if(start===end) return start let mid=start+end>>1,left=this.rangeQuery(start,mid) if( left>=x) return this.seachPrefixIndex(x,start,mid) else return this.seachPrefixIndex(x-left,mid+1,end) } } var MKAverage = function(m, k) { this.A=[],this.m=m,this.k=k,this.div=m-2*k this.S1=new ArraySegTree([...Array(1e5+2)].map(d=>0))//indices this.S2=new ArraySegTree([...Array(1e5+2)].map(d=>0))//sums }; /** * @param {number} num * @return {void} */ MKAverage.prototype.addElement = function(num) { this.A.push(num) this.S1.pointUpdate(num,1) this.S2.pointUpdate(num,num) if(this.A.length>this.m){ let z=this.A.shift() this.S1.pointUpdate(z,-1) this.S2.pointUpdate(z,-z) } }; /** * @return {number} */ MKAverage.prototype.calculateMKAverage = function() { if(this.A.length<this.m) return -1 let S=this.S1.seachPrefixIndex(this.k+1), count1=this.S1.rangeQuery(0,S), take=(count1-this.k)*S let E=this.S1.seachPrefixIndex(this.m-this.k), count2=this.S1.rangeQuery(0,E), remove=(count2-this.m+this.k)*E let midSum=this.S2.rangeQuery(S+1,E) return (take+midSum-remove)/this.div>>0 };
Finding MK Average
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. &nbsp; Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]] Example 2: Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] &nbsp; Constraints: n == matrix.length == matrix[i].length 1 &lt;= n &lt;= 20 -1000 &lt;= matrix[i][j] &lt;= 1000
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # transpose size = len(matrix) for i in range(size): for j in range(i+1, size): matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i] print(matrix) # reverse row for row in range(len(matrix)): matrix[row] = matrix[row][::-1] print(matrix)
class Solution { public void swap(int[][] matrix, int n1, int m1, int n2, int m2) { int a = matrix[n1][m1]; int temp = matrix[n2][m2]; matrix[n2][m2] = a; matrix[n1][m1] = temp; } public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n/2; i++) { for (int j = 0; j < n; j++) { swap(matrix, i,j, n-i-1, j); } } for (int i = n-1; i >= 0; i--) { for (int j = 0; j < i; j++) { swap(matrix, i,j, j, i); } } } }
class Solution { public: void rotate(vector<vector<int>>& matrix) { int row = matrix.size(); for(int i=0;i<row; i++){ for(int j=0; j<=i;j++){ swap(matrix[i][j], matrix[j][i]); } } for(int i=0;i<row;i++){ reverse(matrix[i].begin(), matrix[i].end()); } } };
/** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function(matrix) { let m = matrix.length; let n = matrix[0].length; for (let i = m - 1; i >= 0; i--) { for (let j = 0; j < m; j++) { matrix[j].push(matrix[i].shift()); } } };
Rotate Image
A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order. &nbsp; Example 1: Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"] Output: ["alice,20,800,mtv","alice,50,100,beijing"] Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. Example 2: Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"] Output: ["alice,50,1200,mtv"] Example 3: Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"] Output: ["bob,50,1200,mtv"] &nbsp; Constraints: transactions.length &lt;= 1000 Each transactions[i] takes the form "{name},{time},{amount},{city}" Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10. Each {time} consist of digits, and represent an integer between 0 and 1000. Each {amount} consist of digits, and represent an integer between 0 and 2000.
class Transaction: def __init__(self, name, time, amount, city): self.name = name self.time = int(time) self.amount = int(amount) self.city = city from collections import defaultdict class Solution: def invalidTransactions(self, transactions): transactions = [Transaction(*transaction.split(',')) for transaction in transactions] transactions.sort(key=lambda t: t.time) # O(nlogn) time trans_indexes = defaultdict(list) for i, t in enumerate(transactions): # O(n) time trans_indexes[t.name].append(i) res = [] for name, indexes in trans_indexes.items(): # O(n) time left = right = 0 for i, t_index in enumerate(indexes): t = transactions[t_index] if (t.amount > 1000): res.append("{},{},{},{}".format(t.name, t.time, t.amount, t.city)) continue while left <= len(indexes)-2 and transactions[indexes[left]].time < t.time - 60: # O(60) time left += 1 while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time right += 1 for i in range(left,right+1): # O(120) time if transactions[indexes[i]].city != t.city: res.append("{},{},{},{}".format(t.name, t.time, t.amount, t.city)) break return res
class Solution { public List<String> invalidTransactions(String[] transactions) { Map<String, List<Transaction>> nameToTransaction = new HashMap<>(); for (int i = 0; i < transactions.length; i++) { Transaction t = new Transaction(transactions[i], i); nameToTransaction.putIfAbsent(t.name, new ArrayList<>()); nameToTransaction.get(t.name).add(t); } List<String> invalid = new ArrayList<>(); for (List<Transaction> list : nameToTransaction.values()) { for (Transaction t : list) { if (t.isInvalidAmount()) invalid.add(transactions[t.id]); else { for (Transaction otherT : list) { if (t.isInvalidCity(otherT)) { invalid.add(transactions[t.id]); break; } } } } } return invalid; } } class Transaction { String name, city; int time, amount, id; Transaction(String s, int id) { this.id = id; String[] split = s.split(","); name = split[0]; time = Integer.parseInt(split[1]); amount = Integer.parseInt(split[2]); city = split[3]; } boolean isInvalidAmount() { return this.amount > 1000; } boolean isInvalidCity(Transaction t) { return !city.equals(t.city) && Math.abs(t.time - time) <= 60; } }
class Solution { public: /* this question is absolutely frustrating 🙂 */ /* method to split string */ vector<string> split(string s){ string t=""; vector<string> v; for(int i=0;i<s.length();i++){ if(s[i]==','){ v.push_back(t); t=""; }else{ t+=s[i]; } } v.emplace_back(t); return v; } /* this function checks the second condition. */ bool check(string s,string time,string city,map<string,vector<string>>mp){ for(auto x:mp[s]){ vector<string>out=split(x); int val1=stoi(out[1]); int val2=stoi(time); if(out[3]!=city and abs(val2-val1)<=60){ return true; } } return false; } vector<string> invalidTransactions(vector<string>& transactions) { vector<string> res;/* stores the result */ map<string,vector<string>>mp;/* to search for only that person*/ int n=transactions.size(); vector<vector<string>>v(n,vector<string>(4));/*ith v stores info about ith transaction*/ int c=0; for(auto x:transactions){ vector<string> out=split(x); v[c]=out; mp[out[0]].emplace_back(x); c+=1; } for(int i=0;i<n;i++){ if(stoi(v[i][2])>1000){ /* check for first condition */ res.emplace_back(transactions[i]); }else{ /* checks for second condition. */ if(check(v[i][0],v[i][1],v[i][3],mp)){ res.emplace_back(transactions[i]); } } } return res; } };
var invalidTransactions = function(transactions) { const invalid = new Uint8Array(transactions.length).fill(false); for(let i = 0; i < transactions.length; i++){ const [name, time, amount, city] = transactions[i].split(','); if(+amount > 1000) invalid[i] = true; for(let j = i + 1; j < transactions.length; j++){ const [name1, time1, amount1, city1] = transactions[j].split(','); if(Math.abs(+time - +time1) <= 60 && name === name1 && city !== city1){ invalid[i] = true; invalid[j] = true; } } } return invalid.reduce((acc, val, index) => { if(val) acc.push(transactions[index]) return acc; }, []) };
Invalid Transactions
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. A subtree of root is a tree consisting of root and all of its descendants. &nbsp; Example 1: Input: root = [4,8,5,0,1,null,6] Output: 5 Explanation: For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4. For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5. For the node with value 0: The average of its subtree is 0 / 1 = 0. For the node with value 1: The average of its subtree is 1 / 1 = 1. For the node with value 6: The average of its subtree is 6 / 1 = 6. Example 2: Input: root = [1] Output: 1 Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1. &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 &lt;= Node.val &lt;= 1000
class Solution: def averageOfSubtree(self, root: Optional[TreeNode]) -> int: def calculate_average(root): if root: self.summ+=root.val self.nodecount+=1 calculate_average(root.left) calculate_average(root.right) def calculate_for_each_node(root): if root: self.summ = 0 self.nodecount = 0 calculate_average(root) if ((self.summ)//(self.nodecount)) == root.val: self.count+=1 calculate_for_each_node(root.left) calculate_for_each_node(root.right) self.count = 0 calculate_for_each_node(root) return self.count
class Solution { int res = 0; public int averageOfSubtree(TreeNode root) { dfs(root); return res; } private int[] dfs(TreeNode node) { if(node == null) { return new int[] {0,0}; } int[] left = dfs(node.left); int[] right = dfs(node.right); int currSum = left[0] + right[0] + node.val; int currCount = left[1] + right[1] + 1; if(currSum / currCount == node.val) { res++; } return new int[] {currSum, currCount}; } }
class Solution { public: pair<int,int> func(TreeNode* root,int &ans){ if(!root)return {0,0}; auto p1=func(root->left,ans); auto p2=func(root->right,ans); int avg=(root->val+p1.first+p2.first)/(p1.second+p2.second+1); if(avg==root->val)ans++; return {root->val+p1.first+p2.first,p1.second+p2.second+1}; } int averageOfSubtree(TreeNode* root) { int ans=0; func(root,ans); return ans; } };
var averageOfSubtree = function(root) { let result = 0; const traverse = node => { if (!node) return [0, 0]; const [leftSum, leftCount] = traverse(node.left); const [rightSum, rightCount] = traverse(node.right); const currSum = node.val + leftSum + rightSum; const currCount = 1 + leftCount + rightCount; if (Math.floor(currSum / currCount) === node.val) result++; return [currSum, currCount]; }; traverse(root); return result; };
Count Nodes Equal to Average of Subtree
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. The steps of the insertion sort algorithm: Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. &nbsp; Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] &nbsp; Constraints: The number of nodes in the list is in the range [1, 5000]. -5000 &lt;= Node.val &lt;= 5000
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function insertionSortList(head: ListNode | null): ListNode | null { if (!head) return null if (!head.next) return head let output = head let curr = head.next head.next = null while (curr) { const next = curr.next const insertion = curr output = insert(output, insertion) curr = next as ListNode } return output } function insert(head: ListNode, other: ListNode) { let curr = head const val = other.val if (val <= head.val) { other.next = head return other } while (curr) { if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) { other.next = curr.next curr.next = other return head } curr = curr.next as ListNode } return head }
class Solution { public ListNode insertionSortList(ListNode head) { ListNode cur = head; ListNode temp = new ListNode(-5001); ListNode prev = temp; while(cur != null){ ListNode nxt = cur.next; if(prev.val >= cur.val) prev = temp; while(prev.next != null && prev.next.val < cur.val) prev = prev.next; cur.next = prev.next; prev.next = cur; cur = nxt; } return temp.next; } }
class Solution { public: ListNode* insertionSortList(ListNode* head) { ListNode *prev=head,*cur=head->next; while(cur){ ListNode *tmp=head,*pt=NULL; while(tmp!=cur and tmp->val < cur->val){ pt=tmp; tmp=tmp->next; } if(tmp==cur){ prev=prev->next; cur=cur->next; continue; } prev->next=cur->next; if(!pt){ cur->next=head; head=cur; } else{ pt->next=cur; cur->next=tmp; } cur=prev->next; } 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 insertionSortList = function(head) { let ptr = head; while(ptr.next !== null){ if(ptr.val <= ptr.next.val) ptr = ptr.next; else{ let temp = ptr.next; ptr.next = ptr.next.next; if(temp.val < head.val) { temp.next = head; head = temp; } else{ let ptr2 = head; while(ptr2.next != null && temp.val >= ptr2.next.val){ ptr2 = ptr2.next; } temp.next = ptr2.next; ptr2.next = temp; } } } return head; };
Insertion Sort List
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. &nbsp; Example 1: Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s = "abab", p = "ab" Output: [0,1,2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". &nbsp; Constraints: 1 &lt;= s.length, p.length &lt;= 3 * 104 s and p consist of lowercase English letters.
from collections import Counter class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: l='abcdefghijklmnopqrstuvwxyz' if len(p)>len(s): return [] d={} for x in l: d[x]=0 d1=dict(d) d2=dict(d) for x in range(len(p)): d1[s[x]]+=1 d2[p[x]]+=1 l1=[] if d1==d2: l1=[0] #print(d1) for x in range(len(p),len(s)): d1[s[x]]+=1 d1[s[x-len(p)]]-=1 if d1==d2: l1.append(x-len(p)+1) return l1
class Solution { public List<Integer> findAnagrams(String s, String p) { int fullMatchCount = p.length(); Map<Character, Integer> anagramMap = new HashMap<>(); for (Character c : p.toCharArray()) anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1); List<Integer> result = new ArrayList<>(); int left = 0, right = 0, currentMatchCount = 0; Map<Character, Integer> currentAnagramMap = new HashMap<>(); while (right < s.length()) { char c = s.charAt(right); if (anagramMap.get(c) == null) { currentAnagramMap = new HashMap<>(); right++; left = right; currentMatchCount = 0; continue; } currentAnagramMap.put(c, currentAnagramMap.getOrDefault(c, 0) + 1); currentMatchCount++; if (currentAnagramMap.get(c) > anagramMap.get(c)) { char leftC = s.charAt(left); while (leftC != c) { currentAnagramMap.put(leftC, currentAnagramMap.get(leftC) - 1); left++; leftC = s.charAt(left); currentMatchCount--; } left++; currentAnagramMap.put(c, currentAnagramMap.get(c) - 1); currentMatchCount--; } if (currentMatchCount == fullMatchCount) result.add(left); right++; } return result; } }
//easy to understand class Solution { public: bool allZeros(vector<int> &count) { for (int i = 0; i < 26; i++) { if (count[i] != 0) return false; } return true; } vector<int> findAnagrams(string s, string p) { string s1 = p, s2 = s; int n = s1.length(); int m = s2.length(); if (n > m) return {}; vector<int> ans; vector<int> count(26, 0); for (int i = 0; i < n; i++) { count[s1[i] - 'a']++; count[s2[i] - 'a']--; } //it will check for s1 = abcd, s2 = cdab if (allZeros(count)) { ans.push_back(0); } for (int i = n; i < m; i++) { count[s2[i] - 'a']--; count[s2[i - n] - 'a']++; if (allZeros(count)) ans.push_back(i-n+1); } return ans; } };
var findAnagrams = function(s, p) { function compareMaps(map1, map2) { var testVal; if (map1.size !== map2.size) { return false; } for (var [key, val] of map1) { testVal = map2.get(key); // in cases of an undefined value, make sure the key // actually exists on the object so there are no false positives if (testVal !== val || (testVal === undefined && !map2.has(key))) { return false; } } return true; } let p_map=new Map() let s_map=new Map() let res=[] let pn=p.length let sn=s.length for(let i in p){ p_map.set(p[i],p_map.get(p[i])?p_map.get(p[i])+1:1) s_map.set(s[i],s_map.get(s[i])?s_map.get(s[i])+1:1) } let l=0 if(compareMaps(s_map,p_map)) res.push(l) for(let r=pn;r<sn;r++){ s_map.set(s[r],s_map.get(s[r])?s_map.get(s[r])+1:1) s_map.set(s[l],s_map.get(s[l])-1) if(s_map.get(s[l])===0){ s_map.delete(s[l]) } if(compareMaps(s_map,p_map)) res.push(l+1) l++ } return(res) };
Find All Anagrams in a String
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. &nbsp; Example 1: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true Example 2: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false &nbsp; Constraints: m == matrix.length n == matrix[i].length 1 &lt;= m, n &lt;= 100 -104 &lt;= matrix[i][j], target &lt;= 104
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: left=0 right=len(matrix)-1 while left <= right: mid=(left+right)//2 if matrix[mid][0] < target: left = mid+1 elif matrix[mid][0] >target: right= mid-1 else: return True left1=0 right1=len(matrix[right])-1 while left1 <= right1: mid=(left1+right1)//2 if matrix[right][mid] < target: left1 = mid+1 elif matrix[right][mid] >target: right1= mid-1 else: return True return False
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (target < matrix[0][0]) { return false; } for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] > target | i == matrix.length - 1) { if (matrix[i][0] > target) { i--; } for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == target) { return true; } } return false; } } return false; } }
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for(int i = 0; i < matrix.size(); i ++) { if(matrix[i][0] > target) return false; for(int j = 0; j < matrix[i].size(); j ++) { if(matrix[i][j] == target) return true; else if(matrix[i][j] > target) break; } } return false; } };
var searchMatrix = function(matrix, target) { let matCopy = [...matrix]; let leftIndex = 0; let rightIndex = matrix.length - 1; let mid = Math.ceil((matrix.length - 1) / 2); let eachMatrixLength = matrix[0].length; if (matrix[mid].includes(target) === true) { return true; } else if (matrix.length == 1) { return false; } if (matrix[mid][eachMatrixLength - 1] > target) { rightIndex = mid - 1; matCopy.splice(-mid); } else { leftIndex = mid + 1; matCopy.splice(0, mid); } return searchMatrix(matCopy, target); };
Search a 2D Matrix
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. Successor(x, curOrder): if x has no children or all of x's children are in curOrder: if x is the king return null else return Successor(x's parent, curOrder) else return x's oldest child who's not in curOrder For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. In the beginning, curOrder will be ["king"]. Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"]. Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"]. Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"]. Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"]. Using the above function, we can always obtain a unique order of inheritance. Implement the ThroneInheritance class: ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor. void birth(string parentName, string childName) Indicates that parentName gave birth to childName. void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead. string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people. &nbsp; Example 1: Input ["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"] [["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]] Output [null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]] Explanation ThroneInheritance t= new ThroneInheritance("king"); // order: king t.birth("king", "andy"); // order: king &gt; andy t.birth("king", "bob"); // order: king &gt; andy &gt; bob t.birth("king", "catherine"); // order: king &gt; andy &gt; bob &gt; catherine t.birth("andy", "matthew"); // order: king &gt; andy &gt; matthew &gt; bob &gt; catherine t.birth("bob", "alex"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; catherine t.birth("bob", "asha"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; asha &gt; catherine t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"] t.death("bob"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; asha &gt; catherine t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"] &nbsp; Constraints: 1 &lt;= kingName.length, parentName.length, childName.length, name.length &lt;= 15 kingName, parentName, childName, and name consist of lowercase English letters only. All arguments childName and kingName are distinct. All name arguments of death will be passed to either the constructor or as childName to birth first. For each call to&nbsp;birth(parentName, childName), it is guaranteed that&nbsp;parentName is alive. At most 105 calls will be made to birth and death. At most 10 calls will be made to getInheritanceOrder.
class ThroneInheritance: def __init__(self, kingName: str): # Taking kingName as root self.root = kingName # notDead will hold all the people who are alive and their level number self.alive = {} self.alive[kingName] = 0 # hold edges existing in our graph self.edges = {self.root:[]} def birth(self, parentName: str, childName: str) -> None: # birth --> new child so update alive self.alive[childName] = self.alive[parentName]+1 # add parent to child edges in the edges dictionary if parentName in self.edges: self.edges[parentName].append(childName) if childName not in self.edges: self.edges[childName] = [] else: if childName not in self.edges: self.edges[childName] = [] self.edges[parentName] = [childName] def death(self, name: str) -> None: # removing the dead people from alive map del self.alive[name] def getInheritanceOrder(self) -> List[str]: hierarchy = [] def dfs(cur,parent=-1): nonlocal hierarchy # current person available in alive then only add in hierarchy if cur in self.alive: hierarchy.append(cur) # traverse all the children of current node for i in self.edges[cur]: if i!=parent: dfs(i,cur) dfs(self.root) return hierarchy
class Tree{ List<Tree>child; String name; public Tree(String name,List<Tree>child){ this.name=name; this.child=child; } } class ThroneInheritance { private Set<String>death; private Tree tree; private Map<String,Tree>addtoTree; public ThroneInheritance(String kingName) { death=new HashSet<>(); tree=new Tree(kingName,new ArrayList()); addtoTree=new HashMap(); addtoTree.put(kingName,tree); } public void birth(String parentName, String childName) { Tree tmp =addtoTree.get(parentName); Tree childtree=new Tree(childName,new ArrayList()); tmp.child.add(childtree); addtoTree.put( childName,childtree); } public void death(String name) { death.add(name); } public List<String> getInheritanceOrder() { List<String>ans=new ArrayList<>(); preOreder(tree,ans,death); return ans; } void preOreder(Tree n,List<String>ans,Set<String>death){ if(n==null)return; if(!death.contains(n.name))ans.add(n.name); for(Tree name:n.child){ preOreder(name,ans,death); } } }
class ThroneInheritance { public: ThroneInheritance(string kingName) { curr_king = kingName; } void birth(string parentName, string childName) { children[parentName].push_back(childName); } void death(string name) { dead.insert(name); } void rec(string parent) { if (!dead.count(parent)) inheritance.push_back(parent); for (auto child : children[parent]) rec(child); } vector<string> getInheritanceOrder() { inheritance = {}; rec(curr_king); return inheritance; } private: unordered_map<string, vector<string>> children; vector<string> inheritance; unordered_set<string> dead; string curr_king; };
var bloodList = function(name, parent = null) { return { name, children: [] }; } var ThroneInheritance = function(kingName) { this.nameMap = new Map(); this.nameMap.set(kingName, bloodList(kingName)); this.king = kingName; this.deadList = new Set(); }; /** * @param {string} parentName * @param {string} childName * @return {void} */ ThroneInheritance.prototype.birth = function(parentName, childName) { const parent = this.nameMap.get(parentName); const childId = bloodList(childName, parent); this.nameMap.set(childName, childId); parent.children.push(childId); }; /** * @param {string} name * @return {void} */ ThroneInheritance.prototype.death = function(name) { this.deadList.add(name); }; /** * @return {string[]} */ function updateList(list, nameId, deadList) { if (!deadList.has(nameId.name)) list.push(nameId.name); for (let child of nameId.children) { updateList(list, child, deadList); } } ThroneInheritance.prototype.getInheritanceOrder = function() { let list = []; updateList(list, this.nameMap.get(this.king), this.deadList); return list; };
Throne Inheritance
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array. &nbsp; Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7. &nbsp; Constraints: 1 &lt;= arr.length &lt;= 104 1 &lt;= arr[i] &lt;= 104
class Solution: def find_max(self, i, a, n): maxs = i+1 for j in range(n-1, i, -1): # if only j is greater than max and smaller than first descending element if(a[maxs] <= a[j] and a[j] < a[i]): maxs = j # Swap a[i], a[maxs] = a[maxs], a[i] return a def prevPermOpt1(self, arr): n = len(arr) for i in range(n-1, 0, -1): if(arr[i] < arr[i-1]): # sending the first descending element from right to max_function arr = self.find_max(i-1, arr, n) break return arr
class Solution { public int[] prevPermOpt1(int[] arr) { int n=arr.length; int small=arr[n-1]; int prev=arr[n-1]; for(int i=n-2;i>=0;i--){ if(arr[i]<=prev){ prev=arr[i]; } else{ int indte=i; int te=0; for(int j=i+1;j<n;j++){ if(arr[j]<arr[i]&&arr[j]>te){ te=arr[j]; indte=j; } } int tem=arr[indte]; arr[indte]=arr[i]; arr[i]=tem; return arr; } } return arr; } }
class Solution { public: vector<int> prevPermOpt1(vector<int>& arr) { int i, p, mn = -1; for(i=arr.size() - 2; i>=0; i--) { if(arr[i] > arr[i + 1]) break; } if(i == -1) return arr; for(int j=i + 1; j<arr.size(); j++) { if(arr[j] > mn && arr[j] < arr[i]) mn = arr[j], p = j; } swap(arr[i], arr[p]); return arr; } };
var prevPermOpt1 = function(arr) { const n = arr.length; let i = n - 1; while (i > 0 && arr[i] >= arr[i - 1]) i--; if (i === 0) return arr; const swapIndex = i - 1; const swapDigit = arr[swapIndex]; let maxIndex = i; i = n - 1; while (swapIndex < i) { const currDigit = arr[i]; if (currDigit < swapDigit && currDigit >= arr[maxIndex]) maxIndex = i; i--; } [arr[maxIndex], arr[swapIndex]] = [arr[swapIndex], arr[maxIndex]]; return arr; };
Previous Permutation With One Swap
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -&gt; s1 -&gt; s2 -&gt; ... -&gt; sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 &lt;= i &lt;= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. &nbsp; Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation:&nbsp;There are 2 shortest transformation sequences: "hit" -&gt; "hot" -&gt; "dot" -&gt; "dog" -&gt; "cog" "hit" -&gt; "hot" -&gt; "lot" -&gt; "log" -&gt; "cog" Example 2: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. &nbsp; Constraints: 1 &lt;= beginWord.length &lt;= 5 endWord.length == beginWord.length 1 &lt;= wordList.length &lt;= 500 wordList[i].length == beginWord.length beginWord, endWord, and wordList[i] consist of lowercase English letters. beginWord != endWord All the words in wordList are unique.
class Solution: WILDCARD = "." def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: """ Given a wordlist, we perform BFS traversal to generate a word tree where every node points to its parent node. Then we perform a DFS traversal on this tree starting at the endWord. """ if endWord not in wordList: # end word is unreachable return [] # first generate a word tree from the wordlist word_tree = self.getWordTree(beginWord, endWord, wordList) # then generate a word ladder from the word tree return self.getLadders(beginWord, endWord, word_tree) def getWordTree(self, beginWord: str, endWord: str, wordList: List[str]) -> Dict[str, List[str]]: """ BFS traversal from begin word until end word is encountered. This functions constructs a tree in reverse, starting at the endWord. """ # Build an adjacency list using patterns as keys # For example: ".it" -> ("hit"), "h.t" -> ("hit"), "hi." -> ("hit") adjacency_list = defaultdict(list) for word in wordList: for i in range(len(word)): pattern = word[:i] + Solution.WILDCARD + word[i+1:] adjacency_list[pattern].append(word) # Holds the tree of words in reverse order # The key is an encountered word. # The value is a list of preceding words. # For example, we got to beginWord from no other nodes. # {a: [b,c]} means we got to "a" from "b" and "c" visited_tree = {beginWord: []} # start off the traversal without finding the word found = False q = deque([beginWord]) while q and not found: n = len(q) # keep track of words visited at this level of BFS visited_this_level = {} for i in range(n): word = q.popleft() for i in range(len(word)): # for each pattern of the current word pattern = word[:i] + Solution.WILDCARD + word[i+1:] for next_word in adjacency_list[pattern]: if next_word == endWord: # we don't return immediately because other # sequences might reach the endWord in the same # BFS level found = True if next_word not in visited_tree: if next_word not in visited_this_level: visited_this_level[next_word] = [word] # queue up next word iff we haven't visited it yet # or already are planning to visit it q.append(next_word) else: visited_this_level[next_word].append(word) # add all seen words at this level to the global visited tree visited_tree.update(visited_this_level) return visited_tree def getLadders(self, beginWord: str, endWord: str, wordTree: Dict[str, List[str]]) -> List[List[str]]: """ DFS traversal from endWord to beginWord in a given tree. """ def dfs(node: str) -> List[List[str]]: if node == beginWord: return [[beginWord]] if node not in wordTree: return [] res = [] parents = wordTree[node] for parent in parents: res += dfs(parent) for r in res: r.append(node) return res return dfs(endWord)
class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { Set<String> dict = new HashSet(wordList); if( !dict.contains(endWord) ) return new ArrayList(); // adjacent words for each word Map<String,List<String>> adjacency = new HashMap(); Queue<String> queue = new LinkedList(); // does path exist? boolean found = false; // BFS for shortest path, keep removing visited words queue.offer(beginWord); dict.remove(beginWord); while( !found && !queue.isEmpty() ) { int size = queue.size(); // adjacent words in current level HashSet<String> explored = new HashSet(); while( size-- > 0 ) { String word = queue.poll(); if( adjacency.containsKey(word) ) continue; // remove current word from dict, and search for adjacent words dict.remove(word); List<String> adjacents = getAdjacents(word, dict); adjacency.put(word, adjacents); for(String adj : adjacents) { if( !found && adj.equals(endWord) ) found = true; explored.add(adj); queue.offer(adj); } } // remove words explored in current level from dict for(String word : explored) dict.remove(word); } // if a path exist, dfs to find all the paths if( found ) return dfs(beginWord, endWord, adjacency, new HashMap()); else return new ArrayList(); } private List<String> getAdjacents(String word, Set<String> dict) { List<String> adjs = new ArrayList(); char[] wordChars = word.toCharArray(); for(int i=0; i<wordChars.length; i++) for(char c='a'; c<='z'; c++) { char temp = wordChars[i]; wordChars[i] = c; String newAdj = new String(wordChars); if( dict.contains(newAdj) ) adjs.add(newAdj); wordChars[i] = temp; } return adjs; } private List<List<String>> dfs(String src, String dest, Map<String,List<String>> adjacency, Map<String,List<List<String>>> memo) { if( memo.containsKey(src) ) return memo.get(src); List<List<String>> paths = new ArrayList(); // reached dest? return list with dest word if( src.equals( dest ) ) { paths.add( new ArrayList(){{ add(dest); }} ); return paths; } // no adjacent for curr word? return empty list List<String> adjacents = adjacency.get(src); if( adjacents == null || adjacents.isEmpty() ) return paths; for(String adj : adjacents) { List<List<String>> adjPaths = dfs(adj, dest, adjacency, memo); for(List<String> path : adjPaths) { if( path.isEmpty() ) continue; List<String> newPath = new ArrayList(){{ add(src); }}; newPath.addAll(path); paths.add(newPath); } } memo.put(src, paths); return paths; } }
// BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime. // The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time. // Then, use DFS (backtracking) to generate the transformation sequences according to the mapping. // The reverse DFS allows us to only make the shortest paths, never having to clear a whole sequence when we encounter better result in BFS // No string operations are done, by dealing with indices instead. class Solution { public: bool able(string s,string t){ int c=0; for(int i=0;i<s.length();i++) c+=(s[i]!=t[i]); return c==1; } void bfs(vector<vector<int>> &g,vector<int> parent[],int n,int start,int end){ vector <int> dist(n,1005); queue <int> q; q.push(start); parent[start]={-1}; dist[start]=0; while(!q.empty()){ int x=q.front(); q.pop(); for(int u:g[x]){ if(dist[u]>dist[x]+1){ dist[u]=dist[x]+1; q.push(u); parent[u].clear(); parent[u].push_back(x); } else if(dist[u]==dist[x]+1) parent[u].push_back(x); } } } void shortestPaths(vector<vector<int>> &Paths, vector<int> &path, vector<int> parent[],int node){ if(node==-1){ // as parent of start was -1, we've completed the backtrack Paths.push_back(path); return ; } for(auto u:parent[node]){ path.push_back(u); shortestPaths(Paths,path,parent,u); path.pop_back(); } } vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { // start and end are indices of beginWord and endWord int n=wordList.size(),start=-1,end=-1; vector<vector<string>> ANS; for(int i=0;i<n;i++){ if(wordList[i]==beginWord) start=i; if(wordList[i]==endWord) end=i; } // if endWord doesn't exist, return empty list if(end==-1) return ANS; // if beginWord doesn't exist, add it in start of WordList if(start==-1){ wordList.emplace(wordList.begin(),beginWord); start=0; end++; n++; } // for each word, we're making adjency list of neighbour words (words that can be made with one letter change) // Paths will store all the shortest paths (formed later by backtracking) vector<vector<int>> g(n,vector<int>()),Paths; // storing possible parents for each word (to backtrack later), path is the current sequence (while backtracking) vector<int> parent[n],path; // creating adjency list for each pair of words in the wordList (including beginword) for(int i=0;i<n-1;i++) for(int j=i+1;j<n;j++) if(able(wordList[i],wordList[j])){ g[i].push_back(j); g[j].push_back(i); } bfs(g,parent,n,start,end); // backtracking to make shortestpaths shortestPaths(Paths,path,parent,end); for(auto u:Paths){ vector <string> now; for(int i=0;i<u.size()-1;i++) now.push_back(wordList[u[i]]); reverse(now.begin(),now.end()); now.push_back(wordList[end]); ANS.push_back(now); } return ANS; } };
const isMatch = (currWord, nextWord) => { let mismatch = 0; for(let i = 0; i < nextWord.length; i += 1) { if(nextWord[i] !== currWord[i]) { mismatch += 1; } } return mismatch === 1; } const getNextWords = (lastRung, dictionary) => { const nextWords = []; for(const word of dictionary) { if(isMatch(word, lastRung)) { nextWords.push(word); } } return nextWords; } const updateLadders = (ladders, dictionary) => { const updatedLadders = []; const nextRung = new Set(); for(const ladder of ladders) { const nextWords = getNextWords(ladder[ladder.length - 1], dictionary); for(const nextWord of nextWords) { updatedLadders.push([...ladder, nextWord]); nextRung.add(nextWord); } } return [updatedLadders, nextRung]; } const updateDictionary = (dictionary, nextRung) => { return dictionary.filter((word) => !nextRung.has(word)); } // BFS traversal from endWord to beginWord // This limits the paths that we'll need to consider during our traversal from beingWord to endWord const getDictionary = (wordList, endWord, beginWord) => { const dictionary = new Set(); let currRung = [endWord]; while(currRung.length > 0) { const nextRung = new Set(); if(!wordList.includes(beginWord)) break; while(currRung.length > 0) { const currWord = currRung.pop(); dictionary.add(currWord); for(const nextWord of wordList) { if(isMatch(currWord, nextWord)) { nextRung.add(nextWord); } } } currRung = [...nextRung]; wordList = wordList.filter((word) => !nextRung.has(word)); } return [...dictionary]; } var findLadders = function(beginWord, endWord, wordList) { if(!wordList.includes(endWord)) return []; if(!wordList.includes(beginWord)) wordList.push(beginWord); const result = []; const saveResult = (ladders) => { for(const ladder of ladders) { if(ladder[ladder.length - 1] === endWord) { result.push(ladder); } } } let ladders = [[beginWord]]; let dictionary = getDictionary(wordList, endWord, beginWord); while(ladders.length > 0) { if(!dictionary.includes(endWord)) { saveResult(ladders); break; } const [updatedLadders, nextRung] = updateLadders(ladders, dictionary); ladders = updatedLadders; dictionary = updateDictionary(dictionary, nextRung); } return result; };
Word Ladder II
Given the head of a singly linked list, return true if it is a palindrome. &nbsp; Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false &nbsp; Constraints: The number of nodes in the list is in the range [1, 105]. 0 &lt;= Node.val &lt;= 9 &nbsp; Follow up: Could you do it in O(n) time and O(1) space?
class Solution: def isPalindrome(self, head: "Optional[ListNode]") -> bool: if head.next == None: return True #if only 1 element, it's always a palindrome forward = head first_half = [] fast = head while (fast != None and fast.next != None): first_half.append(forward.val) forward = forward.next fast = fast.next.next # forward should now be through half the list if fast != None : forward = forward.next # if length isn't even, skip the middle number reverse = len(first_half)-1 while forward != None: if forward.val != first_half[reverse]: return False forward = forward.next reverse -= 1 return True
class Solution { public boolean isPalindrome(ListNode head) { ListNode mid = getMiddle(head); ListNode headSecond = reverse(mid); ListNode reverseHead = headSecond; while(head != null && headSecond != null){ if(head.val != headSecond.val){ break; } head = head.next; headSecond = headSecond.next; } reverse(reverseHead); return head==null || headSecond == null; } public ListNode reverse(ListNode head){ if(head==null) return head; ListNode prev = null; ListNode present = head; ListNode next = head.next; while(present != null){ present.next = prev; prev = present; present = next; if(next!=null) next = next.next; } return prev; } public ListNode getMiddle(ListNode head){ ListNode temp = head; int count = 0; while(temp!=null){ temp = temp.next; count++; } int mid = count/2; temp = head; for(int i=0; i<mid;i++){ temp = temp.next; } return temp; } }
class Solution { public: ListNode* reverse(ListNode* head) { ListNode* prev=nullptr; while(head) { ListNode* current=head->next; head->next=prev; prev=head; head=current; } return prev; } bool isPalindrome(ListNode* head) { if(!head || !head->next) return true; ListNode* tort=head; ListNode* hare=head; while(hare->next && hare->next->next) { tort=tort->next; hare=hare->next->next; } tort->next=reverse(tort->next); tort=tort->next; ListNode* dummy=head; while(tort) { if(tort->val!=dummy->val) return false; tort=tort->next; dummy=dummy->next; } return true; } }; Time Complexity: O(n/2)+O(n/2)+O(n/2) Space Complexity: O(1)
/** * 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 {boolean} */ var isPalindrome = function(head) { let slow = head; let fast = head; // Moving slow one step at a time while fast, two steps while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } // This way, slow will end up right after the middle node // Reverse the list from that node slow = reverse(slow); fast = head; // Now check for equality first half and second half of the list while (slow) { if (slow.val !== fast.val) { return false; } slow = slow.next; fast = fast.next; } return true; }; // Function to reverse a LinkedList function reverse(head) { let prev = null; while (head) { let nextNode = head.next; head.next = prev; prev = head; head = nextNode; } return prev; }
Palindrome Linked List
On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking. Return the number of available captures for the white rook. &nbsp; Example 1: Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example, the rook is attacking all the pawns. Example 2: Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 0 Explanation: The bishops are blocking the rook from attacking any of the pawns. Example 3: Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: The rook is attacking the pawns at positions b5, d6, and f5. &nbsp; Constraints: board.length == 8 board[i].length == 8 board[i][j] is either 'R', '.', 'B', or 'p' There is exactly one cell with board[i][j] == 'R'
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: # Checking for possible case to the right of Rook def right_position(n,i): List = i[0:n][::-1] # taking list to the right of rook pIndex,bIndex = -1,-1 if 'p' in List: # Checking if 'p' in list pIndex = List.index('p') if 'B' in List: # Checking if 'B' in list bIndex = List.index('B') print(bIndex,pIndex,List) if bIndex == -1 and pIndex >-1: # if list does not have 'B' and have 'p' return True if pIndex == -1: # if list does not have 'p' return False return bIndex>pIndex def left_position(n,i): List = i[n+1:]# taking list to the right of rook pIndex,bIndex = -1,-1 if 'p' in List: pIndex = List.index('p') if 'B' in List: bIndex = List.index('B') print(bIndex,pIndex,List) if bIndex == -1 and pIndex >-1: return True if pIndex == -1: return False return bIndex>pIndex Count = 0 # Checking for possibilites in row for i in board: if 'R' in i: print(i) n = i.index('R') if left_position(n,i): Count += 1 if right_position(n,i): Count += 1 Col = [] # checking for possibilites in col for i in range(0,len(board)): Col.append(board[i][n]) # taking the elements from the same col of Rook n = Col.index('R') if left_position(n,Col): Count += 1 if right_position(n,Col): Count += 1 return Count
class Solution { public int numRookCaptures(char[][] board) { int ans = 0; int row = 0; int col = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board[i][j] == 'R') { row = i; col = j; break; } } } int j = col; while (j >= 0) { if (board[row][j] == 'B') { break; } else if (board[row][j] == 'p') { ans++; break; } j--; } j = col; while (j <= board[0].length - 1) { if (board[row][j] == 'B') { break; } else if (board[row][j] == 'p') { ans++; break; } j++; } int i = row; while (i <= board.length - 1) { if (board[i][col] == 'B') { break; } else if (board[i][col] == 'p') { ans++; break; } i++; } i = row; while (i >= 0) { if (board[i][col] == 'B') { break; } else if (board[i][col] == 'p') { ans++; break; } i--; } return ans; } }
class Solution { public: int numRookCaptures(vector<vector<char>>& board) { int res=0; int p=-1,q=-1; for(int i=0;i<board.size();i++) { for(int j=0;j<board[0].size();j++) { if(board[i][j]=='R') // storing position of R { p=i; q=j; break; } } if(p>=0) break; } // traverse Up, Down, Left and Right from R for(int i=p+1;i<board.size();i++) { if(board[i][q]!='.') { if(board[i][q]=='p') res++; break; } } for(int i=p-1;i>=0;i--) { if(board[i][q]!='.') { if(board[i][q]=='p') res++; break; } } for(int j=q+1;j<board[0].size();j++) { if(board[p][j]!='.') { if(board[p][j]=='p') res++; break; } } for(int j=q-1;j>=0;j--) { if(board[p][j]!='.') { if(board[p][j]=='p') res++; break; } } return res; } };
var numRookCaptures = function(board) { const r=board.length; const c=board[0].length; let res=0 const dir=[[0,1],[0,-1],[1,0],[-1,0]]; // all the 4 possible directions let rook=[]; // finding the rook's position for(let i=0;i<r;i++){ for(let j=0;j<c;j++){ if(board[i][j]==='R'){ rook=[i,j] break; } } } // traversing all the 4 directions for(let [x,y] of dir){ res+=helper(x,y,rook[0],rook[1]) } return res; function helper(x,y,i,j){ let newX=x+i let newY=y+j let attack=0 while(newX<r&&newY<c&&newX>=0&&newY>=0){ if(board[newX][newY]==='p'){ attack++ break; // break because Rook can't attack more than one pawn in same direction }else if(board[newX][newY]==='B'){ break } // keep moving towards the same direction newX+=x newY+=y } return attack } };
Available Captures for Rook
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree. &nbsp; Example 1: Input: root = [4,2,6,1,3] Output: 1 Example 2: Input: root = [1,0,48,null,null,12,49] Output: 1 &nbsp; Constraints: The number of nodes in the tree is in the range [2, 100]. 0 &lt;= Node.val &lt;= 105 &nbsp; Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
# class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: if root is None: return 0 temp1=float(inf) from collections import deque a=deque([root]) b=[] while a: node=a.popleft() b.append(node.val) if node.left: a.append(node.left) if node.right: a.append(node.right) b.sort() for i in range(0,len(b)-1): if b[i+1]-b[i]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int mini=Integer.MAX_VALUE; public void find(TreeNode root,ArrayList<Integer>arr){ if(root==null){ return; } arr.add(root.val); find(root.left,arr); for(int i=arr.size()-2;i>=0;i--){ mini=Math.min(mini,Math.abs(root.val-arr.get(i))); } find(root.right,arr); arr.remove(arr.size()-1); } public int minDiffInBST(TreeNode root) { ArrayList<Integer>arr=new ArrayList<>(); find(root,arr); return mini; } }
class Solution { int minDiff=INT_MAX,prev=INT_MAX; public: void inorder(TreeNode* p){ if(p==NULL) return; inorder(p->left); minDiff=min(minDiff,abs(p->val-prev)); prev=p->val; inorder(p->right); } int minDiffInBST(TreeNode* root) { inorder(root); return minDiff; } };
/** * @param {TreeNode} root * @return {number} */ var minDiffInBST = function(root) { let arr = []; const helper = (node) => { if (node) { helper(node.left); arr.push(node.val); helper(node.right); } } helper(root); let min = Infinity; for (let i = 0; i < arr.length - 1; i++) { const diff = Math.abs(arr[i] - arr[i + 1]); min = Math.min(min, diff); } return min; };
Minimum Distance Between BST Nodes
Alice and Bob have an undirected graph of n nodes and three types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both Alice and Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. &nbsp; Example 1: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. Example 2: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob. Example 3: Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]] Output: -1 Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. &nbsp; &nbsp; Constraints: 1 &lt;= n &lt;= 105 1 &lt;= edges.length &lt;= min(105, 3 * n * (n - 1) / 2) edges[i].length == 3 1 &lt;= typei &lt;= 3 1 &lt;= ui &lt; vi &lt;= n All tuples (typei, ui, vi) are distinct.
class DSUF: def __init__(self, n): self.arr = [-1] * n def find(self, node): p = self.arr[node] if p == -1: return node self.arr[node] = self.find(p) return self.arr[node] def union(self, a, b): aP = self.find(a) bP = self.find(b) if aP == bP: return 0 self.arr[aP] = bP return 1 def countParents(self): count = 0 for i in self.arr: if i == -1: count += 1 return count class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: # Solution - DSU # Time - O(ElogV) # Space - O(V) aliceSet = DSUF(n) bobSet = DSUF(n) bothEdges = [] bobEdges = [] aliceEdges= [] for i in range(len(edges)): if edges[i][0] == 3: bothEdges.append(edges[i]) elif edges[i][0] == 1: aliceEdges.append(edges[i]) else: bobEdges.append(edges[i]) usedEdgeCount = 0 # connect both edges for edge in bothEdges: aReq = aliceSet.union(edge[1]-1, edge[2]-1) bReq = bobSet.union(edge[1]-1, edge[2]-1) if aReq and bReq: usedEdgeCount += 1 # connect individual edges for edge in aliceEdges: usedEdgeCount += aliceSet.union(edge[1]-1, edge[2]-1) for edge in bobEdges: usedEdgeCount += bobSet.union(edge[1]-1, edge[2]-1) if aliceSet.countParents() == 1 and bobSet.countParents() == 1: return len(edges) - usedEdgeCount return -1
class Solution { public int maxNumEdgesToRemove(int n, int[][] edges) { Arrays.sort(edges, (a, b)->{ return b[0]-a[0]; });//giving the priority to third type of edge or the edge which Bob and Alice both can access //1-based indexing of nodes int []parentAlice= new int[n+1];//Graph 1 for Alice connectedness int []parentBob= new int[n+1];//Graph 2 for Bob connectedness for(int i= 0; i< n+1; i++){//every node is pointing to itself, at first no connection is considered all sets are independent(no dependency) parentAlice[i]= i; parentBob[i]= i; } //number of merged unique node for Alice and Bob that are required to maintain the connectedness of Alice and Bob graph nodes//intialised with one because merging happens in pair int mergeAlice= 1; int mergeBob= 1; //number of cyclic or the non dependent node, that are not required for the connectedness of Alice and Bob nodes int removeEdge= 0; for(int []edge: edges) { int cat= edge[0];//category of edge 1)edge Alice can only access 2)edge Bob can only access 3)edge both Alice and Bob can access int u= edge[1]; int v= edge[2]; if(cat == 3){//edge both Alice and Bob an access //creating dependency of nodes in graph 1 and 2 boolean tempAlice= union(u, v, parentAlice); boolean tempBob= union(u, v, parentBob); if(tempAlice == true) mergeAlice+= 1; if(tempBob == true) mergeBob+= 1; if(tempAlice == false && tempBob == false)//retundant or the cyclic non-dependent edge//both Alice and Bob don't rquire it connection is already there between these pair of nodes removeEdge+= 1; } else if(cat == 2){//edge Bob can only access //creating dependency of nodes in graph 2 boolean tempBob= union(u, v, parentBob); if(tempBob == true) mergeBob+= 1; else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency removeEdge+= 1; } else{//edge Alice can only access //creating dependency of nodes in graph 1 boolean tempAlice= union(u, v, parentAlice); if(tempAlice == true) mergeAlice+= 1; else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency removeEdge+= 1; } } if(mergeAlice != n || mergeBob != n)//all node are not connected, connectedness is not maintained return -1; return removeEdge;//number of edge removed by maintaining the connectedness } public int find(int x, int[] parent) { if(parent[x] == x)//when we found the absolute root or the leader of the set return x; int temp= find(parent[x], parent); parent[x]= temp;//Path Compression//child pointing to the absolute root or the leader of the set, while backtracking return temp;//returning the absolute root } public boolean union(int x, int y, int[] parent) { int lx= find(x, parent);//leader of set x or the absolute root int ly= find(y, parent);//leader of set y or the absolute root if(lx != ly){//belong to different set merging //Rank Compression is not done, but you can do it parent[lx]= ly; return true;//union done, dependency created } else return false;//no union done cycle is due to this edge }//Please do Upvote, it helps a lot }
class Solution { public: vector < int > Ar , Ap , Br , Bp; // alice and bob parent and rank arrays static bool cmp(vector < int > & a , vector < int > & b){ return a[0] > b[0]; } // lets create the alice graph first // find function for finding the parent nodes int find1(int x){ if(x == Ap[x]) return x; return Ap[x] = find1(Ap[x]); } // if nodes are already connected return 1 else make the connection and return 0 bool union1( int x , int y){ int parX = find1(x); int parY = find1(y); if(parX == parY) return 1; if(Ar[parX] > Ar[parY]){ Ap[parY] = parX; } else if(Ar[parX] < Ar[parY]){ Ap[parX] = parY; } else { Ap[parY] = parX; Ar[parX]++; } return 0; } // same thing do for bob graph int find2(int x){ if(x == Bp[x]) return x; return Bp[x] = find2(Bp[x]); } bool union2( int x , int y){ int parX = find2(x); int parY = find2(y); if(parX == parY) return 1; if(Br[parX] > Br[parY]){ Bp[parY] = parX; } else if(Br[parX] < Br[parY]){ Bp[parX] = parY; } else { Bp[parY] = parX; Br[parX]++; } return 0; } int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) { Ar.resize(n , 1); Ap.resize(n , 1); Br.resize(n , 1); Bp.resize(n , 1); for(int i = 0; i<n ; i++){ Ap[i] = i; Bp[i] = i; } sort(edges.begin() , edges.end() , cmp); int ans = 0; // give priority to 3rd type of vertices for(auto a : edges){ if(a[0] != 3) continue; if(union1(a[1]-1 , a[2]-1))ans++; union2(a[1] -1, a[2]-1); } // now try the edges one by one and check if it the given nodes are already connected in respective alice and bob graph or not for(auto a : edges){ if(a[0] == 3) continue; if(a[0] == 1) { if(union1(a[1]-1 , a[2]-1))ans++; } else { if(union2(a[1]-1 , a[2]-1))ans++;} } int cnt1 = 0, cnt2 = 0; for(int i = 0; i< n ; i++){ if(Ap[i] == i) cnt1++; if(Bp[i] == i) cnt2++; } if(cnt1 >1 | cnt2 >1) return -1; return ans; } };
// A common disjoint set class function DS(n) { var root = [...new Array(n + 1).keys()]; var rank = new Array(n + 1).fill(0); this.find = function(v) { if (root[v] !== v) root[v] = this.find(root[v]); return root[v]; } this.union = function (i, j) { var [a, b] = [this.find(i), this.find(j)]; if (a === b) return false; if (rank[a] > rank[b]) root[b] = a; else if (rank[a] < rank[b]) root[a] = b; else root[a] = b, rank[b]++; return true; } // check if the nodes 1-n is in the same set this.canFullyTraverse = function() { var key = this.find(1); for (var i = 2; i <= n; i++) { if (this.find(i) !== key) return false; } return true; } } /** * @param {number} n * @param {number[][]} edges * @return {number} */ var maxNumEdgesToRemove = function(n, edges) { // two persons disjoint set var ds1 = new DS(n); var ds2 = new DS(n); // sort edges by type, to make sure we can handle type 3 first edges.sort((a, b) => b[0] - a[0]); var result = 0; edges.forEach(([type, u, v]) => { // when edge type is 3, union u, v for both person's ds // if they are already in the same set, this edge can be remove, result++ if (type === 3) { var [r1, r2] = [ds1.union(u, v), ds2.union(u, v)]; if (!r1 && !r2) { result++; } // for specific person } else if (type === 1) { if (!ds1.union(u, v)) { result++; } } else { if (!ds2.union(u, v)) { result++; } } }); // if one person cannot fully traverse, return -1 // otherwise, return result if (ds1.canFullyTraverse() && ds2.canFullyTraverse()) { return result; } return -1; };
Remove Max Number of Edges to Keep Graph Fully Traversable
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. &nbsp; Example 1: Input: n = 34, k = 6 Output: 9 Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. Example 2: Input: n = 10, k = 10 Output: 1 Explanation: n is already in base 10. 1 + 0 = 1. &nbsp; Constraints: 1 &lt;= n &lt;= 100 2 &lt;= k &lt;= 10
class Solution: def sumBase(self, n: int, k: int) -> int: cnt = 0 while n: cnt += (n % k) n //= k print(cnt) return cnt
class Solution { public int sumBase(int n, int k) { int res = 0; for (; n > 0; n /= k) res += n % k; return res; } }
class Solution { public: int sumBase(int n, int k) { int sum=0; while(n!=0) sum+=n%k,n=n/k; return sum; } };
/** * @param {number} n * @param {number} k * @return {number} */ var sumBase = function(n, k) { return n.toString(k).split("").reduce((acc, cur) => +acc + +cur) };
Sum of Digits in Base K
Given the root of a&nbsp;binary tree, return the postorder traversal of its nodes' values. &nbsp; Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] &nbsp; Constraints: The number of the 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 typing import List, Optional class Solution: """ Time: O(n) """ def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if root is None: return [] postorder = [] stack = [root] while stack: node = stack.pop() postorder.append(node.val) if node.left is not None: stack.append(node.left) if node.right is not None: stack.append(node.right) return postorder[::-1] class Solution: """ Time: O(n) """ def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: return list(self.postorder_generator(root)) @classmethod def postorder_generator(cls, tree: Optional[TreeNode]): if tree is not None: yield from cls.postorder_generator(tree.left) yield from cls.postorder_generator(tree.right) yield tree.val
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { List<Integer> res = new ArrayList<>(); public List<Integer> postorderTraversal(TreeNode root) { traversal(root); return res; } public void traversal(TreeNode root){ if(root == null) return; traversal(root.left); traversal(root.right); res.add(root.val); } }
class Solution { void solve(TreeNode *root, vector<int> &ans){ if(root == NULL) return; solve(root->left, ans); solve(root->right, ans); ans.push_back(root->val); } public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ans; solve(root, ans); return ans; } };
class Pair{ constructor(node, state){ this.node = node; this.state = state; } } var postorderTraversal = function(root) { let ans = []; let st = []; // stack root != null && st.push(new Pair(root, 1)); while(st.length > 0){ let top = st[st.length - 1]; if(top.state == 1){ top.state++; if(top.node.left != null){ st.push(new Pair(top.node.left, 1)) } } else if(top.state == 2){ top.state++; if(top.node.right != null){ st.push(new Pair(top.node.right, 1)) } } else{ ans.push(top.node.val); st.pop(); } } return ans; };
Binary Tree Postorder Traversal
You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands. &nbsp; Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1 &nbsp; Constraints: n == grid.length == grid[i].length 2 &lt;= n &lt;= 100 grid[i][j] is either 0 or 1. There are exactly two islands in grid.
class Solution: def shortestBridge(self, grid): m, n = len(grid), len(grid[0]) start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j]) stack = [(start_i, start_j)] visited = set(stack) while stack: i, j = stack.pop() visited.add((i, j)) for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited: stack.append((ii, jj)) visited.add((ii, jj)) ans = 0 queue = list(visited) while queue: new_queue = [] for i, j in queue: for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited: if grid[ii][jj] == 1: return ans new_queue.append((ii, jj)) visited.add((ii, jj)) queue = new_queue ans += 1
class Solution { private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}}; public int shortestBridge(int[][] grid) { boolean[][] visited=new boolean[grid.length][grid[0].length]; LinkedList<Pair> queue=new LinkedList<Pair>(); boolean found=false; for(int i=0;i<grid.length && !found;i++){ for(int j=0;j<grid[0].length && !found;j++){ if(grid[i][j]==1){ dfs(grid,i,j,queue,visited); found=true; } } } int level=0; while(queue.size()>0){ int size=queue.size(); while(size-- >0){ Pair pair=queue.poll(); for(int k=0;k<4;k++){ int rowDash=pair.row+dirs[k][0]; int colDash=pair.col+dirs[k][1]; if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length || visited[rowDash][colDash]==true )continue; if(grid[rowDash][colDash]==1) return level; queue.add(new Pair(rowDash,colDash)); visited[rowDash][colDash]=true; } } level++; } return -1; } private void dfs(int[][] grid,int i,int j,LinkedList<Pair> queue,boolean[][] visited){ visited[i][j]=true; queue.add(new Pair(i,j)); for(int k=0;k<4;k++){ int rowDash=i+dirs[k][0]; int colDash=j+dirs[k][1]; if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length || visited[rowDash][colDash]==true || grid[rowDash][colDash]==0)continue; dfs(grid,rowDash,colDash,queue,visited); } } static class Pair{ int row; int col; public Pair(int row,int col){ this.row=row; this.col=col; } } }
class Solution { public: void findOneIsland(vector<vector<int>>& grid, int i, int j, queue<pair<int, int>>& q){ if(i<0 || j<0 || i==grid.size() || j==grid.size() || grid[i][j]!=1) return; grid[i][j] = 2; q.push({i,j}); findOneIsland(grid, i, j-1, q); findOneIsland(grid, i, j+1, q); findOneIsland(grid, i-1, j, q); findOneIsland(grid, i+1, j, q); } int shortestBridge(vector<vector<int>>& grid) { int n = grid.size(); queue<pair<int, int>> q; int res=0; bool OneIslandFound = false; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(grid[i][j]==1){ OneIslandFound = true; findOneIsland(grid, i, j, q); break; } } if(OneIslandFound) break; } while(!q.empty()){ int i=q.front().first, j=q.front().second; q.pop(); if(i!=0 && grid[i-1][j]<2){ if(grid[i-1][j]==1){ res = grid[i][j]-2; break; } if(grid[i-1][j]==0){ grid[i-1][j] = grid[i][j]+1; q.push({i-1, j}); } } if(i!=grid.size()-1 && grid[i+1][j]<2){ if(grid[i+1][j]==1){ res = grid[i][j]-2; break; } if(grid[i+1][j]==0){ grid[i+1][j] = grid[i][j]+1; q.push({i+1, j}); } } if(j!=0 && grid[i][j-1]<2){ if(grid[i][j-1]==1){ res = grid[i][j]-2; break; } if(grid[i][j-1]==0){ grid[i][j-1] = grid[i][j]+1; q.push({i, j-1}); } } if(j!=grid.size()-1 && grid[i][j+1]<2){ if(grid[i][j+1]==1){ res = grid[i][j]-2; break; } if(grid[i][j+1]==0){ grid[i][j+1] = grid[i][j]+1; q.push({i, j+1}); } } } return res; } };
/** * @param {number[][]} grid * @return {number} */ const DIR = [ [0,1], [0,-1], [1,0], [-1,0] ]; var shortestBridge = function(grid) { const que = []; const ROWS = grid.length; const COLS = grid[0].length; // find first insland outer: for(let row=0; row<ROWS; row++) { for(let col=0; col<COLS; col++) { if(grid[row][col] == 1) { const stack = [[row, col]]; while(stack.length) { const [r, c] = stack.pop(); que.push([r, c]); grid[r][c] = 2; // mark as visited. for(const dir of DIR) { const newRow = r+dir[0]; const newCol = c+dir[1]; if(newRow<0 || newCol<0 || newRow>=ROWS || newCol>=COLS) continue; if(grid[newRow][newCol] != 1) continue; stack.push([newRow, newCol]); } } break outer; } } } let steps = 0; while(que.length) { let size = que.length; for(let i=0; i<size; i++) { const [row, col] = que.shift(); for(const dir of DIR) { const newRow = row+dir[0]; const newCol = col+dir[1]; if(newRow<0 || newCol<0 || newRow>=ROWS || newCol>=COLS) continue; if(grid[newRow][newCol] == 2) continue; if(grid[newRow][newCol] == 1) return steps; grid[newRow][newCol] = 2; // mark as visited. que.push([newRow, newCol]); } } steps++; } return -1; };
Shortest Bridge
You are given an integer array nums with the following properties: nums.length == 2 * n. nums contains n + 1 unique elements. Exactly one element of nums is repeated n times. Return the element that is repeated n times. &nbsp; Example 1: Input: nums = [1,2,3,3] Output: 3 Example 2: Input: nums = [2,1,2,5,3,2] Output: 2 Example 3: Input: nums = [5,1,5,2,5,3,5,4] Output: 5 &nbsp; Constraints: 2 &lt;= n &lt;= 5000 nums.length == 2 * n 0 &lt;= nums[i] &lt;= 104 nums contains n + 1 unique elements and one of them is repeated exactly n times.
class Solution: def repeatedNTimes(self, nums: List[int]) -> int: return Counter(nums).most_common(1)[0][0]
class Solution { public int repeatedNTimes(int[] nums) { int count = 0; for(int i = 0; i < nums.length; i++) { for(int j = i + 1; j < nums.length; j++) { if(nums[i] == nums[j]) count = nums[j]; } } return count; } }
class Solution { public: int repeatedNTimes(vector<int>& nums) { unordered_map<int, int> mp; for(auto it : nums) mp[it]++; int n; for(auto it : mp) { if(it.second == nums.size() / 2) { n = it.first; break; } } return n; } };
var repeatedNTimes = function(nums) { // loop through the array and then as we go over every num we filter that number and get the length. If the length is equal to 1 that is not the element so we continue if its not equal to one its the element we want and we just return that element. for (let num of nums) { let len = nums.filter(element => element === num).length if (len == 1) continue; else return num } };
N-Repeated Element in Size 2N Array
The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. &nbsp; Example 1: Input: nums = [2,1,3] Output: 6 Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. Example 2: Input: nums = [2] Output: 0 &nbsp; Constraints: 1 &lt;= nums.length &lt;= 105 1 &lt;= nums[i] &lt;= 105
class Solution: def sumSubseqWidths(self, nums: List[int]) -> int: nums.sort() n = len(nums) M = 10**9+7 res = 0 le = 1 re = pow(2, n-1, M) #by Fermat's Little Thm #inverse of 2 modulo M inv = pow(2, M-2, M) for num in nums: res = (res + num * (le - re))%M le = (le * 2) % M re = (re * inv) % M return res
class Solution { public int sumSubseqWidths(int[] nums) { int MOD = (int)1e9 + 7; Arrays.sort(nums); long ans = 0; long p = 1; for(int i = 0; i < nums.length; i++){ ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD; p = (p * 2) % MOD; } return (int)ans; } }
class Solution { public: int sumSubseqWidths(vector<int>& nums) { vector < long long > pow(nums.size() ); pow[0] = 1; for(int i = 1 ; i<nums.size(); i++){ pow[i] = pow[i-1] * 2 % 1000000007; } sort(nums.begin() , nums.end()); long long ans = 0 ; for(int i = 0 ; i<nums.size(); i++){ ans = (ans + pow[i]*nums[i]) % 1000000007; ans = (ans - pow[nums.size()-i-1] * (long long)nums[i] ) % 1000000007; } return ans; } };
var sumSubseqWidths = function(nums) { const mod = 1000000007; nums.sort((a, b) => a - b), total = 0, power = 1; for(let i = 0; i < nums.length; i++) { total = (total + nums[i] * power) % mod; power = (power * 2) % mod; } power = 1; for(let i = nums.length - 1; i >= 0; i--) { total = (total - nums[i] * power + mod) % mod; power = (power * 2) % mod; } return (total + mod) % mod };
Sum of Subsequence Widths
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. &nbsp; Example 1: Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] &nbsp; Constraints: 1 &lt;= s.length &lt;= 105 s[i] is a printable ascii character.
class Solution(object): def reverseString(self, s): for i in range(len(s)): s.insert(i,s.pop()) return s
class Solution { public void reverseString(char[] s) { int start = 0, end = s.length-1; while(start < end) { char temp = s[end]; s[end] = s[start]; s[start] = temp; start++; end--; } } }
class Solution { public: void reverseString(vector<char>& s) { int i = -1, j = s.size(); while (++i < --j){ //Instead of using temp we can do the following s[i] = s[j] + s[i]; s[j] = s[i] - s[j]; s[i] = s[i] - s[j]; } } };
var reverseString = function(s) { for(let i = 0 ; i < s.length / 2 ; i++){ [s[i], s[s.length - i - 1]] = [s[s.length - i - 1], s[i]] } return s; };
Reverse String
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. &nbsp; Example 1: Input: date = "2019-01-09" Output: 9 Explanation: Given date is the 9th day of the year in 2019. Example 2: Input: date = "2019-02-10" Output: 41 &nbsp; Constraints: date.length == 10 date[4] == date[7] == '-', and all other date[i]'s are digits date represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.
class Solution: def dayOfYear(self, date: str) -> int: d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} year=int(date[:4]) if year%4==0: if year%100==0: if year%400==0: d[2]=29 else: d[2]=29 month=int(date[5:7]) day=int(date[8:]) ans=0 for i in range(1,month+1): ans+=d[i] return ans-(d[month]-day)
class Solution { public int dayOfYear(String date) { int days = 0; int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31}; String[] year = date.split("-"); int y = Integer.valueOf(year[0]); int month = Integer.valueOf(year[1]); int day = Integer.valueOf(year[2]); boolean leap = false; for(int i = 0; i < month-1; i++){ days = days+arr[i]; } days = days+day; if(y%4==0){ if(y%100==0){ if(y%400==0){ leap = true; } else{ leap = false; } } else{ leap = true; } } else{ leap = false; } if(leap==true && month>2){ System.out.println("Leap Year"); days = days+1; } return days; } }
class Solution { public: bool leapyear(int year){ return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } int dayOfYear(string date) { vector<int> v; int ans = 0; int n = date.length(); for (int i = 0; i < n; i++) { if (date[i] >= '0' && date[i] <= '9') { ans = ans * 10 + (date[i] - '0'); // subtract '0' to get the integer value } else { v.push_back(ans); ans = 0; } } v.push_back(ans); // add the last value to the vector if (v.size() != 3) return -1; // error handling for invalid input int year = v[0]; int month = v[1]; int day = v[2]; if (month == 1) return day; if (month == 2) return 31 + day; if (month == 3) return leapyear(year) ? 60 + day : 59 + day; if (month == 4) return leapyear(year) ? 91 + day : 90 + day; if (month == 5) return leapyear(year) ? 121 + day : 120 + day; if (month == 6) return leapyear(year) ? 152 + day : 151 + day; if (month == 7) return leapyear(year) ? 182 + day : 181 + day; if (month == 8) return leapyear(year) ? 213 + day : 212 + day; if (month == 9) return leapyear(year) ? 244 + day : 243 + day; if (month == 10) return leapyear(year) ? 274+ day : 273 + day; if (month == 11) return leapyear(year) ? 305 + day : 304 + day; if (month == 12) return leapyear(year) ? 335 + day : 334 + day; return -1; } };
var dayOfYear = function(date) { let dat2 = new Date(date) let dat1 = new Date(dat2.getFullYear(),00,00) let totalTime = dat2 - dat1 return Math.floor(totalTime/1000/60/60/24) };
Day of the Year
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: dominoes[i] = 'L', if the ith domino has been pushed to the left, dominoes[i] = 'R', if the ith domino has been pushed to the right, and dominoes[i] = '.', if the ith domino has not been pushed. Return a string representing the final state. &nbsp; Example 1: Input: dominoes = "RR.L" Output: "RR.L" Explanation: The first domino expends no additional force on the second domino. Example 2: Input: dominoes = ".L.R...LR..L.." Output: "LL.RR.LLRRLL.." &nbsp; Constraints: n == dominoes.length 1 &lt;= n &lt;= 105 dominoes[i] is either 'L', 'R', or '.'.
class Solution: def pushDominoes(self, dom: str) -> str: from collections import deque n = len(dom) d = set() q = deque() arr = [0 for i in range(n)] for i in range(n): if dom[i] == "L": arr[i] = -1 d.add(i) q.append((i,"L")) if dom[i] == "R": arr[i] = 1 d.add(i) q.append((i,"R")) while q: t1 = set() for _ in range(len(q)): t = q.popleft() if t[1] == "L": if t[0]-1 >= 0 and t[0]-1 not in d: t1.add(t[0]-1) arr[t[0]-1] -= 1 else: if t[0]+1 < n and t[0]+1 not in d: t1.add(t[0]+1) arr[t[0]+1] += 1 for val in t1: d.add(val) if arr[val] > 0: q.append((val,"R")) elif arr[val]<0: q.append((val,"L")) ans = "" for val in arr: if val<0: ans += "L" elif val>0: ans += "R" else: ans += "." return ans
// Time complexity: O(N) // Space complexity: O(N), where N is the length of input string class Solution { public String pushDominoes(String dominoes) { // ask whether dominoes could be null final int N = dominoes.length(); if (N <= 1) return dominoes; char[] res = dominoes.toCharArray(); int i = 0; while (i < N) { if (res[i] == '.') { i++; } else if (res[i] == 'L') { // push left int j = i-1; while (j >= 0 && res[j] == '.') { res[j--] = 'L'; } i++; } else { // res[i] == 'R' int j = i+1; while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side j++; } if (j < N && res[j] == 'L') { // if found 'L', push left and right for (int l = i+1, r = j-1; l < r; l++, r--) { res[l] = 'R'; res[r] = 'L'; } i = j + 1; } else { // if no 'L', push right while (i < j) { res[i++] = 'R'; } } } } return String.valueOf(res); } }
class Solution { public: string pushDominoes(string dominoes) { #define SET(ch, arr) \ if (dominoes[i] == ch) { count = 1; prev = ch; } \ else if (dominoes[i] != '.') prev = dominoes[i]; \ if (prev == ch && dominoes[i] == '.') arr[i] = count++; string res = ""; char prev; int n = dominoes.size(), count = 1; vector<int> left(n, 0), right(n, 0); for (int i = 0; i < n; i++) { SET('R', right); } prev = '.'; for (int i = n-1; i >= 0; i--) { SET('L', left); } for (int i = 0; i < n; i++) { if (!left[i] && !right[i]) res += dominoes[i]; else if (!left[i]) res += 'R'; else if (!right[i]) res += 'L'; else if (left[i] == right[i]) res += '.'; else if (left[i] < right[i]) res += 'L'; else res += 'R'; } return res; } };
/** * @param {string} dominoes * @return {string} */ var pushDominoes = function(dominoes) { let len = dominoes.length; let fall = []; let force = 0; let answer = ""; // Traverse from left to right. Focus on the dominoes falling to the right for (let i = 0; i < len; i++) { if (dominoes[i] == 'R') { force = len; } else if (dominoes[i] == 'L') { force = 0; } else { force = Math.max(force-1,0); } fall[i] = force; } //console.log('fall array 1: ', fall); // Traverse from right to left. Focus on the dominoes falling to the left // Subtract the value from the values above for (let i = len-1; i >= 0; i--) { if (dominoes[i] == 'L') { force = len; } else if (dominoes[i] == 'R') { force = 0; } else { force = Math.max(force-1,0); } fall[i] -= force; } //console.log('fall array 2: ', fall); // Just traverse through the fall[] array and assign the values in the answer string accordingly for (let i = 0; i < len; i++) { if (fall[i] < 0) answer += 'L'; else if (fall[i] > 0 ) answer += 'R'; else answer += '.'; } //console.log('answer: ', answer); return answer; };
Push Dominoes
You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square. 2 representing the ending square. There is exactly one ending square. 0 representing empty squares we can walk over. -1 representing obstacles that we cannot walk over. Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once. &nbsp; Example 1: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) Example 2: Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) Example 3: Input: grid = [[0,1],[2,0]] Output: 0 Explanation: There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. &nbsp; Constraints: m == grid.length n == grid[i].length 1 &lt;= m, n &lt;= 20 1 &lt;= m * n &lt;= 20 -1 &lt;= grid[i][j] &lt;= 2 There is exactly one starting cell and one ending cell.
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: ans, empty = 0, 1 def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None: if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1: return nonlocal ans if grid[row][col] == 2: if empty == count: ans += 1 return if (row, col) not in visited: visited.add((row, col)) dfs(grid, row + 1, col, count + 1, visited) dfs(grid, row - 1, col, count + 1, visited) dfs(grid, row, col + 1, count + 1, visited) dfs(grid, row, col - 1, count + 1, visited) visited.remove((row, col)) row, col = 0, 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: row, col = i, j elif grid[i][j] == 0: empty += 1 dfs(grid, row, col, 0, set()) return ans
class Solution { int walk = 0; public int uniquePathsIII(int[][] grid) { int m = grid.length; int n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { walk++; } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { return ways(grid, i, j, m, n, 0); } } } return 0; } public int ways(int[][] grid, int cr, int cc, int m, int n, int count) { if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) { return 0; } if (grid[cr][cc] == 2) { if (count - 1 == walk) return 1; return 0; } grid[cr][cc] = -1; int ans = 0; int[] r = {0, 1, 0, -1}; int[] c = {1, 0, -1, 0}; for (int i = 0; i < 4; i++) { ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1); } grid[cr][cc] = 0; return ans; } }
class Solution { public: int dfs(vector<vector<int>>&grid,int x,int y,int zero){ // Base Condition if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || grid[x][y] == -1){ return 0; } if(grid[x][y] == 2){ return zero == -1 ? 1 : 0; // Why zero = -1, because in above example we have 9 zero's. So, when we reach the final cell we are covering one cell extra that means if all zero all covered then on reaching final it will make zero count = -1 // If that's the case we find the path and return '1' otherwise return '0'; } grid[x][y] = -1; // mark the visited cells as -1; zero--; // and reduce the zero by 1 int totalPaths = dfs(grid, x + 1, y, zero) + // calculating all the paths available in 4 directions dfs(grid, x - 1, y, zero) + dfs(grid, x, y + 1, zero) + dfs(grid, x, y - 1, zero); // Let's say if we are not able to count all the paths. Now we use Backtracking over here grid[x][y] = 0; zero++; return totalPaths; // if we get all the paths, simply return it. } int uniquePathsIII(vector<vector<int>>& grid) { int start_x,start_y=0,cntzero=0; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[0].size();j++){ if(grid[i][j]==0) cntzero++; else if(grid[i][j]==1){ start_x=i; start_y=j; } } } return dfs(grid,start_x,start_y,cntzero); } };
// 980. Unique Paths III var uniquePathsIII = function(grid) { const M = grid.length; // grid height const N = grid[0].length; // grid width let result = 0; // final result let startY = 0, startX = 0; // starting point coordinates let finalY = 0, finalX = 0; // endpoint coordinates let empty = 0; // count of empty squares let visit = Array(M); // visited squares (MxN of booleans) // Initialization of required variables for (let i = 0; i < M; i++) { visit[i] = Array(N).fill(false); // now: "visit[i][j] === false" for (let j = 0; j < N; j++) { switch (grid[i][j]) { case 0 : empty++; break; case 1 : startY = i; startX = j; break; case 2 : finalY = i; finalX = j; break; } } } // Recursively run DFS and get the answer in the "result" variable dfs(startY, startX, visit, 0); return result; // DFS implementation function dfs (startY, startX, visit, step) { // If it's a wrong square, then exit immediately if (startY < 0 || startY >= M || // off grid (height) startX < 0 || startX >= N || // off grid (width) visit[startY][startX] || // already processed grid [startY][startX] === -1 // this is an obstacle ) return; // ... exit now // Base case: we're at the endpoint, need to stop the recursion. // If all of squares are visited, increase the "result": // (count of paths from start to the end). if (startY === finalY && startX === finalX) { if (step - 1 === empty) result++; return; } // Run DFS for neighboring squares. // Increase the number of steps (count of the visited squares). visit[startY][startX] = true; // mark current square as visited dfs(startY-1, startX, visit, step + 1); // top dfs(startY, startX+1, visit, step + 1); // right dfs(startY+1, startX, visit, step + 1); // bottom dfs(startY, startX-1, visit, step + 1); // left visit[startY][startX] = false; // restore visited square } };
Unique Paths III
A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string. &nbsp; Example 1: Input: word = "aba" Output: 4 Explanation: The four wonderful substrings are underlined below: - "aba" -&gt; "a" - "aba" -&gt; "b" - "aba" -&gt; "a" - "aba" -&gt; "aba" Example 2: Input: word = "aabb" Output: 9 Explanation: The nine wonderful substrings are underlined below: - "aabb" -&gt; "a" - "aabb" -&gt; "aa" - "aabb" -&gt; "aab" - "aabb" -&gt; "aabb" - "aabb" -&gt; "a" - "aabb" -&gt; "abb" - "aabb" -&gt; "b" - "aabb" -&gt; "bb" - "aabb" -&gt; "b" Example 3: Input: word = "he" Output: 2 Explanation: The two wonderful substrings are underlined below: - "he" -&gt; "h" - "he" -&gt; "e" &nbsp; Constraints: 1 &lt;= word.length &lt;= 105 word consists of lowercase English letters from 'a'&nbsp;to 'j'.
class Solution: def wonderfulSubstrings(self, word: str) -> int: cnt, res, mask = [1] + [0] * 1023, 0, 0 for ch in word: mask ^= 1 << (ord(ch) - ord('a')) res += cnt[mask] for n in range(10): res += cnt[mask ^ 1 << n]; cnt[mask] += 1 return res
class Solution { public long wonderfulSubstrings(String word) { int n = word.length(); long count = 0; long[] freq = new long[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap freq[0] = 1; int res = 0; // initialize the frequency of 0000000000 as 1 because when no element is encountered, then th bitmask is 0 for (int i = 0; i < n; i++) { int mask = (1 << (word.charAt(i) - 'a')); res ^= mask; // toggling bit of the current character to make it from odd to even OR even to odd int chkMask = 1; count += freq[res]; for (int j = 1; j <= 10; j++) { // Loop for checking all possiblities of different places of the Different Bit count += freq[chkMask ^ res]; chkMask <<= 1; } freq[res]++; // increasing the frequency of the current bitmask } return count; } }
class Solution { public: long long wonderfulSubstrings(string word) { int n=word.length(); int mask=0; unordered_map<int,int>m; m[0]++; long long int ans=0; for(int i=0;i<n;i++){ mask = mask^(1<<(word[i]-'a')); int temp=mask; int j=0; while(j<=9){ int x=temp^(1<<j); ans+=m[x]; j++; } ans+=m[mask]; m[mask]++; } return ans; } };
/** * @param {string} word * @return {number} */ var wonderfulSubstrings = function(word) { let hashMap={},ans=0,binaryRepresentation=0,t,pos,number,oneBitToggled; hashMap[0]=1; for(let i=0;i<word.length;i++){ pos = word[i].charCodeAt(0)-"a".charCodeAt(0);//Let's use position 0 for a, 1 for b .... 9 for j t = (1 << pos); binaryRepresentation = (binaryRepresentation^t);//Toggle the bit at pos in the current mask(pattern) //This loop will check same binaryRepresentation and all the other binaryRepresentation with difference of 1 bit for(let i=0;i<10;i++){//Check all the numbers by changing 1 position number = (1<<i);//Change 1 bit at a time oneBitToggled = (binaryRepresentation^number); if(hashMap[oneBitToggled]!==undefined){ ans += hashMap[oneBitToggled]; } } if(hashMap[binaryRepresentation]===undefined){ hashMap[binaryRepresentation]=1; }else{ ans += hashMap[binaryRepresentation]; hashMap[binaryRepresentation]++; } } return ans; };
Number of Wonderful Substrings
Given a collection of numbers, nums,&nbsp;that might contain duplicates, return all possible unique permutations in any order. &nbsp; Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] &nbsp; Constraints: 1 &lt;= nums.length &lt;= 8 -10 &lt;= nums[i] &lt;= 10
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 1: return [[nums[0]]] res = self.permuteUnique(nums[1:]) for i in range(len(res)-1, -1 , -1): j = 0 while j < len(res[i]): if res[i][j] == nums[0]: #to account for repeated nums break lst = res[i][:] lst.insert(j, nums[0]) res.append(lst) j += 1 res[i].insert(j,nums[0]) return res
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); boolean used[] = new boolean[nums.length]; permutationsFinder(nums,ans,new ArrayList<>(),used); return ans; } static void permutationsFinder(int[] nums,List<List<Integer>> ans,List<Integer> list,boolean used[]){ if(list.size() == nums.length){ ans.add(new ArrayList<>(list)); return; } for(int i=0;i<nums.length;i++){ if(used[i]) continue; if(i>0 && nums[i]==nums[i-1] && !used[i-1]) continue; list.add(nums[i]); used[i] = true; permutationsFinder(nums,ans,list,used); list.remove(list.size()-1); used[i] = false; } } }
class Solution { public: void fun(vector<int>& nums, vector<vector<int>>&ans,int i) { if(i==nums.size()) { ans.push_back(nums); return; } int freq[21]={0}; for(int j=i;j<nums.size();j++) { if(freq[nums[j]+10]==0) { swap(nums[i],nums[j]); fun(nums,ans,i+1); swap(nums[i],nums[j]); } freq[nums[j]+10]++; } } vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>>ans; fun(nums,ans,0); return ans; } };
var permuteUnique = function(nums) { const answer = [] function perm (pos, array) { if (pos >= array.length) { answer.push(array) } const setObject = new Set() for (let index=pos; index<array.length; index++) { if (setObject.has(array[index])) { continue } setObject.add(array[index]) // swap numbers let temp = array[pos] array[pos] = array[index] array[index] = temp perm(pos + 1, [...array]) // undo swapping for next iteration temp = array[index] array[index] = array[pos] array[pos] = temp } } perm(0, nums) return answer };
Permutations II
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. &nbsp; Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" &nbsp; Constraints: 1 &lt;= s.length &lt;= 104 s consists of lowercase English letters. &nbsp; Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
class Solution: def removeDuplicateLetters(self, s: str) -> str: last_occ = {} stack = [] visited = set() for i in range(len(s)): last_occ[s[i]] = i for i in range(len(s)): if s[i] not in visited: while (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i): visited.remove(stack.pop()) stack.append(s[i]) visited.add(s[i]) return ''.join(stack)
class Solution { public String removeDuplicateLetters(String s) { int[] lastIndex = new int[26]; for (int i = 0; i < s.length(); i++){ lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence } boolean[] seen = new boolean[26]; // keep track seen Stack<Integer> st = new Stack(); for (int i = 0; i < s.length(); i++) { int curr = s.charAt(i) - 'a'; if (seen[curr]) continue; // if seen continue as we need to pick one char only while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){ seen[st.pop()] = false; // pop out and mark unseen } st.push(curr); // add into stack seen[curr] = true; // mark seen } StringBuilder sb = new StringBuilder(); while (!st.isEmpty()) sb.append((char) (st.pop() + 'a')); return sb.reverse().toString(); } }
class Solution { public: string removeDuplicateLetters(string s) { int len = s.size(); string res = ""; unordered_map<char, int> M; unordered_map<char, bool> V; stack<int> S; for (auto c : s) { if (M.find(c) == M.end()) M[c] = 1; else M[c]++; } for (unordered_map<char, int>::iterator iter=M.begin(); iter!=M.end(); iter++) V[iter->first] = false; cout<<M.size()<<V.size()<<endl; for (int i=0; i<len; i++) { M[s[i]]--; if (V[s[i]] == true) continue; while (!S.empty() and s[i] < s[S.top()] and M[s[S.top()]] > 0) { V[s[S.top()]] = false; S.pop(); } S.push(i); V[s[i]] = true; } while (!S.empty()) { res = s[S.top()] + res; S.pop(); } return res; } }; Analysis Time complexity O(n) space complexity O(n)
var removeDuplicateLetters = function(s) { let sset = [...new Set(s)] if(Math.min(sset) == sset[0]) return [...sset].join(''); else { sset.sort(); return [...sset].join(''); } };
Remove Duplicate Letters
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). &nbsp; Example 1: Input: root = [5,2,-3] Output: [2,-3,4] Example 2: Input: root = [5,2,-5] Output: [2] &nbsp; Constraints: The number of nodes in the tree is in the range [1, 104]. -105 &lt;= Node.val &lt;= 105
# 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 findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: def dfs(root): if not root: return 0 l = dfs(root.left) r = dfs(root.right) res = root.val + l + r d[res] += 1 return res d = collections.Counter() dfs(root) maxi = max(d.values()) return [i for i in d if d[i] == maxi] # An Upvote will be encouraging
class Solution { public int[] findFrequentTreeSum(TreeNode root) { HashMap<Integer,Integer> map=new HashMap<>(); int sum=sum(root,map); int max=0; int count=0; for(Integer key:map.keySet()){ max=Math.max(max,map.get(key)); } for(Integer key:map.keySet()){ if(max==map.get(key)){ count++; } } int[] ans=new int[count]; int counter=0; for(Integer key:map.keySet()){ if(max==map.get(key)){ ans[counter++]=key; } } return ans; } public int sum(TreeNode root,HashMap<Integer,Integer> map){ if(root==null)return 0; int lh=sum(root.left,map); int rh=sum(root.right,map); map.put(lh+rh+root.val,map.getOrDefault(lh+rh+root.val,0)+1); return lh+rh+root.val; } }
class Solution { private: unordered_map<int, int> m; int maxi = 0; int f(TreeNode* root){ if(!root) return 0; int l = f(root->left); int r = f(root->right); int sum = root->val + l + r; m[sum]++; maxi = max(maxi, m[sum]); return sum; } public: vector<int> findFrequentTreeSum(TreeNode* root) { vector<int> ans; f(root); for(auto &e : m){ if(e.second == maxi) ans.push_back(e.first); } return ans; } };
var findFrequentTreeSum = function(root) { const hash = new Map(); const result = []; let max = 0; const dfs = (node = root) => { if (!node) return 0; const { left, right, val } = node; const sum = val + dfs(left) + dfs(right); const count = hash.get(sum) ?? 0; hash.set(sum, count + 1); max = Math.max(max, count + 1); return sum; }; dfs(); hash.forEach((value, key) => value === max && result.push(key)); return result; };
Most Frequent Subtree Sum
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p&nbsp;and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually. &nbsp; Example 1: Input: p = 2, q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. Example 2: Input: p = 3, q = 1 Output: 1 &nbsp; Constraints: 1 &lt;= q &lt;= p &lt;= 1000
class Solution: def mirrorReflection(self, p: int, q: int) -> int: L = lcm(p,q) if (L//q)%2 == 0: return 2 return (L//p)%2
class Solution { public int mirrorReflection(int p, int q) { while (p % 2 == 0 && q % 2 == 0){ p >>= 1; q >>= 1; } return 1 - p % 2 + q % 2; } };
class Solution { public: int mirrorReflection(int p, int q) { while (p % 2 == 0 && q % 2 == 0){ p/=2; q/=2; } return 1 - p % 2 + q % 2; } };
// Time complexity: O(log (min(p,q)) // Space complexity: O(1) var mirrorReflection = function(p, q) { let ext = q, ref = p; while (ext % 2 == 0 && ref % 2 == 0) { ext /= 2; ref /= 2; } if (ext % 2 == 0 && ref % 2 == 1) return 0; if (ext % 2 == 1 && ref % 2 == 1) return 1; if (ext % 2 == 1 && ref % 2 == 0) return 2; return -1; };
Mirror Reflection