algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n ele...
class Solution: def minimumDifference(self, nums: List[int]) -> int: h=heapq k=len(nums)//3 min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, [] h.heapify(max_heap) , h.heapify(min_heap) for x in nums[:-k]: h.heappush(min_heap,...
class Solution { public long minimumDifference(int[] nums) { int n=nums.length; //length of nums int len3=n/3; // 1/3 length long res=Long.MAX_VALUE; // final result; //Try to make first part as min as possible; //first[m] store the value, the min value of the size=len3, from...
class Solution { public: long long minimumDifference(vector<int>& nums) { int N = nums.size(); int n = N/3; priority_queue<int> pq; map<int, long long> m; long long sum = 0; for(int i=0;i<n;i++){ sum += nums[i]; pq.push(nums[i]); } ...
/** * @param {number[]} nums * @return {number} */ var minimumDifference = function(nums) { //Creating heap class Heap{ constructor(type){ this.type = type; this.data = []; this.data[0] = undefined; } print(){ for(let i=1;i<this.data.length...
Minimum Difference in Sums After Removal of Elements
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other a...
class Solution: def reverseStr(self, s: str, k: int) -> str: a=list(s) for i in range(0,len(a),2*k): a[i:i+k]=a[i:i+k][::-1] print(a) return("".join(a))
class Solution { public String reverseStr(String s, int k) { char[] ch=s.toCharArray(); int cnt=1,i=0; StringBuilder sb=new StringBuilder(); String ans=""; if(k>=s.length()){ sb.append(s); sb.reverse(); return sb.toString(); } ...
Time: O(n) Space: O(1) class Solution { public: string reverseStr(string s, int k) { int n=size(s); for(int i=0;i<n;i=i+2*k){ int j=i+k-1,k=i; if(j>=n) j=n-1; while(k<(j)){ swap(s[k],s[j]); k++,j--; } ...
/** * @param {string} s * @param {number} k * @return {string} */ var reverseStr = function(s, k) { const sArr = s.split(''); let start = 0; let end = k - 1; const swapBlock = (start, end) => { while (start < end) { [sArr[start], sArr[end]] = [sArr[end], sArr[start]]; ...
Reverse String II
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a strin...
class Solution: def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str: val = lambda ch : ord(ch) - ord("a") + 1 hash, res, power_k = 0, 0, pow(power, k, mod) for i in reversed(range(len(s))): hash = (hash * power + val(s[i])) % mod if i < l...
class Solution { public String subStrHash(String s, int power, int modulo, int k, int hashValue) { // calculate all the powers from power^0 till power^k // utilized binary exponentiation long[] powers = new long[k]; for (int i = 0; i < k; i++) powers[i] = binaryExponentiation(power, i, mo...
''' class Solution { public: string subStrHash(string s, int power, int modulo, int k, int hashValue) { int n=s.size(); long long int sum=0; long long int p=1; // Intializing a window from end of size k for(int i=0;i<k;i++){ sum=(sum+((s[n-...
let arrChar ="1abcdefghijklmnopqrstuvwxyz".split(""); var subStrHash = function(s, power, modulo, k, hashValue) { for(let i=0;i<s.length;i++){ let subStr = s.substring(i,i+k); if(hash(subStr,power,modulo)==hashValue){ return subStr; } } }; let hash = function(str,power,m){...
Find Substring With Given Hash Value
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1. There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are giv...
class Solution: def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]: ans = [1] * len(parents) if 1 in nums: tree = {} for i, x in enumerate(parents): tree.setdefault(x, []).append(i) k = nums.index(1) ...
class Solution { public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { int n = parents.length; int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = 1; } int oneIndex = -1; for (int i = 0; i < n; i++) { if (num...
class Solution { public: unordered_set<int> visited; vector<int> nums ; vector<vector<int>> adj; void dfs(int node){ for(auto child:adj[node]){ if(!visited.count(nums[child])){ visited.insert(nums[child]); dfs(child); } } } ...
var smallestMissingValueSubtree = function(parents, nums) { let n=parents.length,next=[...Array(n)].map(d=>[]),used={} for(let i=1;i<n;i++) next[parents[i]].push(i) let dfs=(node)=>{ if(used[nums[node]]) return used[nums[node]]=true for(let child of next[node]) ...
Smallest Missing Genetic Value in Each Subtree
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" ...
from collections import Counter class Solution: def buddyStrings(self, s: str, goal: str) -> bool: if len(s) != len(goal): return False diffCharactersCount = 0 diffCharactersInS = [] diffCharactersInGoal = [] for i in range(len(s)): if s[i] != goal[i]...
class Solution { public boolean buddyStrings(String s, String goal) { char a = '\u0000', b = '\u0000'; char c = '\u0000', d = '\u0000'; int lenS = s.length(); int lenGoal = goal.length(); boolean flag = true; HashSet<Character> hset = new HashSet<>(); if(lenS...
class Solution { public: //In case string is duplicated, check if string has any duplicate letters bool dupeCase(string s){ unordered_set<char> letters; for(auto it : s){ if(letters.count(it)){ //Found dupe letter (they can be swapped) return true; } else...
var buddyStrings = function(A, B) { if(A.length != B.length) return false; const diff = []; for(let i = 0; i < A.length; i++) { if(A[i] != B[i]) diff.push(i); if(diff.length > 2) return false; } if(!diff.length) return A.length != [...new Set(A)].length; const [i, j] = diff;...
Buddy Strings
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. &nbsp; Example 1: Input: timePoints = ["23:59","00:00"] Output: 1 Example 2: Input: timePoints = ["00:00","23:59","00:00"] Output: 0 &nbsp; Constraints: 2 &lt;= timePoints.leng...
class Solution: def findMinDifference(self, timePoints: List[str]) -> int: timePoints.sort() def getTimeDiff(timeString1, timeString2): time1 = int(timeString1[:2]) * 60 + int(timeString1[3:]) time2 = int(timeString2[:2]) * 60 + int(timeString2[3:]) minDiff = abs(time1 - time2) return min(minDiff, 1...
class Solution { public int findMinDifference(List<String> timePoints) { int N = timePoints.size(); int[] minutes = new int[N]; for(int i = 0; i < N; i++){ int hr = Integer.parseInt(timePoints.get(i).substring(0, 2)); int min = Integer.parseInt(timePoints.get(i).subst...
class Solution { public: int findMinDifference(vector<string>& timePoints) { unordered_set<string> st; for(auto &i: timePoints) { if(st.count(i)) return 0; st.insert(i); } int ans = INT_MAX; int first = -1,prev = 0; // first variable will take ...
var findMinDifference = function(timePoints) { const DAY_MINUTES = 24 * 60; const set = new Set(); for (let index = 0; index < timePoints.length; index++) { const time = timePoints[index]; const [hours, minutes] = time.split(':'); const totalMinutes = hours * 60 + +minutes; ...
Minimum Time Difference
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces,...
class Solution: def decodeString(self, s): it, num, stack = 0, 0, [""] while it < len(s): if s[it].isdigit(): num = num * 10 + int(s[it]) elif s[it] == "[": stack.append(num) num = 0 stack.append("") ...
class Solution { public String decodeString(String s) { int bb = s.indexOf('['); // location of beginning bracket int nbb = s.indexOf('[', bb + 1); // location of next beginning bracket int eb = s.indexOf(']'); // location of ending bracket int n = 0; // number of times to repeat ...
class Solution { public: string decodeString(string s) { stack<char> st; for(int i = 0; i < s.size(); i++){ if(s[i] != ']') { st.push(s[i]); } else{ string curr_str = ""; while(st.top() != '['){ ...
var decodeString = function(s) { const stack = []; for (let char of s) { if (char === "]") { let curr = stack.pop(); let str = ''; while (curr !== '[') { str = curr+ str; curr = stack.pop(); } let num = ""; ...
Decode String
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you ca...
class Solution: flips = [11, 23, 38, 89, 186, 308, 200, 464, 416] def minFlips(self, mat: List[List[int]]) -> int: mask = self.make_mask(mat) check = self.make_mask([[1 for c in r] for r in mat]) min_steps = -1 last = 0 for x in range(2**9): x = x & check...
class Solution { public int minFlips(int[][] mat) { int m = mat.length, n = mat[0].length; Set<Integer> visited = new HashSet<>(); Queue<Integer> queue = new LinkedList<>(); int steps = 0; int initialState = toBinary(mat); queue.add(initialState); vis...
class Solution { public: bool check(string str) { for(auto &i: str) if(i=='1') return false; return true; } int minFlips(vector<vector<int>>& mat) { int m = mat.size(); int n = mat[0].size(); string str = ""; for(auto &i: mat) { ...
// Helper counts how many ones are in the matrix to start with. O(mn) var countOnes = function(mat) { let count = 0; for (let r = 0; r < mat.length; r++) { count += mat[r].reduce((a, b) => a + b); } return count; } // Helper flips a cell and its neighbors. Returns updated number of ones left in...
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
You are given an m x n integer matrix grid​​​. A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the co...
class Solution: def getBiggestThree(self, grid: List[List[int]]) -> List[int]: def calc(l,r,u,d): sc=0 c1=c2=(l+r)//2 expand=True for row in range(u,d+1): if c1==c2: sc+=grid[row][c1] else: sc+=grid[row][c1]+grid[row][c2] ...
class Solution { public int[] getBiggestThree(int[][] grid) { int end = Math.min(grid.length, grid[0].length); int maxThree[] = {0,0,0}; for(int length=0; length<end; length++){ searchBigThree(grid, maxThree, length); } Arrays.sort(maxThree); // If there...
class Solution { public: vector<int> getBiggestThree(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); set<int> s; // 1x1, 3x3, 5x5 for (int len = 1; len <= min(m, n); len += 2) { for (int i = 0; i + len <= n; i ++) { for (int j = 0; ...
var getBiggestThree = function(grid) { const m = grid.length; const n = grid[0].length; const set = new Set(); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { let sum = grid[i][j]; set.add(sum) let len = 1; let row = i; ...
Get Biggest Three Rhombus Sums in a Grid
You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 &lt;= i &lt; n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute...
class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) diff = [] sum = 0 for i in range(n): temp = abs(nums1[i]-nums2[i]) diff.append(temp) sum += temp nums1.sort() best_diff = [] ...
class Solution { public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { int mod = (int)1e9+7; // Sorted copy of nums1 to use for binary search int[] snums1 = nums1.clone(); Arrays.sort(snums1); int maxDiff = 0; // maximum difference between original and new ab...
class Solution { public: int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) { long sum=0, minSum; vector<int> nums=nums1; int n=nums.size(); // Calculate the current sum of differences. for(int i=0;i<n;i++) sum+=abs(nums1[i]-nums2[i]); sort(nums.begin(), nums.end(...
var minAbsoluteSumDiff = function(nums1, nums2) { const MOD = 1e9 + 7; const n = nums1.length; const origDiffs = []; let diffSum = 0; for (let i = 0; i < n; i++) { const num1 = nums1[i]; const num2 = nums2[i]; const currDiff = Math.abs(num1 - num2); origDiffs[i] =...
Minimum Absolute Sum Difference
The set [1, 2, 3, ...,&nbsp;n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. &nbsp; Example 1: Input: n = 3, k = 3 Output: ...
class Solution: def nextPermutation(self, nums: List[int]): n = len(nums) high = n-1 low = -1 for i in range(n-1, 0, -1): if nums[i] > nums[i-1]: low = i-1 break if low == -1: nums[low+1:] = reversed(nums[low+1:]) ...
class Solution { public String getPermutation(int n, int k) { int fact = 1; List<Integer> nums = new ArrayList<>(); for(int i = 1; i<n; i++){ fact = fact * i; nums.add(i); } nums.add(n); // Add last permutation number. String res = ""; ...
class Solution { public: string getPermutation(int n, int k) { int fact=1; vector<int> numbers; for(int i=1;i<n;i++){ fact=fact*i; numbers.push_back(i); } numbers.push_back(n); string ans=""; k=k-1; while(true){ ans=...
const dfs = (path, visited, result, numbers, limit) => { // return if we already reached the permutation needed if(result.length === limit) { return; } // commit the result if(path.length === numbers.length) { result.push(path.join('')) return; } // easier t...
Permutation Sequence
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. &nbsp; Example 1: Input: head = [-10,...
class Solution: def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: arr = [] while head: arr.append(head.val) head = head.next def dfs(left, right): if left > right: return m = (left + right)//2 return TreeNod...
class Solution { public TreeNode sortedListToBST(ListNode head) { ListNode tmp = head; ArrayList<Integer> treelist = new ArrayList<>(); while(tmp != null) { treelist.add(tmp.val); tmp = tmp.next; } ...
class Solution { public: typedef vector<int>::iterator vecIt; TreeNode* buildTree(vector<int>& listToVec, vecIt start, vecIt end) { if (start >= end) return NULL; vecIt midIt = start + (end - start) / 2; TreeNode* newNode = new TreeNode(*midIt); newNode->left = bu...
var sortedListToBST = function(head) { if(!head) return null; if(!head.next) return new TreeNode(head.val); let fast = head, slow = head, prev = head; while(fast && fast.next) { prev = slow; slow = slow.next; fast = fast.next.next; } const root = new TreeNode(sl...
Convert Sorted List to Binary Search Tree
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. &nbsp; Example 1: Input: target = 7, nums = [2,3,1,2,4,3...
class Solution: def minSubArrayLen(self, target, nums): # Init left pointer and answer l, ans = 0, len(nums) + 1 # Init sum of subarray s = 0 # Iterate through all numbers as right subarray for r in range(len(nums)): # Add right number to sum s += nums[r] # Check fo...
class Solution { public int minSubArrayLen(int target, int[] nums) { int left = 0; int n = nums.length; int sum = 0; int minCount = Integer.MAX_VALUE; for(int i = 0;i<n;i++){ sum += nums[i]; while(sum >= target){ minCount = Math.min(min...
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { int m=INT_MAX,s=0,l=0; for(int i=0;i<nums.size();i++) { s+=nums[i]; if(s>=target) m=min(m,i-l+1); while(s>=target) { m=min(m,i-l+1); ...
/** * @param {number} target * @param {number[]} nums * @return {number} */ var minSubArrayLen = function(target, nums) { let indexStartPosition = 0; let sum = 0; let tempcounter = 0; let counter = Infinity; for(var indexI=0; indexI<nums.length; indexI++){ sum = sum + nums[indexI]; ...
Minimum Size Subarray Sum
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. For exampl...
##################################################################################################################### # Problem: Wiggle Subsequence # Solution : Dynamic Programming # Time Complexity : O(n) # Space Complexity : O(1) ######################################################################################...
class Solution { int n; int dp[][][]; public int wiggleMaxLength(int[] nums) { n = nums.length; dp = new int[n][1005][2]; for(int i = 0; i < n; i++){ for(int j = 0; j < 1005; j++){ Arrays.fill(dp[i][j] , -1); } } int pos = f(0 ,...
class Solution { public: int wiggleMaxLength(vector<int>& nums) { vector<vector<int>> dp(2, vector<int>(nums.size(),0)); int ans = 1, high, low; dp[0][0] = dp[1][0] = 1; for(int i=1; i<nums.size(); ++i){ high = low = 0; for(int j=0; j<i; ++j){ ...
/** * @param {number[]} nums * @return {number} */ var wiggleMaxLength = function(nums) { //two pass //assume we start with positive or start with negative //choose the longest of the two return Math.max(helper(nums,true),helper(nums,false)) }; const helper = (nums, start) =>{ let l = 0 let...
Wiggle Subsequence
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. &nbsp; Example 1: Input: nums = [2,1,2] Output: 5 Example 2: Input: nums = [1,2,1] Output: 0 &nbsp; Constraints:...
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums=sorted(nums,reverse=True) l=len(nums) for i in range(l-2): if nums[i]<nums[i+1]+nums[i+2]: #condition if triangle can be formed return nums[i]+nums[i+1]+nums[i+2] return 0
class Solution { public int largestPerimeter(int[] nums) { Arrays.sort(nums); for(int i = nums.length - 3; i >= 0; i--) { if(nums[i] + nums[i + 1] > nums[i + 2]) return nums[i] + nums[i + 1] + nums[i + 2]; } return 0; } }
class Solution { public: int largestPerimeter(vector<int>& nums) { // sort the elements sort(nums.begin(),nums.end()); // iterate in everse order to get maximum perimeter for (int i=nums.size()-2; i>=1 ; i--){ //Triangle is formed if sum of two sides is greater than third side if (nums...
/** * @param {number[]} nums * @return {number} */ var largestPerimeter = function(nums) { const sorted=nums.sort((a,b)=>a-b); const result=[]; for(let i=0;i<sorted.length;i++){ if((sorted[i]+sorted[i+1]>sorted[i+2])&&(sorted[i+2]+sorted[i+1]>sorted[i])&&(sorted[i]+sorted[i+2]>sorte...
Largest Perimeter Triangle
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. &nbsp; Example 1: Input: s = "aaabbb" Output: true Explanation: The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. Hence, every 'a' app...
class Solution: def checkString(self, s: str) -> bool: if "ba" in s: return False else: return True
class Solution { public boolean checkString(String s) { for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == 'b'){ for(int j = i+1; j < s.length(); j++){ if(s.charAt(j) == 'a'){ return false; } } ...
class Solution { public: bool checkString(string s) { for(int i = 1; i < s.size(); i++){ if(s[i - 1] == 'b' && s[i] == 'a'){ return false; } } return true; } };
var checkString = function(s) { // a cannot come after b let violation = "ba"; return s.indexOf(violation, 0) == -1; };
Check if All A's Appears Before All B's
Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right...
# 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 isValidBST(self, root: Optional[TreeNode]) -> bool: def valid(node,left,right): if not node: # checking node is...
class Solution { public boolean isValidBST(TreeNode root) { return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public boolean dfs(TreeNode root, int min, int max) { if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) || ...
// We know inorder traversal of BST is always sorted, so we are just finding inorder traversal and check whether it is in sorted manner or not, but only using const space using prev pointer. class Solution { public: TreeNode* prev; Solution(){ prev = NULL; } bool isValidBST(TreeNode* root) { ...
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isValidBST = fun...
Validate Binary Search Tree
Given a string s which represents an expression, evaluate this expression and return its value.&nbsp; The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any buil...
class Solution: def calculate(self, s: str) -> int: stack = [] currentNumber = 0 operator = '+' operations = '+-/*' for i in range(len(s)): ch = s[i] if ch.isdigit(): currentNumber = currentNumber * 10 + int(ch) if ch in op...
class Solution { public int calculate(String s) { if(s==null ||s.length()==0)return 0; Stack<Integer> st = new Stack<>(); int curr=0; char op = '+'; char [] ch = s.toCharArray(); for(int i=0;i<s.length();i++){ if(Character.isDigit(ch[i])){ ...
class Solution { public: int calculate(string s) { stack<int> nums; stack<char> ops; int n = 0; for(int i = 0; i < s.size(); ++i){ if(s[i] >= '0' && s[i] <= '9'){ string t(1, s[i]); n = n*10 + stoi(t); }else if( s[i] == '+' || s...
/** * @param {string} s * @return {number} */ var calculate = function(s) { const n = s.length; let currNum = 0, lastNum = 0, res = 0; let op = '+'; for (let i = 0; i < n; i++) { let currChar = s[i]; if (currChar !== " " && !isNaN(Number(currChar))) { currNum...
Basic Calculator II
Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) &nbsp; Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4] Exam...
function preorder(root: Node | null): number[] { const res: number[] = []; const getNodeVal = (node: Node | null): void => { if (node) { res.push(node.val); for (let i = 0; i < node.children.length; i++) { getNodeVal(node.children[i]); } } }; getNodeVal(root); return res;...
class Solution { public List<Integer> preorder(Node root) { if (root == null) return new ArrayList<Integer>(); Stack<Node> stk = new Stack<Node>(); ArrayList<Integer> arr = new ArrayList<Integer>(); stk.push(root); Node ref; while(!stk.empty()) { ...
class Solution { public: vector<int> preorder(Node* root) { vector<int>ans; stack<Node*>st; st.push(root); while(!st.empty()){ auto frnt=st.top(); st.pop(); ans.push_back(frnt->val); for(int i=frnt->children.size()-1;i>=0;i--){ ...
var preorder = function(root) { return [root.val].concat(root.children.map( (c)=>c ? preorder(c) : [] ).flat() ); };
N-ary Tree Preorder Traversal
A tree is an undirected graph in which any two vertices are connected by&nbsp;exactly&nbsp;one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes&nbsp;labelled from 0 to n - 1, and an array of&nbsp;n - 1&nbsp;edges where edges[i] = [ai, bi] indicates that there is an und...
class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n==0: return [] if n==1:return [0] adj=[[] for i in range (n)] degree=[0]*n for i in edges: adj[i[0]].append(i[1]) adj[i[1]].append(i[0]) ...
class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { if(edges.length == 0) { List<Integer> al = new ArrayList<>(); al.add(0); return al; } HashMap<Integer, Set<Integer>> map = new HashMap<>(); // map == graph int [] degr...
class Solution { public: int getheight(vector<int> a[],int sv,int n) { int lvl = 0; vector<int> vis(n,0); queue<int> q; q.push(sv); vis[sv] = 0; while(q.size()) { int sz = q.size(); lvl++; while(sz--) { ...
var findMinHeightTrees = function(n, edges) { //edge case if(n <=0) return []; if(n === 1) return [0] let graph ={} let indegree = Array(n).fill(0) let leaves = [] // build graph for(let [v,e] of edges){ //as this is undirected graph we will build indegree for both e...
Minimum Height Trees
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k. &nbsp; Example 1: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2 Explanation: Because the sum of the ...
class Solution: def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: import numpy as np matrix = np.array(matrix, dtype=np.int32) M,N = matrix.shape ret = float("-inf") CUM = np.zeros((M,N), dtype=np.int32) for shift_r...
class Solution { public int maxSumSubmatrix(int[][] matrix, int tar) { int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar; for(i=0;i<n;i++){ for(j=0;j<m;j++){ dp[i][j]=matrix[i][j]; if(j>0) dp[i][j]+=...
class Solution { public: // function for finding maximum subarray having sum less than k int find_max(vector<int>& arr, int k) { int n = arr.size(); int maxi = INT_MIN; // curr_sum will store cumulative sum int curr_sum = 0; // set will store the prefix sum of a...
/** * @param {number[][]} matrix * @param {number} k * @return {number} */ var maxSumSubmatrix = function(matrix, k) { if (!matrix.length) return 0; let n = matrix.length, m = matrix[0].length; let sum = new Array(n + 1).fill(0).map(a => new Array(m + 1).fill(0)); let ans = -Infinity; for (let...
Max Sum of Rectangle No Larger Than K
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-v...
class Solution: def minFlips(self, s: str) -> int: prev = 0 start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize odd = len(s)%2 for val in s: val = int(val) if val == prev: if odd: start_0_odd = min(start...
class Solution { public int minFlips(String s) { /* * Sliding Window Approach */ int n = s.length(); int mininumFlip = Integer.MAX_VALUE; int misMatchCount = 0; for(int i = 0; i < (2 * n); i++){ int ...
class Solution { public: int minFlips(string s) { int n = s.size(); string ss = s+s; string s1, s2; int ans = INT_MAX; for(int i=0; i<ss.size(); i++) { s1+=(i%2?'1':'0'); s2+=(i%2?'0':'1'); } int ans1 = 0, ans2 = 0; for(int i=0; i<ss.size(); i++) ...
/** * @param {string} s * @return {number} */ var minFlips = function(s) { let length = s.length-1 let flipMap = { '1': '0', '0': '1' } s = s + s let alt1 = '1' let alt2 = '0' let left = 0 let right = 0 let diff1 = 0 let diff2 = 0 let min = Infinity wh...
Minimum Number of Flips to Make the Binary String Alternating
You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusi...
from itertools import accumulate class Solution: def rangeSum(self, nums, n, left, right): acc = [] for i in range(n): acc.extend(accumulate(nums[i:])) acc.sort() return sum(acc[left - 1:right]) % (10**9 + 7)
class Solution { private static int mod=(int)1e9+7; public int rangeSum(int[] nums, int n, int left, int right) { PriorityQueue<int[]> pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]); for(int i=0;i<n;i++) pq.add(new int[]{i,nums[i]}); int ans=0; for(int i=...
class Solution { public: int rangeSum(vector<int>& nums, int n, int left, int right) { const int m= 1e9+7; // To return ans % m int ans=0; // Final Answer int k=1; // For 1 based indexing int size= (n*(n+1))/2; // We can form n(n+1)/2 subarrays for an array of size n ...
var rangeSum = function(nums, n, left, right) { const sums = []; for (let i = 0; i < nums.length; i++) { let sum = 0; for (let j = i; j < nums.length; j++) { sum += nums[j]; sums.push(sum); } } sums.sort((a, b) => a - b); let an...
Range Sum of Sorted Subarray Sums
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could ...
class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: hashmap1 = {} hashmap2 = {} common = {} for i in range(len(list1)): hashmap1[list1[i]] = i for j in range(len(list2))...
class Solution { public String[] findRestaurant(String[] list1, String[] list2) { List<String> l1 = Arrays.asList(list1); int least = Integer.MAX_VALUE; List<String> returnArray = new ArrayList<>(); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < list2.length...
class Solution { public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { vector<string>vc; unordered_map<string,int>umap,umap1; for(int i=0;i<list1.size();i++) { umap[list1[i]]=i; } for(int i=0;i<list...
var findRestaurant = function(list1, list2) { let obj ={} for(let i =0; i <list1.length; i ++){ if(list2.indexOf(list1[i]) !==-1){ const sum = i+ list2.indexOf(list1[i]) if(obj[sum]!==undefined) { obj[sum]['value'].push(list1[i]) ...
Minimum Index Sum of Two Lists
Given an integer num, find the closest two integers in absolute difference whose product equals&nbsp;num + 1&nbsp;or num + 2. Return the two integers in any order. &nbsp; Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 &amp; 3, for num + 2 = 10, the closest divisors a...
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(int((num+2) ** (0.5)), 0, -1): if not (num+1) % i: return [i, (num+1)//i] if not (num+2) % i: return [i, (num+2)//i] return []
class Solution { public int[] closestDivisors(int num) { int ans[]=new int[2]; double a=Math.sqrt(num+1); double b=Math.sqrt(num+2); if(num==1){ ans[0]=1; ans[1]=2; return ans; } else if(a%1==0){ ans[0]=(int)a; ...
class Solution { public: vector<int> findnumbers(int num) { int m=sqrt(num); while(num%m!=0) { m--; } return {num/m,m}; } vector<int> closestDivisors(int num) { vector<int> ans1=findnumbers(num+1); vector<int> ans2=findnumbers(num+2); if(abs(ans1[0]-ans1[1])<abs(ans2[0]-ans2[1])) return an...
/** * @param {number} num * @return {number[]} */ var closestDivisors = function(num) { const n1 = num + 1; const n2 = num + 2; let minDiff = Infinity; let result = []; for(let i = Math.floor(Math.sqrt(n2)); i >= 1; i--) { if(n1 % i === 0) { const diff = Math.abs(i - (n1 / i)...
Closest Divisors
Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. &nbsp; Example 1: Input: s = "bbbab" Output: 4 Explanation: One possible longest palind...
class Solution: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) dp = [[0 for x in range(n)] for x in range(n)] for i in range(n): dp[i][i] = 1 # Single length strings are palindrome for chainLength in range(2, n+1): for i in range(0, n-chainLength+1): # Disca...
class Solution { public int longestPalindromeSubseq(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); String s2 = sb.toString(); return longestCommonSubsequence(s,s2); } public int longestCommonSubsequence(String text1, String text2) { int [][]dp ...
class Solution { public: int longestPalindromeSubseq(string s) { int n = s.size(); int dp[n][n]; memset(dp, 0, sizeof(dp)); for(int i = 0; i < n; i++){ dp[i][i] = 1; } int res = 1; for(int j = 1; j < n; j++){ for(int r = 0, c = j ; r < ...
var longestPalindromeSubseq = function(s) { const { length } = s; const dp = Array(length).fill('').map(() => Array(length).fill(0)); for (let start = 0; start < length; start++) { const str = s[start]; dp[start][start] = 1; for (let end = start - 1; end >= 0; end--) { ...
Longest Palindromic Subsequence
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 n, return its complement. &nbsp; Example 1: Input: n = 5 Out...
class Solution: def bitwiseComplement(self, n: int) -> int: cnt=0 ans=0 if n==0: return 1 while n>0: if n&1: cnt+=1 else: ans =ans +(2**cnt) cnt+=1 n=n>>1 return ans
class Solution { public int bitwiseComplement(int n) { String bin = Integer.toBinaryString(n); String res = ""; for(char c :bin.toCharArray()) { if( c == '1') res += "0"; else res += "1"; } return Integer.parseIn...
class Solution { public: int bitwiseComplement(int num) { //base case if(num == 0) return 1; unsigned mask = ~0; while( mask & num ) mask = mask << 1; return ~num ^ mask; } };
var bitwiseComplement = function(n) { let xor = 0b1; let copy = Math.floor(n / 2); while (copy > 0) { xor = (xor << 1) + 1 copy = Math.floor(copy / 2); } return n ^ xor; };
Complement of Base 10 Integer
You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated...
class Solution: def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: n = len(s) max_chunk_sz = n // k d = collections.Counter(s) chars = sorted([c for c in d if d[c] >= k], reverse=True) if not chars: return '' old_cand = chars ...
class Solution { char[] A; public String longestSubsequenceRepeatedK(String s, int k) { A = s.toCharArray(); Queue<String> queue = new ArrayDeque<>(); queue.offer(""); String ans = ""; int[] count = new int[26]; BitSet bit = new BitSet(); for (char ch : A)...
class Solution { public: int Alpha=26; bool find(string &s,string &p,int k) { int j=0; int n=s.size(); int count=0; for(int i=0;i<n;i++) { if(s[i]==p[j]) { j++; if(j==p.size()) { ...
// Idea comes from: // https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1471930/Python-Answer-is-not-so-long-explained var longestSubsequenceRepeatedK = function(s, k) { const freq = {}; for (const c of s) { if (!freq[c]) freq[c] = 0; freq[c]++; } // Find hot string let hot...
Longest Subsequence Repeated k Times
Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise. &nbsp; Example 1: Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palindromes using all characters in s. Some possible constructions "anna" + "elble...
from collections import Counter class Solution: def canConstruct(self, s: str, k: int) -> bool: if k > len(s): return False h = Counter(s) countOdd = 0 for value in h.values(): if value % 2: countOdd += 1 if countOdd > k: r...
class Solution { public boolean canConstruct(String s, int k) { if(k==s.length()) { return true; } else if(k>s.length()) { return false; } Map<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++...
class Solution { public: bool canConstruct(string s, int k) { if(s.size() < k) return false; unordered_map<char, int> m; for(char c : s) m[c]++; int oddFr = 0; for(auto i : m) if(i.second % 2) oddFr++; return oddFr <= k; } };
var canConstruct = function(s, k) { if(s.length < k) return false; // all even all even // all even max k odd const freq = {}; for(let c of s) { freq[c] = (freq[c] || 0) + 1; } let oddCount = 0; const freqOfNums = Object.values(freq); for(let cnt of freqOfNums) { if(...
Construct K Palindrome Strings
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value. &nbsp; Example 1: Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The d...
class Solution: def findClosestNumber1(self, nums: List[int]) -> int: return min(nums, key=lambda x: (abs(x), -x)) def findClosestNumber2(self, nums: List[int]) -> int: return min(nums, key=lambda x: abs(x - .1)) def findClosestNumber3(self, nums: List[int]) -> int: re...
// If absolute of n is less than min, update the closest_num // If absolute of n is same of as min, update the bigger closest_num class Solution { public int findClosestNumber(int[] nums) { int min = Integer.MAX_VALUE, closest_num = 0; for(int n : nums) { if(min > Math.abs(n)) { ...
class Solution { public: int findClosestNumber(vector<int>& nums) { // setting the ans to maximum value of int int ans = INT_MAX ; for(int i : nums){ // checking if each value of nums is less than the max value if(abs(i) < abs(ans)){ ans = i ; //check for the less...
//Solution 1 var findClosestNumber = function(nums) { let pos = Infinity; let neg = -Infinity; for(let i = 0; i < nums.length; i++) { if( nums[i] > 0 ){ if( pos > nums[i] ) pos = nums[i]; } else { if( neg < nums[i] ) ...
Find Closest Number to Zero
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an in...
from math import * class Solution: def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: n=len(dist) # Error Range 10^-9 can be ignored in ceil, so we will subtract this value before taking ceil e=1e-9 mat=[[0 for i in range(n)]for j in range(n)] mat[0][0]=dist...
class Solution { public int minSkips(int[] dist, int speed, int hoursBefore) { int N = dist.length, INF = (int)1e9; int[] dp = new int[N]; Arrays.fill(dp, INF); dp[0]=0; // before we start, we have a time of 0 for 0 cost for (int i = 0 ; i<N; i++){ for (int j = i;...
class Solution { public: vector<int>D; long long s, last; long long memo[1010][1010]; long long dfs_with_minimum_time_with_k_skip(int idx, int k) { if (idx < 0 ) return 0; long long &ret = memo[idx][k]; if (ret != -1 ) return ret; long long d = dfs_with_minimum_time_with_...
var minSkips = function(dist, speed, hoursBefore) { // calculates the time needed to rest const getRestTime = (timeFinished) => { if (timeFinished === Infinity) return 0; return (speed - (timeFinished % speed)) % speed; } // dp is a n x n matrix with // dp[destinationIndex][numRest...
Minimum Skips to Arrive at Meeting On Time
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be returned in lowercase. &nbsp; Ex...
class Solution: import string from collections import Counter def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: #sunday morning hangover solution haha #calling this twice seems unnecesary but whatevs #replace "," with " " (apparently translate() is much qui...
class Solution { public String mostCommonWord(String paragraph, String[] banned) { HashMap<String, Integer> hm = new HashMap<>(); String[] words = paragraph.replaceAll("[!?',;.]"," ").toLowerCase().split("\\s+"); for(int i=0; i<words.length; i++) { if(hm.containsKey(word...
class Solution { public: string mostCommonWord(string paragraph, vector<string>& banned) { string temp; vector<string> words; for(char c:paragraph){ if(isalpha(c) && !isspace(c)) temp+=tolower(c); else{ if(temp.length()) words.push_back(temp); ...
var mostCommonWord = function(paragraph, banned) { paragraph = new Map(Object.entries( paragraph .toLowerCase() .match(/\b[a-z]+\b/gi) .reduce((acc, cur) => ((acc[cur] = (acc[cur] || 0) + 1), acc), {})) .sort((a, b) => b[1] - a[1]) ); for (let i = 0; i < banned.length; i++) paragraph.delete(banned[i]); ret...
Most Common Word
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the t...
class Solution: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: """ timeDur = (timeSeries[0], timeSeries[0] + duration - 1) i = 1 total = 0 while i < len(timeSeries): if timeSeries[i] > timeDur[1]: total += (ti...
// Teemo Attacking // https://leetcode.com/problems/teemo-attacking/ class Solution { public int findPoisonedDuration(int[] timeSeries, int duration) { int sum = 0; for (int i = 0; i < timeSeries.length; i++) { if (i == 0) { sum += duration; } else { ...
class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { int ans=0; int n=timeSeries.size(); for(int i=0;i<n;i++){ ans+=min(duration,(i==n-1?duration:timeSeries[i+1]-timeSeries[i])); } return ans; } };
var findPoisonedDuration = function(timeSeries, duration) { let totalTime=duration for(let i=0;i+1<timeSeries.length;i++){ let diff=timeSeries[i+1]-timeSeries[i] totalTime+= diff>duration ? duration : diff } return totalTime };
Teemo Attacking
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that i...
# 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: ans = False def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: def dfs(node,...
class Solution { public boolean isCousins(TreeNode root, int x, int y) { Set<TreeNode> parentSet = new HashSet<>(); Queue<TreeNode> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int len = q.size(); for (int i = 0; i < len; i++) { ...
class Solution { public: bool isCousins(TreeNode* root, int x, int y) { if(root -> left == NULL || root -> right == NULL) return false; //to store node with parent queue<pair<TreeNode*, TreeNode*> > q; //push root q.push({root, NULL}); //push NULL for level seperation...
var isCousins = function(root, x, y) { let xHeight = 1; let xParent = null; let yHeight = 1; let yParent = null; const helper = (node, depth, parent) => { if(node === null) return null; helper(node.left, depth + 1, node); helper(node.right, depth + 1...
Cousins in Binary Tree
Given an array nums of integers, a move&nbsp;consists of choosing any element and decreasing it by 1. An array A is a&nbsp;zigzag array&nbsp;if either: Every even-indexed element is greater than adjacent elements, ie.&nbsp;A[0] &gt; A[1] &lt; A[2] &gt; A[3] &lt; A[4] &gt; ... OR, every odd-indexed element is great...
class Solution: def solve(self,arr,n,x): idx = 1 ans = 0 while idx < n: if idx == 0: idx += 1 if idx % 2 == x: if arr[idx-1] >= arr[idx]: ans += arr[idx-1] - arr[idx] + 1 arr[idx-1] = arr[idx] - 1 ...
class Solution { /* firstly, check elements in odd indices are greater than its neighbours. if not, decrease its neigbours and update the cost. do same thing for even indices, because there can be two combinations as indicated in question. */ private int calculateCost(i...
class Solution { public: int movesToMakeZigzag(vector<int>& nums) { int oddSum = 0, evenSum = 0; int n = nums.size(); for(int i=0; i<n; i++){ if(i%2 == 0){ int left = i==0?INT_MAX:nums[i-1]; int right = i==n-1?INT_MAX:nums[i+1]; eve...
var movesToMakeZigzag = function(nums) { const n = nums.length; let lastEvenRight = Number.MIN_SAFE_INTEGER; let evenMoves = 0; let lastOddRight = nums[0]; let oddMoves = 0; for (let i = 0; i < n; i++) { const currNum = nums[i]; const nextNum = i < n - 1 ? nums[i + 1] : Number...
Decrease Elements To Make Array Zigzag
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the ro...
class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: self.res=root.val def solving(root): if not root: return 0 current=root.val sleft,sright=float('-inf'),float('-inf') if root.left: sleft=solving(root...
class Solution { int[] ans = new int[1]; public int maxPathSum(TreeNode root) { ans[0]=root.val; //Handle edge case dfs(root); return ans[0]; } public int dfs(TreeNode root){ if(root==null) return 0; int left=Math.max(0,dfs(root.left)); //Check on ...
class Solution { public: int rec(TreeNode* root,int& res ){ if(root==nullptr) return 0; // maximum value from left int l = rec(root->left,res); //maximum value from right int r = rec(root->right,res); //check if path can go through this node ,if yes upadte the result...
var maxPathSum = function(root) { let res = -Infinity; function solve(root){ if(!root){ return 0; } let left = solve(root.left); let right = solve(root.right); //ignore the values with negative sum let leftVal = Math.max(left, 0); let ...
Binary Tree Maximum Path Sum
You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. &nbsp; Example 1: Input: arr = [5,4,3,2,1] Output: ...
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: sortedArr = sorted(arr) posMap = defaultdict(list) for i in range(len(sortedArr)): posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position idx = len(arr) - 1 cnt = 0 ...
/* 1. Generate Right min 2. Generate Left Max 3. Count chunks Pos -->. 0 1 2 3 4 5 6 7 Input --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70 <------------> <--> <-------> <-------> Left Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75 Right Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max 1. At pos ...
class BIT { public: BIT(int capacity) : nodes(capacity + 1, 0) {} BIT(const vector<int>& nums) : nodes(nums.size() + 1, 0) { for (int i = 0; i < nums.size(); ++i) { update(i + 1, nums[i]); } } void update(int idx, int val) { for (int i = idx; i < nodes.size(); i += i & -i) { nodes[i] +...
var maxChunksToSorted = function(arr) { var rmin = new Array(arr.length).fill(0); rmin[arr.length] = Number.MAX_SAFE_INTEGER; for(var i=arr.length-1; i>=0; i--) { rmin[i] = Math.min(arr[i], rmin[i+1]); } var lmax = Number.MIN_SAFE_INTEGER; var count = 0; for(var i=0; i...
Max Chunks To Make Sorted II
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: answer[i] % answer[j] == 0, or answer[j] % answer[i] == 0 If there are multiple solutions, return any of them. &nbsp; Example 1: Input: nums = [1,2,3...
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) dp = [1 for i in range(n)] hashh = [i for i in range(n)] ans_ind = 0 for i in range(1, n): for j in range(0,i): if nums[i]%nu...
class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { Arrays.sort(nums); int N = nums.length; List<Integer> ans =new ArrayList<Integer>(); int []dp =new int[N]; Arrays.fill(dp,1); int []hash =new int[N]; for(int i=0;i<N;i++){ h...
class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { int n = nums.size(); sort(nums.begin(), nums.end()); vector<int> ans; for(int i = 0; i < n; i++) { vector<int> tmp; tmp.push_back...
/** https://leetcode.com/problems/largest-divisible-subset/ * @param {number[]} nums * @return {number[]} */ var largestDivisibleSubset = function(nums) { // Memo this.memo = new Map(); // Sort the array so we can do dynamic programming from last number // We want to start from last number because it will...
Largest Divisible Subset
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;it will automaticall...
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return nums[0] def helper(nums): one, two = 0, 0 for i in nums: temp = max(i + one, two) one =...
class Solution { public int rob(int[] nums) { if(nums.length==1){ return nums[0]; } int[] t = new int[nums.length]; for(int i = 0 ; i < t.length;i++){ t[i] = -1; } int[] k = new int[nums.length]; for(int i = 0 ; i < k.length;i++){ ...
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if(n == 1) { return nums[0]; } //dp[n][2][1] vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(2, vector<int>(2, -1))); int maxm = 0; for(int i...
var rob = function(nums) { let dp = [] dp[0] = [0,0] dp[1] = [nums[0],0] for(let i=2; i<=nums.length;i++){ let val = nums[i-1] let rob = dp[i-2][0] + val let dont = dp[i-1][0] let noFirst = dp[i-2][1] + val let best = (rob>=dont)?rob:dont if(dp[i-1][1...
House Robber II
Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted. &nbsp; Example 1: Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]] Output: 2.00000 Explanatio...
from itertools import combinations class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: maxA = 0 for p1, p2, p3 in combinations(points, 3): x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y...
class Solution { public double largestTriangleArea(int[][] points) { double ans = 0; int n = points.length; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ for(int k=j+1;k<n;k++){ ans = Math.max(ans,0.5*Math.abs(points[i][0]*(points[j][1] - point...
class Solution { public: double largestTriangleArea(vector<vector<int>>& points) { double ans = 0.00000; for(int i = 0; i<points.size(); ++i) for(int j = 0; j<points.size(); ++j) if(i!=j) for(int k = 0; k<points.size(); ++k) if(...
var largestTriangleArea = function(points) { const n = points.length; let maxArea = 0; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { for (k = j + 1; k < n; k++) { const area = calcArea(points[i], points[j], points[k]); maxArea = Math...
Largest Triangle Area
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation. ...
def solveEquation(self, equation: str) -> str: """ O(N)TS """ x, y, p = 0, 0, 1 for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation): g = i.group() if g == '=': p = -1 elif g[-1] == 'x': x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigi...
class Solution { public int[] simplifyEqn(String eqn){ int prevSign = 1; int sumX = 0; int sumNums = 0; for(int i=0;i<eqn.length();){ int coEff = 0; int j = i; while(j<eqn.length() && Character.isDigit(eqn.charAt(j))){ coEff = coEff...
def solveEquation(self, equation: str) -> str: """ O(N)TS """ x, y, p = 0, 0, 1 for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation): g = i.group() if g == '=': p = -1 elif g[-1] == 'x': x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigi...
def solveEquation(self, equation: str) -> str: """ O(N)TS """ x, y, p = 0, 0, 1 for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation): g = i.group() if g == '=': p = -1 elif g[-1] == 'x': x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigi...
Solve the Equation
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space cove...
class Solution: """ 1 <= rects.length <= 100 rects[i].length == 4 -10^9 <= ai < xi <= 10^9 -10^9 <= bi < yi <= 10^9 xi - ai <= 2000 yi - bi <= 2000 All the rectangles do not overlap. At most 10^4 calls will be made to pick. """ def __init__(self, rects: List[List[int]]): ...
class Solution { int[][] rects; TreeMap<Integer, Integer> weightedRectIndex = new TreeMap<>(); int nPoints = 0; Random rng = new Random(); public Solution(int[][] rects) { this.rects = rects; int index = 0; for (int[] rect : rects) { // inserts cumulative wei...
class Solution { public: vector<int> prefix_sum; vector<vector<int>> rects_vec; int total = 0; Solution(vector<vector<int>>& rects) { int cur = 0; for (int i = 0; i < rects.size(); ++i) { cur += (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1); ...
/** /** * @param {number[][]} rects */ var Solution = function(rects) { this.rects = rects; this.map = {}; this.sum = 0; // we put in the map the number of points that belong to each rect for(let i in rects) { const rect = rects[i]; // the number of points can be picked in this re...
Random Point in Non-overlapping Rectangles
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. Al...
''' from collections import deque class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: L=len(grid) def generate_next_state(i,j): return [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)] def valid_state(states): res=[] for (i,j) in states: if i>L-1...
class Solution { public int shortestPathBinaryMatrix(int[][] grid) { int m = grid.length, n = grid[0].length; boolean [][] visited = new boolean [m][n]; int [] up = {0, 0, 1, -1, 1, 1, -1, -1}; int [] down = {-1, 1, 0, 0, -1, 1, -1, 1}; /* i...
class Solution { public: int shortestPathBinaryMatrix(vector<vector<int>>& grid) { int m = grid.size(),n = grid[0].size(); if(grid[0][0]!=0 || grid[m-1][n-1]!=0) return -1; vector<vector<int>> dist(m,vector<int>(n,INT_MAX)); int ans = INT_MAX; queue<pair<int,int>> q; ...
/** * @param {number[][]} grid * @return {number} */ var shortestPathBinaryMatrix = function(grid) { const n = grid.length const directions = [ [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1] ] const visited = [] const distance = [] const predecessor = [] ...
Shortest Path in Binary Matrix
You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers. Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty...
class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: num = m * n res = [[-1 for j in range(n)] for i in range(m)] x, y = 0, 0 dx, dy = 1, 0 while head: res[y][x] = head.val if x + dx < 0 or x + dx >= n or...
class Solution { public int[][] spiralMatrix(int m, int n, ListNode head) { int[][] ans=new int[m][n]; for(int[] arr:ans){ Arrays.fill(arr,-1); } int rowBegin=0; int rowEnd=m-1; int columnBegin=0; int columnEnd=n-1; ListNode cur=he...
class Solution { public: vector<vector<int>> spiralMatrix(int n, int m, ListNode* head) { // Create a matrix of n x m with values filled with -1. vector<vector<int>> spiral(n, vector<int>(m, -1)); int i = 0, j = 0; // Traverse the matrix in spiral form, and update with the values present in...
var spiralMatrix = function(m, n, head) { var matrix = new Array(m).fill().map(()=> new Array(n).fill(-1)) var row=0, col=0; var direction="right"; while(head) { matrix[row][col]=head.val; if(direction=="right") { if(col+1 == n || matr...
Spiral Matrix IV
Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces...
class Solution: def split(self, s: str, delimiter=" ") -> List[str]: start, end = 0, 0 res = [] for ch in s: if ch == delimiter: if start == end: start += 1 else: res.append(s[start:end]) ...
class Solution { public String reverseWords(String s) { String[] arr = s.replaceAll("\\s{2,}", " ").split(" "); // splitting based on while spaces by replaceing spaces by single gap int n = arr.length; String temp = ""; for(int i =0;i<n/2;i++){ temp = arr[i]; ...
class Solution { public: string reverseWords(string s) { int i=0; string res = ""; while(i<s.length()) { while(i<s.length() && s[i]==' ') i++; if(i>=s.length()) break; int j=i+1; while(j<s.length() && ...
var reverseWords = function(s) { return s.split(" ").filter(i => i).reverse().join(" "); };
Reverse Words in a String
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 &lt;= k &lt;= removable.length) such that, after removing k characters from s using the first k ...
class Solution: def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: def check(m): i = j = 0 remove = set(removable[:m+1]) while i < len(s) and j < len(p): if i in remove: i += 1 continue ...
class Solution { public int maximumRemovals(String s, String p, int[] removable) { int left = 0, right = removable.length; while (left < right) { int middle = (right + left + 1) / 2; String afterRemoval = remove(s, removable, middle); if (isSubsequence(p, afterRe...
class Solution { public: bool isSubSequence(string str1, string str2){ int j = 0,m=str1.size(),n=str2.size(); for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; return (j == m); } int maximumRemovals(string s, string p, vector<int>& removabl...
var maximumRemovals = function(s, p, removable) { let arr = s.split(''); const stillFunctions = (k) => { let result = [...arr]; for(let i = 0; i < k; i++) { result[removable[i]] = ''; } const isSubset = () => { let idx = 0; for(let c = 0;...
Maximum Number of Removable Characters
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. Any student is eligible for an attendance award if they mee...
class Solution: def checkRecord(self, n: int) -> int: if n == 1: return 3 if n==2: return 8 """ Keep track of last 2 digits ways to get ll = last combinations ending with p,l (l,l not allowed) ways to get lp = last combinations ending with l,p ...
class Solution { int mod=1000000000+7; public int checkRecord(int n) { int[][][] cache=new int[n+1][2][3]; for(int i=0; i<=n; i++){ for(int j=0; j<2; j++){ for(int k=0; k<3; k++)cache[i][j][k]=-1; } } return populate(n, 0, 1, 2, cache); ...
class Solution { public: int mod = 1e9+7; int dp[100001][10][10]; int recur(int abs,int late,int n){ if(abs > 1){ return 0; } if(late >= 3){ return 0; } if(n == 0){ return 1; } if(dp[n][late][abs] != -1)...
/** * @param {number} n * @return {number} */ var checkRecord = function(n) { /** * P(n) = A(n - 1) + P(n - 1) + L(n - 1), n ≥ 2. * L(n) = A(n - 1) + P(n - 1) + A(n - 2) + P(n - 2), n ≥ 3. * A(n) = A(n - 1) + A(n - 2) + A(n - 3), n ≥ 4. */ const m = 1000000007; const P = Array(n); const A = Array...
Student Attendance Record II
Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Removes the value key in the HashSet. If key does not exist in the Hash...
class MyHashSet: def __init__(self): self.hash_list = [0]*10000000 def add(self, key: int) -> None: self.hash_list[key]+=1 def remove(self, key: int) -> None: self.hash_list[key] = 0 def contains(self, key: int) -> bool: if self.hash_list[key] > 0: return ...
class MyHashSet { ArrayList<LinkedList<Integer>> list; int size = 100; public MyHashSet() { list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(new LinkedList<Integer>()); } } public int hash(int key) { return key % list.size(); } public int search(int key) { int i = hash(key)...
class MyHashSet { vector<int> v; public: MyHashSet() { } void add(int key) { auto it = find(v.begin(), v.end(), key); if(it == v.end()){ v.push_back(key); } } void remove(int key) { auto it = find(v.begin(), v.end(), key); if(it != v.end())...
var MyHashSet = function() { // Really you should just // Make your own object, but instead // we have attached ourself to the // `this` object which then becomes our hashmap. // What you should instead do is this: // this.hash_map = {} // And then update our following functions };...
Design HashSet
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. For example, given num = 2932, you have the following digits: two 2's, one ...
class Solution: def minimumSum(self, num: int) -> int: s=list(str(num)) s.sort() return int(s[0]+s[2])+int(s[1]+s[3])
class Solution { public int minimumSum(int num) { int[] dig = new int[4]; // For each digit int cur = 0; while(num > 0) // Getting each digit { dig[cur++] = num % 10; num /= 10; } Arrays.sort(dig); // Ascending order int num1 = dig[...
class Solution{ public: int minimumSum(int num){ string s = to_string(num); sort(s.begin(), s.end()); int res = (s[0] - '0' + s[1] - '0') * 10 + s[2] - '0' + s[3] - '0'; return res; } };
var minimumSum = function(num) { let numbers = [] for(let i = 0; i<4; i++){ numbers.push(~~num % 10) num /= 10 } const sorted = numbers.sort((a,b) => b - a) return sorted[0] + sorted[1] + (10 *( sorted[2] + sorted[3])) };
Minimum Sum of Four Digit Number After Splitting Digits
A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. &nbsp; Example 1: Input: arr = [3,5,1] Output: true Expla...
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: arr.sort() check = arr[0] - arr[1] for i in range(len(arr)-1): if arr[i] - arr[i+1] != check: return False return True
class Solution { public boolean canMakeArithmeticProgression(int[] arr) { if(arr.length < 1) return false; Arrays.sort(arr); int diff = arr[1]-arr[0]; for(int i=1;i<arr.length-1;i++){ if(arr[i+1]-arr[i]!=diff){ return false; } ...
class Solution { public: bool canMakeArithmeticProgression(vector<int>& arr) { sort(arr.begin() , arr.end()); int diff = arr[1] - arr[0]; for(int i=1;i<arr.size();i++){ if(diff != arr[i] - arr[i-1]){ return false; } } return true; }...
var canMakeArithmeticProgression = function(arr) { arr.sort(function(a,b){return a-b}); var dif = arr[1] - arr[0]; for(var i=2;i<arr.length;i++){ if(arr[i]-arr[i-1] !== dif){ return false; } } return true; };
Can Make Arithmetic Progression From Sequence
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. &nbsp; Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since i...
class Solution: def missingNumber(self, nums: List[int]) -> int: # T.C = O(n) S.C = O(1) actualsum = 0 currentsum = 0 i = 1 for num in nums: currentsum += num actualsum += i i += 1 return actualsum - currentsum
// Approach 1: Find diff class Solution { public int missingNumber(int[] nums) { int n = nums.length; int expectedSum = (n * (n + 1)) / 2; for (int num : nums) expectedSum -= num; return expectedSum; } } // Approach 2: XOR class Solution { public int missingNumb...
class Solution { public: int missingNumber(vector<int>& nums) { int n=nums.size(); long sum=n*(n+1)/2; long temp=0; for(int i=0;i<n;i++) { temp+=nums[i]; } return sum-temp; } };
var missingNumber = function(nums) { return ((1 + nums.length)*nums.length/2) - nums.reduce((a,b) => a+b) };
Missing Number
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix height...
class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: # Purpose: find the cells that allow rain flow into the ocean # Method: DFS # Intuition: start from each border, check cell and neb, if OK, append to res # init: res, vis (pac, atl), ...
class Solution { public List<List<Integer>> pacificAtlantic(int[][] heights) { if (heights == null) return null; if (heights.length == 0) return null; if (heights[0].length == 0) return null; /** */ boolean [][] po = new boolean[heights.length][heights[0].length]; bo...
class Solution { public: void dfs(vector<vector<int>>& heights,vector<vector<bool>>&v,int i,int j) { int m=heights.size(); int n=heights[0].size(); v[i][j]=true; if(i-1>=0&&v[i-1][j]!=true&&heights[i-1][j]>=heights[i][j]) { dfs(heights,v,i-1,j); } ...
`/** * @param {number[][]} heights * @return {number[][]} */ var pacificAtlantic = function(heights) { let atlantic = new Set(); let pacific = new Set(); let rows = heights.length; let cols = heights[0].length; for (let c = 0; c < cols; c++) { explore(heights, 0, c, pacific, heights[0][c...
Pacific Atlantic Water Flow
You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 &lt;= i &lt; n, the digit i occurs num[i] times in num, otherwise return false. &nbsp; Example 1: Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] =...
from collections import Counter class Solution: def digitCount(self, num: str) -> bool: d = Counter(num) for i in range(len(num)): if int(num[i])!=d.get(str(i), 0): return False return True
class Solution { public boolean digitCount(String num) { int[] freqArr = new int[10]; // n = 10 given in constraints; for(char ch : num.toCharArray()){ freqArr[ch-'0']++; } for(int i=0;i<num.length();i++){ int freq = num.charAt(i)-'...
class Solution { public: bool digitCount(string num) { unordered_map<int,int> mpp; int n= num.length(); for(auto it:num){ int x = it - '0'; mpp[x]++; // Store the frequency of the char as a number } for(int i=0;i<n;i++){ int x = num[i] - '0...
var digitCount = function(num) { const res = [...num].filter((element, index) => { const reg = new RegExp(index, "g"); const count = (num.match(reg) || []).length; return Number(element) === count }) return res.length === num.length };
Check if Number Has Equal Digit Count and Digit Value
You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Re...
class Solution: def reformat(self, s: str) -> str: # Store the alphabets and the numerics from the string in a seperat arrays alpha = [] num = [] # Initiate a res variable to store the resultant string res = '' for i in s: if i.isalpha(): ...
class Solution { public String reformat(String s) { List<Character> ch = new ArrayList<>(); List<Character> d = new ArrayList<>(); for(char c : s.toCharArray()){ if(c >= 'a' && c <= 'z')ch.add(c); else d.add(c); } if(Math.abs...
class Solution { public: string reformat(string s) { string dg,al; for(auto&i:s)isdigit(i)?dg+=i:al+=i; if(abs((int)size(dg)-(int)size(al))>1) return ""; int i=0,j=0,k=0; string ans(size(s),' '); bool cdg=size(dg)>size(al); while(k<size(s)){ if(cdg...
var reformat = function(s) { let letter=[], digit=[]; for(let i=0; i<s.length; i++){ s[i]>=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]); } // impossible to reformat if(Math.abs(letter.length-digit.length)>=2){return ""} let i=0, output=""; while(i<letter.length && i<digit.leng...
Reformat The String
Given a binary array nums, return the maximum number of consecutive 1's in the array. &nbsp; Example 1: Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Example 2: Input: nums = [1,0,1,1,0,1] Output: 2 ...
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: count = maxCount = 0 for i in range(len(nums)): if nums[i] == 1: count += 1 else: maxCount = max(count, maxCount) count = 0 ...
class Solution { public int findMaxConsecutiveOnes(int[] nums) { int max = 0; int new_max = 0; for(int i=0;i<nums.length;i++){ if(nums[i]==1) { max++; } else{ if(max>new_max){ new_max = max; ...
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int curr_count = 0; int max_count = 0; int i = 0; while(i < nums.size()) { if(nums[i] == 1) { curr_count += 1; if(max_count < curr_count) ...
var findMaxConsecutiveOnes = function(nums) { let count =0 let max =0 for(let i=0; i<nums.length; i ++){ if(nums[i]==1){ count ++ } if(nums[i]==0 || i==nums.length-1){ max = Math.max(count,max) count = 0 } } return max };
Max Consecutive Ones
An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i &lt;= j, nums[i] &lt;= nums[j]. An array nums is monotone decreasing if for all i &lt;= j, nums[i] &gt;= nums[j]. Given an integer array nums, return true if the given array is monotonic...
class Solution: def isMonotonic(self, nums: List[int]) -> bool: counter = 0 for i in range(len(nums) - 1): if nums[i] >= nums[i + 1]: counter += 1 if counter == len(nums) - 1: return True counter = 0 for i in range(len(nums) - 1): ...
class Solution { public boolean isMonotonic(int[] nums) { if(nums[0]<nums[nums.length-1]){ for(int i=0;i<nums.length-1;i++){ if(!(nums[i]<=nums[i+1])) return false; } }else{ for(int i=0;i<nums.length-1;i++){ if(!(nums[i]>=nums[i+1])) return fal...
class Solution { public: bool isMonotonic(vector<int>& nums) { auto i = find_if_not(begin(nums), end(nums), [&](int a) {return a == nums.front();}); auto j = find_if_not(rbegin(nums), rend(nums), [&](int a) {return a == nums.back();}); return is_sorted(--i, end(nums)) or is_sorted(--j, rend(...
var isMonotonic = function(nums) { let increasingCount = 0; let decreasingCount = 0; for(let i = 1; i < nums.length; i++){ if(nums[i] > nums[i-1]){ increasingCount++; }else if(nums[i] < nums[i-1]){ decreasingCount++; } } return !(increasingCount &...
Monotonic Array
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. A subarray is defined as a contiguous sequence of numbers in an array. A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l &lt;= i &lt; r, numsi &lt; numsi+1. Note that a subarra...
class Solution: def maxAscendingSum(self, nums: List[int]) -> int: count=nums[0] final=nums[0] for i in range(1,len(nums)): if nums[i]>nums[i-1]: count+=nums[i] else: count=nums[i] final=max(final,count) return final
class Solution { public int maxAscendingSum(int[] nums) { int res = nums[0],temp = nums[0]; for(int i = 1;i<nums.length;i++){ if(nums[i] > nums[i-1]) temp+=nums[i]; else temp = nums[i]; res = Math.max(res,temp); } re...
class Solution { public: int maxAscendingSum(vector<int>& nums) { int max_sum = nums[0], curr = nums[0]; for (int i = 1; i < nums.size(); i++) { if (nums[i-1] < nums[i]) { curr += nums[i]; } else { max_sum = max(max_sum, curr); ...
var maxAscendingSum = function(nums) { const subarray = nums.reduce((acc, curr, index) => { curr > nums[index - 1] ? acc[acc.length - 1] += curr : acc.push(curr); return acc; }, []); return Math.max(...subarray); };
Maximum Ascending Subarray Sum
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a p...
import numpy as np class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: A = np.array(grid) def cumdivs(d): D = sum(A % d**i == 0 for i in range(1, 10)) return D.cumsum(0) + D.cumsum(1) - D return max(np.minimum(cumdivs(2), cumdivs(5)).max() ...
class Solution { public int maxTrailingZeros(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][][] dph = new int[m][n][3]; int[][][] dpv = new int[m][n][3]; int hmax0 = 0; int vmax0 = 0; for (int i = 0; i < m; i++) { for (int j = 0...
array<int, 2> operator+(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] + r[0], l[1] + r[1] }; } array<int, 2> operator-(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] - r[0], l[1] - r[1] }; } int pairs(const array<int, 2> &p) { return min(p[0], p[1]); } class Solution { public: int fa...
var maxTrailingZeros = function(grid) { const m = grid.length; const n = grid[0].length; const postfixCols = []; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { const num = grid[i][j]; if (postfixCols[j] == null) postfixCols[j] = { 2: 0, 5: 0 }; ...
Maximum Trailing Zeros in a Cornered Path
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf...
class Solution: def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: res = [] def dfs(v, path, pathsum): if not v: return path.append(v.val) pathsum += v.val if not v.left and not v.right and pathsum == target...
class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> ans = new ArrayList<>(); pathSum(root, targetSum, new ArrayList<>(), ans); return ans; } public void pathSum(TreeNode root, int targetSum, List<Integer> path, List<List<...
/** * 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) ...
var pathSum = function(root, targetSum) { const paths = []; function dfs(root, sum, curr = []) { if (!root) return; const newCurr = [...curr, root.val]; if (!root.left && !root.right && sum === root.val) return paths.push(newCurr); dfs(root.left, sum - root.val, newCurr); dfs(root.right, sum ...
Path Sum II
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two inte...
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: deltas = [x-y for x, y in zip(gas, cost)] n = len(deltas) deltas = deltas + deltas cursum, curi = 0, 0 maxsum, maxi = 0, 0 for i, delta in enumerate(deltas): cursum = max...
class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // *Upvote will be appreciated* int totalFuel = 0; int totalCost = 0; int n = gas.length; for(int i = 0; i < n; i++) { totalFuel += gas[i]; } for(int i = 0; i < n; i++) { ...
class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); int start = -1; int sum = 0 , gastillnow = 0; for(int i = 0 ; i < 2*n ; i++){ if(start == i%n){ return i%n; } if(gas[i%n] + ...
var canCompleteCircuit = function(gas, cost) { const len = gas.length; // scan forward from the current index const scan = (i) => { let numTries = 0; let tank = 0; let c = 0; while (numTries <= len) { tank -= c; if (tank < 0) return -1; // ...
Gas Station
Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters. &nbsp; Example 1: Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] Example 2: Input: s = "Hello" Output: 1...
class Solution: def countSegments(self, s: str) -> int: return len(s.split())
class Solution { public int countSegments(String s) { int length = 0; boolean flag = false; for(Character c : s.toCharArray()) { if(c == ' ' && flag) { length++; flag = !flag; } else if(c != ' ') { flag = true; ...
class Solution { public: int countSegments(string s) { if(s=="") return 0; int res=0,flag=0; for(int i=0;i<size(s);i++){ if(s[i]!=' '){ i++; while(i<size(s) and s[i]!=' '){ i++; } res+...
/** * @param {string} s * @return {number} */ var countSegments = function(s) { return s.trim() ? s.trim().split(/\s+/).length : 0 };
Number of Segments in a String
Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible. Otherwise, return false. &nbsp; Example 1: Input: nums = [1,2,3,3,4,4,5,6], k = 4 Output: true Explanation: Array can be divided into [1,2,3,4...
class Solution(object): def isPossibleDivide(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if len(nums) % k != 0: return False freq = collections.defaultdict(int) for v in nums: freq[v] += 1 ...
class Solution { public boolean isPossibleDivide(int[] nums, int k) { if (nums.length % k != 0) return false; Map<Integer, Integer> countMap = new HashMap<>(); for (int num : nums) { int count = countMap.getOrDefault(num, 0); countMap.put(num , count + 1); } ...
class Solution { public: bool isPossibleDivide(vector<int>& nums, int k) { if(nums.size() % k) return false; map<int, int> m; for(int i : nums) m[i]++; int n = m.size(); while(n) { int a = m.begin() -> first; m[a]--; if(!m...
var isPossibleDivide = function(nums, k) { if(nums.length % k) { return false; } nums.sort((a, b) => a - b); let numberOfArrays = nums.length / k, index = 0, dp = Array(numberOfArrays).fill(null).map(() => []); dp[0].push(nums[0]); for(let i = 1; i < nums.length; i++) { if(nu...
Divide Array in Sets of K Consecutive Numbers
Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. &nbsp; Example 1: Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["...
import heapq class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: li = {} for i in words: if i in li: li[i]+=1 else: li[i]=1 heap = [] for i in li: heap.append([-li[i],i]) ...
class Solution { public List<String> topKFrequent(String[] words, int k) { Map<String,Integer> map=new LinkedHashMap<>(); for(String word:words) map.put(word,map.getOrDefault(word,0)+1); PriorityQueue<Pair<String,Integer>> queue=new PriorityQueue<>(new Comparator<Pair<String,Int...
class Solution { public: bool static comp(pair<string, int> a, pair<string, int> b){ if(a.second > b.second) return true; else if(a.second < b.second) return false; else{ return a.first < b.first; } } vector<string> topKFrequent(vector<string>& words, int k) { ...
var topKFrequent = function(words, k) { let map=new Map() let res=[] for(let i of words){ if(map.has(i)){ map.set(i,map.get(i)+1) }else{ map.set(i,1) } } res=[...map.keys()].sort((a,b)=>{ if(map.get(a)===map.get(b)){ return b <...
Top K Frequent Words
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions...
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def getNeighbours(row,col,char): neighbours = [] if row > 0 and grid[row-1][col] == char and not visited[row-1][col]: neighbours.append([row-1,col]) if col > 0 and grid[row][c...
class Solution { public boolean containsCycle(char[][] grid) { int rows = grid.length, cols = grid[0].length; // Create a boolean array of same dimensions to keep track of visited cells boolean[][] visited = new boolean[rows][cols]; for (int i = 0; i < rows; i++) { fo...
class Solution { public: int dx[4]={-1,1,0,0}; int dy[4]={0,0,1,-1}; bool solve(vector<vector<char>>& grid,int i,int j,int m,int n,int x,int y,vector<vector<int>>&vis,char startChar){ vis[i][j]=1; for(int k=0;k<4;k++){ int xx=i+dx[k]; int yy=j+dy[k]; if(xx...
/** * @param {character[][]} grid * @return {boolean} */ var containsCycle = function(grid) { const m = grid.length; const n = grid[0].length; const visited = [...Array(m)].map(i => Array(n).fill(0)); const dir = [[-1,0],[1,0],[0,-1],[0,1]]; const dfs = (x,y,lx,ly) => { visit...
Detect Cycles in 2D Grid
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, mu...
class Solution: def minSpaceWastedKResizing(self, A: List[int], K: int) -> int: def waste(i, j, h): sumI = sums[i-1] if i > 0 else 0 return (j-i+1)*h - sums[j] + sumI def dp(i, k): if i <= k: return 0 if k < 0: ...
class Solution { // dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 } public int minSpaceWastedKResizing(int[] nums, int k) { int dp[][]=new int[nums.len...
class Solution { public: int dp[205][205]; #define maxi pow(10,8) #define ll long long int dfs(vector<int>& nums, int idx, int k) { int n = nums.size(); if(idx==n) return 0; if(k<0) return maxi; if(dp[idx][k]!=-1) return dp[idx][k]; ll sum = 0, mx = 0, ans = m...
var minSpaceWastedKResizing = function(nums, k) { var prefixSum = []; // prefix is index 1 based var rangeMax = []; // index 0 based var sum = 0; prefixSum[0] = 0; for (var i = 0; i < nums.length; i++) { sum += nums[i]; prefixSum[i + 1] = sum; } for (var i = 0; i < nums.leng...
Minimum Total Space Wasted With K Resizing Operations
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values ...
class Solution: def maxTwoEvents(self, events: List[List[int]]) -> int: events.sort() heap = [] res2,res1 = 0,0 for s,e,p in events: while heap and heap[0][0]<s: res1 = max(res1,heapq.heappop(heap)[1]) res2 = max(res2,res1+p) heapq.heappush(heap,(e,p)) ...
class Solution { public int maxTwoEvents(int[][] events) { Arrays.sort(events, (a, b) -> a[0] - b[0]); int onRight = 0, maxOne = 0, n = events.length; int[] rightMax = new int[n+1]; for (int i = n - 1; i >= 0; i--) { int start = events[i][0], end = events[i][1], val = eve...
#define ipair pair<int,int> class Solution { public: int maxTwoEvents(vector<vector<int>>& events) { //sort based on smaller start time sort(events.begin(), events.end()); int mx = 0, ans = 0, n = events.size(); priority_queue<ipair, vector<ipair>, greater<>> pq; //...
var maxTwoEvents = function(events) { const n = events.length; events.sort((a, b) => a[0] - b[0]); const minHeap = new MinPriorityQueue({ priority: x => x[1] }); let maxVal = 0; let maxSum = 0; for (let i = 0; i < n; ++i) { const [currStart, currEnd, currVal] = events[i]; wh...
Two Best Non-Overlapping Events
We are playing the Guessing Game. The game will work as follows: I pick a number between&nbsp;1&nbsp;and&nbsp;n. You guess a number. If you guess the right number, you win the game. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. ...
class Solution: def getMoneyAmount(self, n): # For an interval [l,r], we choose a num, which if incorrect still # allows us to know whether the secret# is in either [l,num-1] or # [num+1,r]. So, the worst-case (w-c) cost is ...
class Solution { public int getMoneyAmount(int n) { int dp[][]=new int[n+1][n+1]; for(int a[]:dp){ Arrays.fill(a,-1); } return solve(1,n,dp); } static int solve(int start,int end,int[][] dp){ if(start>=end) return 0; if(dp[start][end]!=-1) return dp[start]...
class Solution { public: vector<vector<int>> dp; int solve(int start, int end) { if(start>= end) return 0; if(dp[start][end] != -1) return dp[start][end]; int ans = 0; int result = INT_MAX; for(int i=start; i<=end; i++) { ...
/** https://leetcode.com/problems/guess-number-higher-or-lower-ii/ * @param {number} n * @return {number} */ var getMoneyAmount = function(n) { // Memo this.memo = new Map(); return dp(n, 0, n); }; var dp = function(n, start, end) { let key = `${start}_${end}`; // Base, there is only 1 node on this ...
Guess Number Higher or Lower II
The Tribonacci sequence Tn is defined as follows:&nbsp; T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n &gt;= 0. Given n, return the value of Tn. &nbsp; Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n = 25 Output: 1389537 &nbsp; Constraints: ...
class Solution: def tribonacci(self, n: int, q={}) -> int: if n<3: q[0]=0 #Initialize first 3 values q[1]=1 q[2]=1 if n not in q: #Have faith that last 3 calls will give the answer :) q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci...
class Solution { public int tribonacci(int n) { if(n==0) return 0; if(n==1) return 1; if(n==2) return 1; int p1=1; int p2=1; int p3=0; int cur=0; for(int i=3;i<=n;i++) { cur=p1+p2+p3; ...
class Solution { public: int tribonacci(int n) { if(n<2) return n; int prev3 = 0; int prev2 = 1; int prev1 = 1; for(int i = 3; i<= n ; i++) { int ans = prev1+ prev2+prev3; prev3 = prev2; prev2 = prev1;...
// Recursive and Memoiztion approach var tribonacci = function(n, cache = {}) { if(n in cache) return cache[n] //Start of Base Cases if(n == 0) return 0 if (n == 1 || n == 2) return 1; // End Of Base Cases // Caching the result cache[n] = tribonacci(n - 1, cache) + tribonacci(n - 2, ca...
N-th Tribonacci Number
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: [4,5,6,7,0,1,4] if it was rotated 4 times. [0,1,4,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in...
class Solution: def findMin(self, nums: List[int]) -> int: return min(nums)
class Solution { public int findMin(int[] nums) { int l = 0; int h = nums.length - 1; while (l < h) { while (l < h && nums[l] == nums[l + 1]) ++l; while (l < h && nums[h] == nums[h - 1]) --h; int mid = l + (h - l) / 2; ...
class Solution { public: int findMin(vector<int>& nums) { int l=0,h=nums.size()-1; while(l<h){ int m=l+(h-l)/2; if(nums[m]<nums[h]) h=m; else if(nums[m]>nums[h]) l=m+1; else h--; } return nums[h]; } };
/** * @param {number[]} nums * @return {number} */ var findMin = function(nums) { let min = Infinity; let l = 0; let r = nums.length - 1; while (l <= r) { const m = Math.floor((l + r) / 2); // Eliminate dupes ......................... only difference from #153 while (l < m &&...
Find Minimum in Rotated Sorted Array II
Given an integer array nums, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the smallest possible size. Return the length of left after such a partitioning. Test cases are generate...
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: prefix = [nums[0] for _ in range(len(nums))] suffix = [nums[-1] for _ in range(len(nums))] for i in range(1, len(nums)): prefix[i] = max(prefix[i-1], nums[i-1]) for i in range(len(nums)-2, -1, -1): ...
class Solution { public int partitionDisjoint(int[] nums) { int mts = nums[0]; // max till scan int mtp = nums[0]; // max till partition int idx = 0; for(int i=1; i<nums.length; i++) { int val = nums[i]; if(val < mtp) { idx = i; ...
class Solution { public: vector<int> tree; void build(vector<int> &nums) { int n=nums.size(); for(int i=0 ; i<nums.size(); i++) tree[i+n]=nums[i]; for(int i=n-1 ; i>0 ; i--) tree[i] = min(tree[i<<1],tree[i<<1|1]); } int query(int l, int r, int n) { l+=n,r+=n; int...
/** * @param {number[]} nums * @return {number} */ var partitionDisjoint = function(nums) { let n = nums.length; let leftMax = Array(n).fill(0), rightMin = Array(n).fill(0); let left = 0, right = n- 1; for(let i = 0, j = n - 1;i<n, j>=0 ;i++,j--){ leftMax[i] = Math.max(nums[i], !i ? -Inf...
Partition Array into Disjoint Intervals
Alice and Bob continue their&nbsp;games with piles of stones.&nbsp; There are a number of&nbsp;piles&nbsp;arranged in a row, and each pile has a positive integer number of stones&nbsp;piles[i].&nbsp; The objective of the game is to end with the most&nbsp;stones.&nbsp; Alice&nbsp;and Bob take turns, with Alice starting...
class Solution: def stoneGameII(self, piles: List[int]) -> int: n = len(piles) dp = {} def recursion(index,M): # if we reached to the end we cannot score any value if index == n: return 0 # we search if we have solved the same case earlier...
class Solution { public int stoneGameII(int[] piles) { Map<String, Integer> memo = new HashMap<>(); int diff = stoneGame(piles,1,0,0,memo); int totalSum = 0; for(int ele: piles) totalSum+=ele; return (diff+totalSum)/2; } public int stoneGame(int[] piles, ...
class Solution { public: int dp[103][103][2]; int rec(int i,int m,int p,vector<int>& piles){ if(i==piles.size()) return 0; if(dp[i][m][p]!=-1) return dp[i][m][p]; int cnt = 0,ans=INT_MIN,n=piles.size(); for(int j=i;j<min(n,i+2*m);j++){ cnt += piles[j]; ans...
var stoneGameII = function(piles) { const length = piles.length; const dp = [...Array(length + 1).fill(null)].map((_) => Array(length + 1).fill(0) ); const sufsum = new Array(length + 1).fill(0); for (let i = length - 1; i >= 0; i--) { sufsum[i] = sufsum[i + 1] + piles[i]; } for (let i = 0; i <= l...
Stone Game II
You are given a string s and an array of strings words. All the strings of words are of the same length. A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated. For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd...
class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: req={} for i in words: req[i]=1+req.get(i,0) l=0 r=len(words)*len(words[0]) ans=[] while r<len(s)+1: i=0 curr={} left, right= l, l+len(word...
class Solution { public List<Integer> findSubstring(String s, String[] words) { HashMap<String, Integer> input = new HashMap<>(); int ID = 1; HashMap<Integer, Integer> count = new HashMap<>(); for(String word: words) { if(!input.containsKey(word)) input.p...
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { int n = words[0].length(); int slen = s.length(); int len = slen - n*words.size(); vector<int> ans; if( len < 0) return ans; string t; unordered_map<string, int> mp; ...
var findSubstring = function(s, words) { let res = []; let wordLength = words[0].length; let wordCount = words.length; let len = wordCount * wordLength; //Length of sliding window let map = {} for (let word of words) map[word] = map[word] + 1 || 1; //Hash word freq for (let i...
Substring with Concatenation of All Words
A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurre...
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: pq = [] if a > 0: heapq.heappush(pq,(-a,'a')) if b > 0: heapq.heappush(pq,(-b,'b')) if c > 0: heapq.heappush(pq,(-c,'c')) ans = '' while pq: c, ch = heapq.heappop(pq) if len(ans)>1 and ans[-1] == ans[-2] =...
/* The idea behid this problem 1. Here we start by taking the size as the sum of a, b, c. 2. Then we use 3 variables A, B, C to count the occurance of a, b, c. 3. Now we iterate until the size, and -> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and th...
class Solution { public: #define f first #define s second string longestDiverseString(int a, int b, int c) { priority_queue<pair<int,char>> pq; if(a>0)pq.push({a,'a'}); if(b>0)pq.push({b,'b'}); if(c>0)pq.push({c,'c'}); string ans = ""; while(!pq.empty()){ auto t = pq.top(); pq.po...
var longestDiverseString = function(a, b, c) { let str = '', aCount = 0, bCount = 0, cCount = 0; let len = a + b + c; for(let i = 0; i < len; i++) { if (a >= b && a >= c && aCount != 2 || bCount == 2 && a > 0 || cCount == 2 && a > 0) { adjustCounts('a', aCount+1, 0, 0); a--; ...
Longest Happy String
You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance. You are also given an intege...
class Solution: def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: return max( ( (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius), [x, y]) for x in range(51) for y in range(51) ...
class Solution { public int[] bestCoordinate(int[][] towers, int radius) { int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0; int[] res = new int[2]; for(int[] t : towers) { minX = Math.min(minX, t[0]); maxX = Math.max(maxX, t[0]); minY = Math.min(minY...
class Solution { public: vector<int> bestCoordinate(vector<vector<int>>& towers, int radius) { int n = towers.size(); int sum; int ans = 0; pair<int,int> ansCoor; // Calculate for every 'x's and 'y's for(int x = 0; x <= 50; x++){ for(int y = 0; y <= 50; y++){ ...
var bestCoordinate = function(towers, radius) { const n = towers.length; const grid = []; for (let i = 0; i <= 50; i++) { grid[i] = new Array(51).fill(0); } for (let i = 0; i < n; i++) { const [x1, y1, quality1] = towers[i]; for (let x2 = 0; x2 <= 50; ...
Coordinate With Maximum Network Quality
Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test...
class Solution: def numSteps(self, s: str) -> int: size = len(s) if size == 1: return 0 one_group = s.split('0') zero_group = s.split('1') if size - len(zero_group[-1]) == 1: return size - 1 else: return size + len(one_gro...
class Solution { public int numSteps(String s) { int countSteps = 0; int carry = 0; for(int i = s.length()-1;i>=1;i--) { int rightMostBit = s.charAt(i)-'0'; if((rightMostBit+carry) == 1) { carry=1; countSteps +=...
class Solution { public: int numSteps(string s) { int n=0; bool carry = false; int steps = 0; if(s == "1") return 0; while(s.length() > 0){ int i = s.length()-1; if(carry){ if(s[i] == '1'){ carry = true; s[i] = '0'; ...
var numSteps = function(s) { let res = 0; s = s.split(""); while(s.length>1){ if(s[s.length-1]==="0") s.pop(); else plusone(s); res++; } return res; }; var plusone = function(p) { p.unshift("0"); let i = p.length-1; p[i] = 1+(+p[i]); while(p[i]===2){ p...
Number of Steps to Reduce a Number in Binary Representation to One
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you ...
class Solution: def maxPoints(self, points: List[List[int]]) -> int: m, n = len(points), len(points[0]) for i in range(m - 1): for j in range(1, n): points[i][j] = max(points[i][j], points[i][j - 1] - 1) for j in range(n - 2, -1, -1): ...
/* -> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get added to next values from next row. -> conditions to update values in frame * we will keep only those values which will contribute maximum in next row addition e.g--> po...
class Solution { public: long long maxPoints(vector<vector<int>>& points) { vector<vector<long long>> dp(points.size(), vector<long long>(points[0].size(), -1)); for (int i = 0; i < points[0].size(); ++i) { dp[0][i] = points[0][i]; } for (int i = 1; i < ...
var maxPoints = function(points) { let prev = points[0]; let curr = Array(points[0].length); for(let i = 1; i<points.length; i++){ // from left to right; for(let j = 0, maxAdd=0; j<points[0].length;j++){ maxAdd = Math.max(maxAdd-1, prev[j]); curr[j] = points[i][j] +...
Maximum Number of Points with Cost
An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x &lt;= y. Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits. &nbsp; Example 1: Input: n = 10 Output: 9 Example 2: Input: n = 1234 Output: 1234 Exampl...
class Solution: def monotoneIncreasingDigits(self, n: int) -> int: num = list(str(n)) for i in range(len(num)-1): # Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return # However, there is the case that num[i-1]==num[i], which ...
class Solution { public int monotoneIncreasingDigits(int n) { int position; int digitInTheNextPosition; while ((position = getThePositionNotSatisfied(n)) != -1) { digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10; n -= Math.pow(10, position - 1) *...
class Solution { public: int monotoneIncreasingDigits(int n) { if(n < 10) return n; string s = to_string(n); for(int i = s.size() - 2; i >= 0; i--) { if(s[i] > s[i+1]) { s[i]--; for(int j = i + 1; j < s.size(); j+...
var monotoneIncreasingDigits = function(n) { let arr = String(n).split(''); for (let i=arr.length-2; i>=0; i--) { if (arr[i]>arr[i+1]) { arr[i]--; for(let j=i+1; j<arr.length; j++) arr[j]='9'; } } return Number(arr.join('')); };
Monotone Increasing Digits
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a bi...
class Codec: def serialize(self, root): if not root: return 'N' left = self.serialize(root.left) right = self.serialize(root.right) return ','.join([str(root.val), left, right]) def deserialize(self, data): data = data.split(',') root = self.buildTree(data) ...
public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { String data=""; Queue<TreeNode> q=new LinkedList<>(); if(root!=null) q.add(root); else return ""; data=Integer.toString(root.val)+"e"; while(!q.is...
TreeNode* ans; class Codec { public: string serialize(TreeNode* root) { ans = root; return ""; } TreeNode* deserialize(string data) { return ans; } };
var serialize = function (root) { if (!root) return ""; let res = []; function getNode(node) { if (!node) { res.push("null"); } else { res.push(node.val); getNode(node.left); getNode(node.right); } } getNode(root); return res.join(","); }; /** * Decodes your encoded ...
Serialize and Deserialize Binary Tree
An original string, consisting of lowercase English letters, can be encoded by the following steps: Arbitrarily split it into a sequence of some number of non-empty substrings. Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string). Concatenate the ...
from functools import lru_cache class Solution: def possiblyEquals(self, s1: str, s2: str) -> bool: def getValidPrefixLength(s,start): end = start while end < len(s) and s[end].isdigit(): end += 1 return end @lru_cache(None) def possibleLengths(s): ...
/** Cases: diff > 0 meaning we need to pick more chars in s1 diff < 0 meaning we need to pick more chars in s2 -1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999 1. s1[i] == s2[j] and diff = 0 increment i+1 and j+1 2. if s1[i] is not digit and diff > 0 then increme...
class Solution { public: bool memo[50][50][2000]; bool comp_seqs(string& s1, string& s2, int i1, int i2, int diff){ // check true condition if(i1 == s1.size() && i2 == s2.size()) return diff == 0; // add 1000 to 'diff' be in range [0, 2000) bool& ret = memo[i1][i2][di...
var possiblyEquals = function(s1, s2) { // Memo array, note that we do not need to memoize true results as these bubble up const dp = Array.from({length: s1.length+1}, () => Array.from({length: s2.length+1}, () => ([]))); const backtrack = (p1,...
Check if an Original String Exists Given Two Encoded Strings
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 &lt;= i &lt; n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. &nbsp; Example 1: Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Exp...
class Solution(object): def getConcatenation(self, nums): return nums * 2
class Solution { public int[] getConcatenation(int[] nums) { int[] ans = new int[2 * nums.length]; for(int i = 0; i < nums.length; i++){ ans[i] = ans[i + nums.length] = nums[i]; } return ans; } }
class Solution { public: vector<int> getConcatenation(vector<int>& nums) { int n=nums.size(); for(int i=0;i<n;i++) { nums.push_back(nums[i]); } return nums; } };
var getConcatenation = function(nums) { //spread the nums array twice and return it return [...nums,...nums] };
Concatenation of Array
You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and...
class Solution(object): def maximumDetonation(self, bombs): def count(i): dq, ret = [i], [i] while len(dq) > 0: i = dq.pop() for j in adj[i]: if j not in ret and j not in dq: dq.append(j) ...
class Solution { /* Make directed graph u -> v means, v is in the range of u check from which node maximum nodes can be reached and return the number of nodes reached */ public int maximumDetonation(int[][] bombs) { Map<Integer, List<Integer>> graph = new HashMap<>(); int n = bo...
class Solution { public: double eucDis(int x1,int y1,int x2,int y2) { double temp=pow(x1-x2,2)+pow(y1-y2,2); return sqrt(temp); } void dfs(int node,vector<int>&vis,vector<int>graph[],int &c) { c++; vis[node]=1; for(auto i:graph[node]) { if(...
/** * @param {number[][]} bombs * @return {number} */ var maximumDetonation = function(bombs) { if(bombs.length <= 1) return bombs.length; let adj = {}, maxSize = 0; const checkIfInsideRange = (x, y, center_x, center_y, radius) =>{ return ( (x-center_x)**2 + (y-center_y)**2 <= radius**2 ) ...
Detonate the Maximum Bombs
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or va...
class Solution: def countHillValley(self, nums: List[int]) -> int: c = 0 i = 1 while i <len(nums)-1: j = i+1 while j < len(nums)-1 and nums[j] == nums[i]: j += 1 if (nums[i-1] > nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and num...
class Solution { public int countHillValley(int[] nums) { int result = 0; // Get head start. Find first index for which nums[index] != nums[index-1] int start = 1; while(start < nums.length && nums[start] == nums[start-1]) start++; int prev = start-1; //index of prev different value num f...
class Solution { public: int countHillValley(vector<int>& nums) { // taking a new vector vector<int>v; v.push_back(nums[0]); //pushing unique elements into new vector for(int i=1;i<nums.size();i++){ if(nums[i]!=nums[i-1]){ v.push_back(nums[i]); } ...
var countHillValley = function(nums) { let previous; let count = 0; for (let i=0; i<nums.length; i++) { if (previous === undefined) { previous = i; continue; } if (nums[i-1] === nums[i]) { continue; } let nextCheck = i + 1; ...
Count Hills and Valleys in an Array
You are given a string s. Reorder the string using the following algorithm: Pick the smallest character from s and append it to the result. Pick the smallest character from s which is greater than the last appended character to the result and append it. Repeat step 2 until you cannot pick more characters. Pick th...
from collections import Counter class Solution: def sortString(self, s: str) -> str: counter = Counter(s) alphabets = "abcdefghijklmnopqrstuvwxyz" rev_alphabets = alphabets[::-1] total = len(s) res = [] while total > 0: for c in alphabets: ...
class Solution { public String sortString(String s) { StringBuilder result = new StringBuilder(); int[] freq = new int[26]; for(char c: s.toCharArray()){ freq[c-'a']++; } int remaining = s.length(); while(remaining!=0){ for(int i=0;i<...
class Solution { public: string sortString(string s) { int count [26]={0}; for(int i =0 ;i< s.size();i++){ char ch = s[i]; count[ch-'a']++; } string res ; while(res.size()!=s.size()){ for(int i = 0 ;i<26;i++){ if(count[i] >0)...
/** * @param {string} s * @return {string} */ var sortString = function(s) { const counts = [...s].reduce((acc, cur) => (acc[cur.charCodeAt() - 97] += 1, acc), new Array(26).fill(0)); const result = []; const pick = (code) => { if (counts[code]) { result.push(String.fromCharCode(code + 97)); c...
Increasing Decreasing String
Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r (l &lt; r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] a...
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: count=0 for i in range(len(nums)): a=nums[i] c=1 for j in range(i+1, len(nums)): if nums[j]>a: a=nums[j] c+=1 else: ...
class Solution { public int findLengthOfLCIS(int[] nums) { int count = 1; int maxCount = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { count++; } else { maxCount = Math.max(count, maxCount); cou...
class Solution { public: int findLengthOfLCIS(vector<int>& nums) { int maxLength = 1; int currLength = 1; int i = 0; int j = 1; while(j<nums.size()){ if(nums[j] > nums[i]){ currLength++; i++; j++; ...
var findLengthOfLCIS = function(nums) { let res = 0; let curr = 1; nums.forEach((num, idx) => { if (num < nums[idx + 1]) { curr++; } else curr = 1; res = Math.max(res, curr); }) return res; };
Longest Continuous Increasing Subsequence
A ramp in an integer array nums is a pair (i, j) for which i &lt; j and nums[i] &lt;= nums[j]. The width of such a ramp is j - i. Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0. &nbsp; Example 1: Input: nums = [6,0,8,2,1,5] Output: 4 Explanation: The ma...
class Solution: def maxWidthRamp(self, nums: List[int]): st=[] n=len(nums) for i in range(n): if len(st)==0 or nums[st[-1]]>=nums[i]: st.append(i) print(st) max_idx=-1 for j in range(n-1,-1,-1): while len(st) and nums[st[-1]]<=n...
class Solution { public int maxWidthRamp(int[] nums) { Stack<Integer> s = new Stack<>(); int res = 0; for(int i = 0; i< nums.length; i++){ if(!s.isEmpty() && nums[s.peek()]<=nums[i]) { res = Math.max(res, i-s.peek()); continue; } ...
class Solution { public: int maxWidthRamp(vector<int>& nums) { int n=nums.size(); if(n==2){ if(nums[0]<=nums[1])return 1; return 0; } stack<int>st; for(int i=0;i<n;i++){ if(st.empty()||nums[i]<nums[st.top()]){st.push(i);} // maintaining a ...
var maxWidthRamp = function(nums) { let stack = [], ans = 0; for (let i = 0; i < nums.length; i++) { let index = lower_bound(stack, i); ans = Math.max(ans, i - index); if (!stack.length || nums[i] < nums[stack[stack.length - 1]]) stack.push(i); } return ans; function lower_bound(arr, index) { ...
Maximum Width Ramp
Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was pr...
class RandomizedSet: def __init__(self): self.data = set() def insert(self, val: int) -> bool: if val not in self.data: self.data.add(val) return True return False def remove(self, val: int) -> bool: if val in self.data: self.data.remove(va...
class RandomizedSet { HashMap<Integer, Integer> map; ArrayList<Integer> list; Random rand; public RandomizedSet() { map = new HashMap<>(); list = new ArrayList<>(); rand = new Random(); } public boolean insert(int val) { if (!map.containsKey(val)){ ...
class RandomizedSet { public: unordered_map<int, int> mp; vector<int> v; RandomizedSet() { } bool insert(int val) { if(mp.find(val) != mp.end()) return false; mp[val] = v.size(); v.push_back(val); return true; } bool remove(int val) { ...
var RandomizedSet = function() { this._data = []; this._flatData = []; }; RandomizedSet.prototype.hash = function(val) { return val % 1e5; } RandomizedSet.prototype.insert = function(val) { const hash = this.hash(val); let basket = this._data[hash]; for (let i = 0; i < basket?.length; i++...
Insert Delete GetRandom O(1)
Given two integers a and b, return the sum of the two integers without using the operators + and -. &nbsp; Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5 &nbsp; Constraints: -1000 &lt;= a, b &lt;= 1000
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ sol=(a,b) return sum(sol) ```
class Solution { public int getSum(int a, int b) { return Integer.sum(a, b); } }
class Solution { public: int getSum(int a, int b) { vector<int> arr = {a,b}; return accumulate(arr.begin(),arr.end(),0); } };
/** * @param {number} a * @param {number} b * @return {number} */ var getSum = function(a, b) { if (a==0){ return b; } else if (b==0){ return a; } else{ return getSum((a^b),(a&b)<<1); } };
Sum of Two Integers
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a...
class Solution: def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: n = len(nums) p = [0] for el in nums: p.append(p[-1] + el) msum = 0 for f, s in [(firstLen, secondLen), (secondLen, firstLen)]: for i in range(f - 1, n...
class Solution { public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) { int []dp1=new int[nums.length]; int []dp2=new int[nums.length]; int sum=0; for(int i=0;i<nums.length;i++){ if(i<firstLen){ sum+=nums[i]; dp1[...
class Solution { public: int solve(vector<int>& prefixSum, int n, int firstLen, int secondLen){ vector<int> dp(n, 0); dp[n-secondLen] = prefixSum[n]-prefixSum[n-secondLen]; for(int i=n-secondLen-1; i>=0; i--){ dp[i] = max(dp[i+1], prefixSum[i+secondLen]-pre...
var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) { function helper(arr, x, y) { const n = arr.length; let sum = 0; const dp1 = []; // store left x sum const dp2 = []; // store right y sum for(let i = 0; i<n; i++) { if(i<x) { ...
Maximum Sum of Two Non-Overlapping Subarrays
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. Train tickets are sold in three different ways: a 1-day pass is sold for costs[0] dollars, a 7-day pass is sold for costs[1] dollars, an...
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: min_cost = float('inf') que = deque() # enqueue the possible state of day 1 que.append((days[0], costs[0])) que.append((days[0]+7-1, costs[1])) que.append((days[0]+30-1, costs[2])) ...
class Solution { public int mincostTickets(int[] days, int[] costs) { HashSet<Integer> set = new HashSet<>(); for(int day: days) set.add(day); int n = days[days.length - 1]; int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = ...
class Solution { public: int f(int i,int j,vector<int>& days,vector<int>& costs,vector<vector<int>>& dp) { if (i==days.size()) return 0; if (days[i]<j) return f(i+1,j,days,costs,dp); if (dp[i][j]!=-1) return dp[i][j]; int x=costs[0]+f(i+1,days[i]+1,days,costs,dp); int y=costs...
var mincostTickets = function(days, costs) { let store = {}; for(let i of days) { store[i] = true } let lastDay = days[days.length - 1] let dp = new Array(days[days.length - 1] + 1).fill(Infinity); dp[0] = 0; for(let i = 1; i< days[days.length - 1] + 1; i++) { if(!store[i]) { dp[i] ...
Minimum Cost For Tickets
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i: If nums[i] is positive, move nums[i] steps forward, and If nums[i] is negative, move nums[i] steps backward. Since the array is circ...
class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) for i in range(n): seen = set() minval = float('inf') maxval = float('-inf') j = i while j not in seen: seen.add(j) minval =...
class Solution { public boolean circularArrayLoop(int[] nums) { for (int i=0; i<nums.length; i++) { boolean isForward = nums[i] > 0; int slow = i; int fast = i; do { slow = findNextIndex(nums, isForward, slow); fast = findNextI...
class Solution { public: bool circularArrayLoop(vector<int>& nums) { unordered_set<int>us; for(int i{0};i<nums.size() && us.find(i)==us.end();i++){ unordered_map<int,int>um; int index=0; int j=i; um[i]; bool flag1=0,flag2=0; whi...
var circularArrayLoop = function(nums) { // cannot be a cycle if there are less than 2 elements const numsLen = nums.length; if (numsLen < 2) return false; // init visited array const visited = Array(numsLen).fill(false); // check each index to see if a cycle can be produced for (let i = 0...
Circular Array Loop
The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'. For example, "ACGAATTCCG" is a DNA sequence. When studying DNA, it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (subst...
class Solution(object): def findRepeatedDnaSequences(self, s): """ :type s: str :rtype: List[str] """ seqs = {} i = 0 while i+10 <= len(s): curr = s[i:i+10] if curr in seqs: seqs[curr] = seqs[curr] + 1 else: ...
class Solution { public List<String> findRepeatedDnaSequences(String s) { HashMap<String,Integer> map =new HashMap(); int i=0; int j=0; int k=10; StringBuilder sb=new StringBuilder(""); while(j<s.length()){ sb.append(s.charAt(j)); if(j-i+1<k){...
class Solution { public: vector<string> findRepeatedDnaSequences(string s) { unordered_map<string,int> freq; int start = 0 , end = 9; while(end < s.size()){ bool flag = true; for(int i = start ; i <= end ; i++){ if(s[i] == 'A' or s[i] == 'C' or s[i] == 'G' or s[i] == 'T') continue; else {f...
// 187. Repeated DNA Sequences var findRepeatedDnaSequences = function(s) { let map = {}; let res = []; for (let i = 0; i <= s.length-10; i++) { let s10 = s.substring(i, i+10); map[s10] = (map[s10] || 0) + 1; if (map[s10] === 2) res.push(s10); } return res; };
Repeated DNA Sequences
You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid "croak" means a frog i...
class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: c = r = o = a = k = max_frog_croak = present_frog_croak = 0 # need to know, at particular point, # what are the max frog are croaking, for i, v in enumerate(croakOfFrogs): if v == 'c': ...
class Solution { public int minNumberOfFrogs(String croakOfFrogs) { int[] index = new int[26]; String corak = "croak"; // Giving index to each characters for (int i = 0; i < corak.length(); ++i) index[corak.charAt(i) - 'a'] = i; int ans = 0, sum = 0; int...
class Solution { public: int minNumberOfFrogs(string croakOfFrogs) { unordered_map<char,int> mp; int size=croakOfFrogs.size(); for(int i=0;i<size;i++) { mp[croakOfFrogs[i]]++; if(mp['c']<mp['r'] || mp['r']<mp['o'] || mp['o']<mp['a'] || mp['a']<mp['k']...
var minNumberOfFrogs = function(croakOfFrogs) { const croakArr = new Array(5).fill(0); //Array to store occurence of each char let overlap = 0; //Store the number of overlaps for(let i = 0; i < croakOfFrogs.length; i++) { switch(croakOfFrogs[i]) { case 'c': croakArr[0] +...
Minimum Number of Frogs Croaking
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. &nbsp; Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 &nbsp; Constraints: 1 &lt;= n &lt;= 19
class Solution(object): def numTrees(self, n): if n == 0 or n == 1: return 1 # Create 'sol' array of length n+1... sol = [0] * (n+1) # The value of the first index will be 1. sol[0] = 1 # Run a loop from 1 to n+1... for i in range(1, n+1): ...
class Solution { public int numTrees(int n) { // Create 'sol' array of length n+1... int[] sol = new int[n+1]; // The value of the first index will be 1. sol[0] = 1; // Run a loop from 1 to n+1... for(int i = 1; i <= n; i++) { // Within the above loop, run...
class Solution { public: int catalan (int n,vector<int> &dp) { if(n<=1) return 1; int ans =0; for(int i=0;i<n;i++) { ans+=catalan(i,dp)*catalan(n-1-i,dp); } return ans; } int numTrees(int n) { ...
var numTrees = function(n) { // Create 'sol' array to store the solution... var sol = [1, 1]; // Run a loop from 2 to n... for (let i = 2; i <= n; i++) { sol[i] = 0; // Within the above loop, run a nested loop from 1 to i... for (let j = 1; j <= i; j++) { // Update th...
Unique Binary Search Trees
Given the array restaurants where &nbsp;restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true)&nbsp;or false&nbsp;(meaning you ...
class Solution: def f_fcn(self,restaurants, veganFriendly, maxPrice, maxDistance): f_lst = filter(lambda x: (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance), restaurants) return f_lst def h_fcn(self,lst): retu...
class Restaurant { int id, rating; Restaurant(int id, int rating) { this.id = id; this.rating = rating; } } class RestaurantComparator implements Comparator<Restaurant> { @Override public int compare(Restaurant r1, Restaurant r2) { return r1.rating == r2.rating ? r2.id - r1....
//comparator class for sorting restaurants by their rating class comp{ public: bool operator ()(vector<int>a,vector<int>b){ //same rating then sort by ids if(a[1]==b[1]) return a[0]>b[0]; return a[1]>b[1]; } }; class Solution { public: vector<int> filte...
var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { let result = [] // veganFriendly filter if(veganFriendly === 1){ restaurants = restaurants.filter(restaurant=> restaurant[2] === 1) } //max price restaurants = restaurants.filter(restaurant=>restau...
Filter Restaurants by Vegan-Friendly, Price and Distance
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: The ...
class Solution: def minPushBox(self, grid: List[List[str]]) -> int: m,n=len(grid),len(grid[0]) q=deque() start,target,box=(0,0),(0,0),(0,0) for i in range(m): for j in range(n): if grid[i][j]=="B": box=(i,j) elif grid[i]...
/** Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves) Uses BFS/A* Algorithm to visit valid transition states Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations */ class Solution { private int targetRow; private int targetCol; ...
class Solution { public: pair<int,int> t; //target pair<int,int> s; //source pair<int,int> b; //box // struct to store each member in priority queue struct node { int heuristic; // to find the dist between target and box int dist; // to keep track of how much the box moved ...
/** * @param {character[][]} grid * @return {number} */ var minPushBox = function(grid) { // common info & utils const m = grid.length const n = grid[0].length const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] const add = (a, b) => [a[0] + b[0], a[1] + b[1]] const equals = (a, b) => a[0] === b[...
Minimum Moves to Move a Box to Their Target Location
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed stri...
class Encrypter: def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): self.hashmap = dict() for i in range(len(keys)): self.hashmap[keys[i]] = values[i] self.dictmap = defaultdict(int) for word in dictionary: self.dictmap[self.encryp...
class Encrypter { Map<String, Integer> encryptedDictCount; int[] keys; Set<String> dictionary; String[] val; public Encrypter(char[] keys, String[] values, String[] dictionary) { this.keys = new int[26]; encryptedDictCount = new HashMap<>(); this.val = values.clone(...
class Encrypter { public: unordered_set<string> dict; unordered_map<char,string> en; unordered_map<string,vector<char>> dy; Encrypter(vector<char>& keys, vector<string>& values, vector<string>& dictionary) { for(auto& t:dictionary) { dict.insert(t);} for(int i=0;i<keys.siz...
var Encrypter = function(keys, values, dictionary) { this.encryptMap = new Map(); for (let i = 0; i < keys.length; i++) { this.encryptMap.set(keys[i], values[i]); } this.dict = new Set(dictionary); // Encypt the values in dict for easy comparison later this.encryptedVals = []; for (l...
Encrypt and Decrypt Strings
A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of th...
class Solution: def shipWithinDays(self, weights: List[int], days: int) -> int: def calc(m):#function calculate no of days for given weight c,s=0,0 for i in weights: if i+s>m: c+=1 s=0 s+=i if s>0: ...
class Solution { public int shipWithinDays(int[] weights, int days) { int left = 0; int right = 0; // left is the biggest element in the array. It's set as the lower boundary. // right is the sum of the array, which is the upper limit. for (int weight : weights) { ...
class Solution { public: // function to check if it is possible to ship all the items within the given number of days using a given weight capacity bool isPossible(int cp, vector<int>& weights, int days) { int d = 1; int cw = 0; // iterate through the weights and check if it is possi...
/** * @param {number[]} weights * @param {number} days * @return {number} */ var shipWithinDays = function(weights, days) { // set left as max of weight, set right as sum of weight let left = Math.max(...weights), right = weights.reduce((a, b) => a + b); // max weight cannot exceed the capacity of ship...
Capacity To Ship Packages Within D Days
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the val...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: # Intialize the result and the current node to the head res = node = head ...
class Solution { public ListNode reverseKGroup(ListNode head, int k) { int numOfNodes = count(head); ListNode ptr = null; List<ListNode> start = new ArrayList<>(), end = new ArrayList<>(); ListNode f = null; while (head != null) { if (numOfNodes >= k) { ...
class Solution { pair<ListNode* , ListNode*> get_rev_list(ListNode* root){ ListNode *tail = root; ListNode *curr = root , *temp , *prev = NULL; while(curr != NULL){ temp = curr -> next; curr -> next = prev; prev = curr; cu...
var reverseKGroup = function(head, k) { const helper = (node) => { let ptr = node; let t = k; let prev = null; while(t && ptr) { prev = ptr; ptr = ptr.next; t -= 1; } if(t > 0) //if k is not zero then do n...
Reverse Nodes in k-Group
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. &nbsp; Example 1: Input: grid = [[1,0],[0,1]] Output: 3 Explanation: Change one 0 to 1 and co...
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # parent array to keey track parent = list(range(m*n)) # rank array used for union by rank and size calculation rank = [1 for _ in range(m*n)] # standard DSU...
class Solution { int dir[][] = new int[][]{ {1, 0}, {-1,0}, {0,1}, {0,-1} }; private int countArea(int grid[][], int i, int j, int num){ if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return 0; if(grid[i][j] != 1) return 0; ...
class Solution { int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; bool isValid(vector<vector<int>>const &grid,vector<vector<int>> &visited, int row, int col){ int n=grid.size(); if(row<0 || row>=n || col<0 || col>=n || grid[row][col]!=1 || visited[row][col]!=0){ return false;...
var largestIsland = function(grid) { const n = grid.length /** * Create the merge find (union find) structure --> https://www.youtube.com/watch?v=ibjEGG7ylHk * For this case, we will form the sets at once, already assigning the same representative to all members. * Thus, we can use this simplistic impleme...
Making A Large Island
Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number withou...
class Solution: def isSolvable(self, words: List[str], result: str) -> bool: # reverse words words = [i[::-1] for i in words] result = result[::-1] allWords = words + [result] # chars that can not be 0 nonZero = set() for word in allWords: ...
class Solution { public static boolean isSolvable(String[] words, String result) { // reverse all strings to facilitate add calculation. for (int i = 0; i < words.length; i++) { words[i] = new StringBuilder(words[i]).reverse().toString(); } result = new StringBuilder(result...
class Solution { int limit = 0; unordered_map<char, int> c2i; unordered_map<int, char> i2c; bool helper(vector<string> &words, string &result, int digit, int wid, int sum) { if(digit==limit) return sum == 0; if(wid==words.size()) { if(c2i.count(result[...
/** * @param {string[]} words * @param {string} result * @return {boolean} */ var isSolvable = function(words, result) { // set to hold all the first characters const firstChars = new Set(); // map for steps 1 & 2 // this will hold the key as the character and multiple as the value let map = {}; for ...
Verbal Arithmetic Puzzle