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 string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. Return a list of integers representing the size of these parts...
class Solution: def partitionLabels(self, s: str) -> List[int]: d = defaultdict(list) for i, char in enumerate(s): d[char].append(i) nums = [] for v in d.values(): nums.append([v[0], v[-1]]) start = nums[0][0] maxIndex = nums[0][1] ...
class Solution { public List<Integer> partitionLabels(String s) { List<Integer>lr=new ArrayList<>(); HashMap<Character,Boolean>mp=new HashMap<>(); int count=0; for(int i=0;i<s.length();i++){ if(!mp.containsKey(s.charAt(i))&&s.lastIndexOf(Character.toString(s.charAt(i)))!=i){ ...
class Solution { public: vector<int> partitionLabels(string s) { unordered_map<char,int>mp; // filling impact of character's for(int i = 0; i < s.size(); i++){ char ch = s[i]; mp[ch] = i; } // making of result vector<int> res; int prev ...
var partitionLabels = function(s) { let last = 0, first = 0; let arr = [...new Set(s)], ss = []; let temp = ''; first = s.indexOf(arr[0]); last = s.lastIndexOf(arr[0]); for(let i = 1; i<arr.length; i++){ if(s.indexOf(arr[i]) < last){ if(last < s.lastIndexOf(arr[i])){ ...
Partition Labels
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. &nbsp; Example 1: Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 Output: 2 Explanation: The maximum side lengt...
class Solution: def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: # prefix matrix dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)] for i in range(1, len(mat)+1): for j in range(1, len(mat[0])+1): dp[i][j] = dp[i][j-1] + dp[i-1][j]...
class Solution { public int maxSideLength(int[][] mat, int threshold) { int rows = mat.length; int cols = mat[0].length; int[][] preSum = new int[rows+1][cols+1]; for(int i=1;i<=rows;i++){ for(int j=1;j<=cols;j++){ preSum[i][j] = preSum[i-1][j] + preSum[i]...
class Solution { public: int maxSideLength(vector<vector<int>>& mat, int threshold) { int m = mat.size(); int n = mat[0].size(); int least = min (m,n); vector<vector<int>> dp (m+1, vector<int> (n+1, 0)); /* create dp matrix with sum of all s...
/** * @param {number[][]} mat * @param {number} threshold * @return {number} */ var maxSideLength = function(mat, threshold) { const n = mat.length, m = mat[0].length; // build sum matrix let sum = []; for(let i=0; i<=n; i++) { sum.push(new Array(m+1).fill(0)); for(let j=0; j<=m...
Maximum Side Length of a Square with Sum Less than or Equal to Threshold
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a st...
class Solution: def findLUSlength(self, s: List[str]) -> int: def lcs(X, Y): m = len(X) n = len(Y) L = [[None]*(n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0 : ...
class Solution { public int findLUSlength(String[] strs) { Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length // store the frequency of all strings in array Map<String,Integer> map = new HashMap<>(); for(String s : strs) map.put(s,map.getOrDefault...
class Solution { private: bool isCommon(string &s,string &t){ int index=0; for(int i=0;i<s.size();i++){ if(s[i]==t[index]){ if(++index==t.size()){ return true; } } } return false; } bool isUncommon(ve...
var findLUSlength = function(strs) { strs.sort((a, b) => b.length - a.length); const isSubsequence = (a, b) => { const A_LENGTH = a.length; const B_LENGTH = b.length; if (A_LENGTH > B_LENGTH) return false; if (a === b) return true; const matches = [...b].reduce((pos, str) => { return a[pos] === str ? pos...
Longest Uncommon Subsequence II
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. &nbsp; Example 1: Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers. Example 2: Input: n = 1 Output: 1 Explanation:...
import heapq class Solution: def nthUglyNumber(self, n: int) -> int: h1, h2, h3 = [], [], [] heapq.heappush(h1, 1) heapq.heappush(h2, 1) heapq.heappush(h3, 1) ugly_number = 1 last_ugly_number = 1 count = 1 while count < n: if 2 * h1[0] <= 3...
// Ugly number II // https://leetcode.com/problems/ugly-number-ii/ class Solution { public int nthUglyNumber(int n) { int[] dp = new int[n]; dp[0] = 1; int i2 = 0, i3 = 0, i5 = 0; for (int i = 1; i < n; i++) { dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5)...
class Solution { public: int nthUglyNumber(int n) { int dp[n+1]; dp[1] = 1; int p2 = 1, p3 = 1, p5 = 1; int t; for(int i = 2; i < n+1; i++){ t = min(dp[p2]*2, min(dp[p3]*3, dp[p5]*5)); dp[i] = t; if(dp[i] == dp[p2]*2){ p...
var nthUglyNumber = function(n) { let uglyNo = 1; let uglySet = new Set(); // Set to keep track of all the ugly Numbers to stop repetition uglySet.add(uglyNo); let minHeap = new MinPriorityQueue(); // Javascript provides inbuilt min and max heaps, constructor does not require callback function for primitive types but a...
Ugly Number II
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 &lt;= k &lt; nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed)....
class Solution: def search(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l<=r: mid = (l+r)//2 if target == nums[mid]: return mid if nums[l]<=nums[mid]: if target > nums[mid] or targe...
class Solution { public int search(int[] nums, int target) { int pivot = findPivot(nums); int ans = binarySearch(nums, target, 0, pivot); if(ans!=-1){ return ans; } return binarySearch(nums, target, pivot+1, nums.length-1); } public int findPivot(int[...
class Solution { public: int search(vector<int>& nums, int target) { int n=nums.size()-1; if(nums[0]==target) return 0; if(nums.size()==1) return -1; // find the index of the minimum element ie pivot int pivot=-1; int low=0; int h...
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { const len = nums.length; if (len === 1 && nums[0] === target) return 0; const h = nums.findIndex((val, i) => nums[i === 0 ? nums.length - 1 : i - 1] > val); if (h !== 0) nums = nums.slic...
Search in Rotated Sorted Array
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this...
class Solution: def assign_sign(self, sign): # verify that we haven't already got a sign #&nbsp;"+42-" -> we don't want to return -42; hence check if not self.is_neg and not self.is_pos: # no sign has been set yet if sign=="+": self.is_pos = True elif sign=="-"...
class Solution { public int myAtoi(String s) { long n=0; int i=0,a=0; s=s.trim(); if(s.length()==0) return 0; if(s.charAt(i)=='+' || s.charAt(i)=='-') a=1; while(a<s.length()) if(s.charAt(a)=='0') a++; el...
class Solution { public: int myAtoi(string s) { long long ans = 0; int neg = 1; int i = 0; while (i < s.length() and s[i] == ' ') { i++; } if (s[i] == '-' || s[i] == '+') { ...
const toNumber = (s) => { let res = 0; for (let i = 0; i < s.length; i++) { res = res * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0)); } return res } var myAtoi = function(s) { s = s.trim(); let r = s.match(/^(\d+|[+-]\d+)/); if (r) { let m = r[0], res; switch...
String to Integer (atoi)
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. &nbsp; Example 1: Input: nums = [2,3,1,1,4] Output: true Explanation: Jump...
class Solution: def canJump(self, nums: List[int]) -> bool: """ # Memoization + DFS Solution # TLE as we have as much as n decisions depending on nums[i] which could be # 10^5 as an uppercase according to problem constraints # better off with a greedy approach cache ...
class Solution { public boolean canJump(int[] nums) { int maxjump = 0; for(int i=0;i<nums.length;i++) { // If the current index 'i' is less than current maximum jump 'curr'. It means there is no way to jump to current index... // so we should return false ...
class Solution { public: bool canJump(vector<int>& nums) { int ans = nums[0]; if(nums.size()>1&&ans==0) return false; for(int i=1; i<nums.size(); i++){ ans = max(ans-1,nums[i]); if(ans<=0&&i!=nums.size()-1) return false; } return true; } };
var canJump = function(nums) { let target = nums.length-1; let max = 0,index = 0; while(index <= target){ max = Math.max(max,index + nums[index]); if(max >= target) return true; if(index >= max && nums[index] === 0) return false; index++; } return false; };
Jump Game
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates&nbsp;where the candidate numbers sum to target. Each number in candidates&nbsp;may only be used once in the combination. Note:&nbsp;The solution set must not contain duplicate combinations. &...
class Solution(object): def combinationSum2(self, candidates, target): res = [] def dfs(nums,summ,curr): if summ>=target: if summ == target: res.append(curr) return for i in range(len(nums)): if i !=0 and num...
class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); // O(nlogn) Arrays.sort(candidates); boolean[] visited = new boolean[candidates.length]; he...
class Solution { public: vector<vector<int>> ans;vector<int> temp; void f(vector<int>& nums,int target,int i){ if(target==0){ ans.push_back(temp); return; } if(i>=nums.size()) return; if(nums[i]<=target){ temp.push_back(nums[i]); ...
/** * @param {number[]} candidates * @param {number} target * @return {number[][]} */ var combinationSum2 = function(candidates, target) { candidates.sort((a, b) => a - b); const ans = []; function dfs(idx, t, st) { if (t === 0) { ans.push(Array.from(st)); retur...
Combination Sum II
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i &lt; j, the condition j - i &lt;= k is satisfied. A subsequence of an array is obtained by deleting some number of ...
class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int: deque = [] for i, num in enumerate(nums): while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i] deque.pop(0) if de...
class Solution { public int constrainedSubsetSum(int[] nums, int k) { int n=nums.length; int[] dp=new int[n]; int res=nums[0]; Queue<Integer> queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap Arrays.fill(dp,Integer.MIN_VALUE); dp[0]=nums[0]; ...
class Solution { public: int constrainedSubsetSum(vector<int>& nums, int k) { priority_queue<array<int, 2>> que; int ret = nums[0], curr; que.push({nums[0], 0}); for (int i = 1; i < nums.size(); i++) { while (!que.empty() && que.top()[1] < i - k) { que.pop...
/** * @param {number[]} nums * @param {number} k * @return {number} */ var constrainedSubsetSum = function(nums, k) { const queue = [[0, nums[0]]]; let max = nums[0]; for (let i = 1; i < nums.length; i++) { const cur = queue.length ? nums[i] + Math.max(0, queue[0][1]) : nums[i]; max = Ma...
Constrained Subsequence Sum
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that&nbsp;abs(x)&nbsp;is the absolute value of x. Return abs(i - start). It is guaranteed that target exists in nums. &nbsp; Example 1: Input: nums = [1,2,3,4,...
class Solution: def getMinDistance(self, nums: List[int], target: int, start: int) -> int: if nums[start] == target: return 0 left, right = start-1, start+1 N = len(nums) while True: if left >=0 and nums[left] == target: return start - left if ...
class Solution { public int getMinDistance(int[] nums, int target, int start) { int ans = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { ans = Math.min(ans, Math.abs(i - start)); } } return ans; } }
class Solution{ public: int getMinDistance(vector<int>& nums, int target, int start){ int ans = INT_MAX; for(int i = 0; i < nums.size(); i++){ int temp = 0; if (nums[i] == target){ temp = abs(i - start); if (temp < ans){ ans...
var getMinDistance = function(nums, target, start) { let min = Infinity; for(let i=nums.indexOf(target);i<nums.length;i++){ if(nums[i]===target){ if(Math.abs(i-start)<min) min = Math.abs(i-start); } } return min; };
Minimum Distance to the Target Element
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. &nbsp; Example 1: Input: points = [[0,0],[1,0...
class Solution: def numberOfBoomerangs(self, points: List[List[int]]) -> int: def sq(a): return a * a def euclid(a, b, c, d): dist = sq(a - c) + sq(b - d) return sq(dist) n = len(points) res = 0 for i in range(n): count = defa...
class Solution { public int numberOfBoomerangs(int[][] points) { int answer = 0; for (int p=0; p<points.length;p++) { int[] i = points[p]; HashMap<Double, Integer> hm = new HashMap<Double, Integer>(); for (i...
class Solution { public: int numberOfBoomerangs(vector<vector<int>>& points) { int cnt = 0, n = points.size(); for(int i = 0; i < n; i++) { map<int, int> mp; for(int j = 0; j < n; j++) { if(i == j) continue; ...
var numberOfBoomerangs = function(points) { const POINTS_LEN = points.length; let result = 0; for (let i = 0; i < POINTS_LEN; i++) { const hash = new Map(); for (let j = 0; j < POINTS_LEN; j++) { if (i === j) continue; const [x1, y1] = points[i]; const [x2, y2] = points[j]; const dis = Math.pow(x1 ...
Number of Boomerangs
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances betw...
from typing import List ROOT_PARENT = -1 class Solution: def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]: """ @see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N) :param n: :param ...
class Solution { private Map<Integer, List<Integer>> getGraph(int[][] edges) { Map<Integer, List<Integer>> graph = new HashMap<>(); for(int[] edge: edges) { graph.putIfAbsent(edge[0], new LinkedList<>()); graph.putIfAbsent(edge[1], new LinkedList<>()); ...
/* Finding sum of distance from ith node to all other nodes takes O(n), so it will take O(n^2) if done naively to find distance for all. x---------------------y / \ \ o o o / / \ o ...
var sumOfDistancesInTree = function(n, edges) { let graph = {}; for (let [start, end] of edges) { if (!graph[start]) graph[start] = []; if (!graph[end]) graph[end] = []; graph[start].push(end); graph[end].push(start); } let visited = new Set(), distanceFromZero = 0, ...
Sum of Distances in Tree
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is: 0 if it is a batch of buy orders, or 1 if it is a batch of sell orders. Note that orders[i] represents a batch of am...
class Solution: def getNumberOfBacklogOrders(self, orders): b, s = [], [] heapq.heapify(b) heapq.heapify(s) for p,a,o in orders: if o == 0: heapq.heappush(b, [-p, a]) elif o == 1: heapq.heappush(s, [p, ...
class Solution { PriorityQueue<Order> buyBackLog; PriorityQueue<Order> sellBackLog; static int MOD = 1_000_000_007; public int getNumberOfBacklogOrders(int[][] orders) { //max heap, heapify on price buyBackLog = new PriorityQueue<Order>((a, b) -> (b.price - a...
class Solution { public: int getNumberOfBacklogOrders(vector<vector<int>>& orders) { int n = orders.size(); //0 - buy , 1 - sell; priority_queue<vector<int>> buyBacklog; priority_queue<vector<int> , vector<vector<int>> , greater<vector<int>>> sellBacklog; for(auto ...
var getNumberOfBacklogOrders = function(orders) { const buyHeap = new Heap((child, parent) => child.price > parent.price) const sellHeap = new Heap((child, parent) => child.price < parent.price) for (let [price, amount, orderType] of orders) { // sell if (orderType) { ...
Number of Orders in the Backlog
A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab",...
class Solution: def minDeletions(self, s: str) -> int: # Get the frequency of each character sorted in reverse order frequencies = sorted(Counter(s).values(), reverse=True) total_deletions = 0 next_unused_freq = len(s) for freq in frequencies: # It is imp...
class Solution { private int N = 26; public int minDeletions(String s) { int[] array = new int[N]; for (char ch : s.toCharArray()) { array[ch - 'a']++; } int ans = 0; Set<Integer> set = new HashSet<>(); for (int i : array) { if (i == 0) con...
class Solution { public: int minDeletions(string s) { //Array to store the count of each character. vector<int> freq (26, 0); //Calculatimg frequency of all characters. for (char c : s){ freq[c - 'a']++; } //sorting the frequencies. So th...
var minDeletions = function(s) { let freq = new Array(26).fill(0); // Create an array to store character frequencies for (let i = 0; i < s.length; i++) { freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; // Count the frequency of each character } freq.sort((a, b) => a - b); // Sort frequenc...
Minimum Deletions to Make Character Frequencies Unique
There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return a boolean array result of length n, where result[i] is true if, after giving the ith kid...
class Solution: def kidsWithCandies(self, candy, extra): #create an array(res) with all values as True and it's lenght is same as candies res = [True]*len(candy) #iterate over the elements in the array candy for i in range(len(candy)): #if the no. of canides at curr posit...
class Solution { public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) { List<Boolean>result = new ArrayList<>(candies.length); // better practice since the length is known int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1 ...
class Solution { public: vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) { vector<bool> ans; int i = 0, size, max = 0; size = candies.size(); for(i = 0; i<size; i++){ if(candies[i]>max) max = candies[i]; } for(i = 0; i<size;i++){ ...
var kidsWithCandies = function(candies, extraCandies) { //First find out maximum number in array:-> let max=0, res=[]; for(let i=0; i<candies.length; i++){ if(candies[i]>max) max=candies[i]; } console.log(max) /*Now add extraCandies with every element in array and checks if that s...
Kids With the Greatest Number of Candies
In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X &gt;= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Each group has exactly X cards. All the cards in each group have the same integer. &nbsp; Example 1: Input: dec...
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: f=defaultdict(int) for j in deck: f[j]+=1 import math u=list(f.values()) g=u[0] for j in range(1,len(u)): ...
// X of a Kind in a Deck of Cards // Leetcode problem : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/ class Solution { public boolean hasGroupsSizeX(int[] deck) { int[] count = new int[10000]; for(int i : deck) count[i]++; int gcd = 0; for(int i : count) ...
class Solution { public: int gcd(int a,int b) { while(a>0 && b>0) { if(a>b) a=a%b; else b=b%a; } return (a==0? b:a); } bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int,int> mp; vector<int> v; for(auto i:deck) ...
var hasGroupsSizeX = function(deck) { let unique = [...new Set(deck)], three = 0, two = 0, five = 0, size = 0, same = 0, s = 0; for(let i = 0; i<unique.length; i++){ for(let y=0; y<deck.length; y++){ if(unique[i] === deck[y]){ size++; } } if(size<...
X of a Kind in a Deck of Cards
Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where 0 &lt;= i &lt; j &lt; nums.length and nums[i] &gt; 2 * nums[j]. &nbsp; Example 1: Input: nums = [1,3,2,3,1] Output: 2 Example 2: Input: nums = [2,4,3,5,1] Output: 3 &nbsp; Constraints: 1 &lt;= nums....
from sortedcontainers import SortedList class Solution: """ For each sub array nums[0, i] We sum the reverse pairs count of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1 Using a BST(sortedList) to get logN insert and lookup time. Time: O(NlogN) Space: O(N) """ def reversePairs...
class Solution { int cnt; public int reversePairs(int[] nums) { int n = nums.length; cnt = 0; sort(0 , n - 1 , nums); return cnt; } void sort(int l , int r , int nums[]){ if(l == r){ return; } int mid = l + (r - l) / 2; sort(l ,...
class Solution { public: int merge_count(vector<int> &nums,int s,int e){ int i; int mid = (s+e)/2; int j=mid+1; long long int count=0; for(i=s;i<=mid;i++){ while((j<=e)&&((double)nums[i]/2.0)>nums[j]){ j++; } count += j-(mi...
/** * @param {number[]} nums * @return {number} */ var reversePairs = function(nums) { let ans = mergeSort(nums,0,nums.length-1); return ans; }; var mergeSort = function(nums,l,h){ if(l>=h){ return 0; } let m = Math.floor((l+h)/2); let inv = mergeSort(nums,l,m); inv = ...
Reverse Pairs
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. &nbsp; Example 1: Input: root = [1,null,2,null,3,...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def balanceBST(self, root): """ :type root: TreeNode :rtype: TreeNod...
class Solution { public TreeNode balanceBST(TreeNode root) { List<Integer> arr = new ArrayList(); InOrder( root, arr); return sortedArrayToBST( arr, 0, arr.size()-1); } public void InOrder(TreeNode node, List<Integer> arr){ if(node != null){ InOrder( node.le...
class Solution { public: vector<int> nums ; void traverse(TreeNode * root){ if(!root) return ; traverse(root->left) ; nums.push_back(root->val) ; traverse(root->right) ; return ; } TreeNode * makeTree(int s , int e){ if(s > e) return nullptr ; int...
var balanceBST = function(root) { let arr = [];//store sorted value in array let InOrder = (node) => {//inorder helper to traverse and store sorted values in array if(!node) return; InOrder(node.left); arr.push(node.val); InOrder(node.right); } InOrder(root); let BalancedFromSortedArray = (arr, ...
Balance a Binary Search Tree
We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i &lt;= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j]. Return the number of possible results. Results that occur more than once ar...
class Solution: def subarrayBitwiseORs(self, arr: List[int]) -> int: ans=set(arr) # each element is a subarry one = set() # to get the ans for the subarray of size >1 # starting from 0th element to the ending element ...
class Solution { public int subarrayBitwiseORs(int[] arr) { int n = arr.length; Set<Integer> s = new HashSet(); LinkedList<Integer> queue = new LinkedList(); for(int i = 0; i< n; i++){ int size = queue.size(); if(!queue.contains(arr[i])){ queue...
class Solution { public: int subarrayBitwiseORs(vector<int>& arr) { vector<int>s; int l=0; for(int a:arr) { int r=s.size(); s.push_back(a); for(int i=l;i<r;i++) if(s.back()!=(s[i]|a)) s.push_back(s[i] | a); l=r; ...
/** https://leetcode.com/problems/bitwise-ors-of-subarrays/ * @param {number[]} arr * @return {number} */ var subarrayBitwiseORs = function(arr) { // Hashset to store the unique bitwise this.uniqueBw = new Set(); // Dynamic programming dp(arr, arr.length - 1); return this.uniqueBw.size; }; var dp = ...
Bitwise ORs of Subarrays
You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 &lt; i &lt; words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index tha...
class Solution: def removeAnagrams(self, words: List[str]) -> List[str]: i = 0 while i < len(words) - 1: if sorted(words[i]) == sorted(words[i + 1]): words.remove(words[i + 1]) continue i += 1 return words
class Solution { public List<String> removeAnagrams(String[] words) { String prev =""; List<String> li=new ArrayList<>(); for(int i=0;i<words.length;i++){ char[] ch=words[i].toCharArray(); Arrays.sort(ch); String curr=String.valueOf(ch); if(!cu...
class Solution { public: vector<string> removeAnagrams(vector<string>& words) { for(int i = 1;i<words.size();i++){ string x = words[i]; sort(x.begin(),x.end()); string y = words[i-1]; sort(y.begin(),y.end()); if(x == y){ words.erase...
var removeAnagrams = function(words) { let n = words.length; for(let i=0; i<n-1; i++){ if(isAnagram(words[i], words[i+1])){ words.splice(i+1, 1); i-- n-- } } return words }; function isAnagram(a, b){ let freqArr = new Array(26).fill(0); ...
Find Resultant Array After Removing Anagrams
You are given an integer num. You will apply the following steps exactly two times: Pick a digit x (0 &lt;= x &lt;= 9). Pick another digit y (0 &lt;= y &lt;= 9). The digit y can be equal to x. Replace all the occurrences of x in the decimal representation of num by y. The new integer cannot have any leading zeros...
class Solution: def maxDiff(self, num: int) -> int: i=0 while i<len(str(num)): change = (str(num)[i]) if change!='9': break i+=1 i=0 flag = False while i<len(str(num)): sc = (str(num)[i]) if ...
class Solution { public int maxDiff(int num) { int[] arr = new int[String.valueOf(num).length()]; for (int i = arr.length - 1; i >= 0; i--){ arr[i] = num % 10; num /= 10; } return max(arr.clone()) - min(arr); } private int max(int[] arr){ // find max ...
class Solution { public: int power10(int n) { int total=1; for(int i=0;i<n;i++) { total*=10; } return total; } int maxDiff(int num) { vector<int> v; vector<int> w; int n = num; while (n > 0) { v.push_back(n % 10); ...
var maxDiff = function(num) { let occur = undefined; let max = num.toString().split(""); let min = num.toString().split(""); for(i=0;i<max.length;i++){ if(max[i]<9&&!occur){ occur = max[i]; max[i] = 9; } if(max[i]===occur) max[i] = 9; } occur = und...
Max Difference You Can Get From Changing an Integer
There are n rooms labeled from 0 to n - 1&nbsp;and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unloc...
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: # Create a set of for rooms visited visited_rooms = set() # Create a queue to do a breadth first search visiting rooms # Append the first room, 0, to the queue to begin the search queue = col...
class Solution { public boolean canVisitAllRooms(List<List<Integer>> rooms) { boolean[] visited = new boolean[rooms.size()]; visited[0]= true; for(int a:rooms.get(0)) { if(!visited[a]) { bfs(a, visited, rooms.size()-1, rooms); } } ...
class Solution { public: void dfs(int node, vector<vector<int>>& rooms,vector<int> &visited){ visited[node]=1; for(auto it: rooms[node]){ if(visited[it]==0) dfs(it, rooms, visited); else continue; } return; } bool canVisit...
function dfs(current,all,visited){ if(visited.size==all.length){ return true; } for(let i=0;i<all[current].length;i++){ if(!visited.has(all[current][i])){ visited.add(all[current][i]); if(dfs(all[current][i],all,visited)) return true; } } ...
Keys and Rooms
You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to covert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums f...
# Observe that: # +1 places a 1 to the end of the int's binary representation # (assuming a 0 there previously) # x2 is a bitshift left # So you basically just need to count all the ones in the binary representations # and find how many shifts are required (largest bit length minus one). class Solution: ...
class Solution { public int minOperations(int[] nums) { int odd = 0, even = 0; Map<Integer, Integer> map = new HashMap<>(); for (int n : nums){ int res = dfs(n, map); odd += res >> 5; even = Math.max(res & 0b11111, even); } return odd + ev...
class Solution { public: int minOperations(vector<int>& nums) { int ans = 0; int t = 33; while(t--){ int flag = false; for(int i = 0; i<nums.size(); i++){ if(nums[i]%2) ans++; nums[i]/=2; if(nums[i]!=0) flag = true; ...
var minOperations = function(nums) { let maxpow = 0, ans = 0, pow, val for (let i = 0; i < nums.length; i++) { for (val = nums[i], pow = 0; val > 0; ans++) if (val % 2) val-- else pow++, val /= 2 ans -= pow if (pow > maxpow) maxpow = pow } return ans + max...
Minimum Numbers of Function Calls to Make Target Array
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note tha...
class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: logs.sort(key=lambda x: x[0]) print(logs) living = 0 max_living = 0 year = 0 for ind, (start, stop) in enumerate(logs): born = ind+1 dead = 0 for i in range...
class Solution { public int maximumPopulation(int[][] logs) { int[] year = new int[2051]; // O(n) -> n is log.length for(int[] log : logs){ year[log[0]] += 1; year[log[1]] -= 1; } int maxNum = year[1950], maxYear = 1950; // O(100) -> 2050...
class Solution { public: int maximumPopulation(vector<vector<int>>& logs) { int arr[101]={0}; for(vector<int> log : logs){ arr[log[0]-1950]++; arr[log[1]-1950]--; } int max=0,year,cnt=0; for(int i=0;i<101;i++){ cnt+=arr[i]; if(c...
var maximumPopulation = function(logs) { const count = new Array(101).fill(0); for (const [birth, death] of logs) { count[birth - 1950]++; count[death - 1950]--; } let max = 0; for (let i = 1; i < 101; i++) { count[i] += count[i - 1]; if (count...
Maximum Population Year
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, i...
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ step = 0 while step < len(nums): if nums[step] == val: nums.pop(step) continue step+=1 ...
class Solution { public int removeElement(int[] nums, int val) { int ind = 0; for(int i=0; i<nums.length; i++){ if(nums[i] != val){ nums[ind++] = nums[i]; } } return ind; } }
// two pointer class Solution { public: int removeElement(vector<int>& nums, int val) { int left = 0; int right = nums.size() - 1; while (left <= right) { if (nums[left] != val) { ++left; } else if (nums[right] == val) { ...
var removeElement = function(nums, val) { for(let i = 0; i < nums.length; i++){ if(nums[i] === val){ nums.splice(i, 1); i--; } } return nums.length; };
Remove Element
Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty str...
class Solution: def findLongestWord(self, s: str, dictionary: list[str]) -> str: solution = "" for word in dictionary: j = 0 for i in range(len(s)): if s[i] == word[j]: j+=1 if j == len(word): solution = ...
class Solution { public String findLongestWord(String s, List<String> dictionary) { int[] fre=new int[26]; String ans=""; int flag=0; int[] fff=new int[26]; char[] ch = s.toCharArray(); for(char c : ch) fre[c-'a']+=1; ...
class Solution { private: //checks whether the string word is a subsequence of s bool isSubSeq(string &s,string &word){ int start=0; for(int i=0;i<s.size();i++){ if(s[i]==word[start]){ //every character of word occurs in s, therefore we return true if(...
/** * @param {string} s * @param {string[]} dictionary * @return {string} */ var findLongestWord = function(s, dictionary) { const getLen = (s1, s2) => { let i = 0, j = 0; while(i < s1.length && j < s2.length) { if(s1[i] == s2[j]) { i++, j++; } else i++; } ...
Longest Word in Dictionary through Deleting
Given the head of a linked list, return the list after sorting it in ascending order. &nbsp; Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] Example 3: Input: head = [] Output: [] &nbsp; Constraints: The number of nodes in the list is in the r...
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: store = [] curr = head while curr: store.append(curr.val) curr = curr.next store.sort() dummyNode = ListNode(0) temp = dummyNode for i in store...
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode sortList(ListNode head) { if (head ...
// Please upvote if it helps class Solution { public: ListNode* sortList(ListNode* head) { //If List Contain a Single or 0 Node if(head == NULL || head ->next == NULL) return head; ListNode *temp = NULL; ListNode *slow = head; ListNode...
function getListSize(head) { let curr = head; let size = 0; while(curr !== null) { size += 1; curr = curr.next; } return size; } function splitInHalf(head, n) { let node1 = head; let curr = head; for (let i = 0; i < Math.floor(n / 2) - 1; i++) { curr = curr.n...
Sort List
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each chi...
def canSplit(candies, mid, k): split = 0 for i in candies: split += i//mid if split >= k: return True else: return False class Solution: def maximumCandies(self, candies: List[int], k: int) -> int: end = sum(candies)//k start = 1 ans = 0 while...
class Solution { public boolean canSplit(int[] candies, long k, long mid) { long split = 0; for(int i = 0; i < candies.length; ++i) { split += candies[i]/mid; } if(split >= k) return true; else return false; } public int max...
class Solution { public: bool canSplit(vector<int>& candies, long long k, long long mid) { long long split = 0; for(int i = 0; i < candies.size(); ++i) { split += candies[i]/mid; } if(split >= k) return true; else return false; } ...
var maximumCandies = function(candies, k) { const n = candies.length; let left = 1; let right = 1e7 + 1; while (left < right) { const mid = (left + right) >> 1; const pilesAvail = divideIntoPiles(mid); if (pilesAvail < k) right = mid; else left = mid + 1; }...
Maximum Candies Allocated to K Children
Given an integer num, return the number of steps to reduce it to zero. In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. &nbsp; Example 1: Input: num = 14 Output: 6 Explanation:&nbsp; Step 1) 14 is even; divide by 2 and obtain 7.&nbsp; Step 2) 7 is odd...
class Solution: def numberOfSteps(self, num: int) -> int: count=0 while num: if num%2: num=num-1 else: num=num//2 count+=1 return count
class Solution { public int numberOfSteps(int num) { return helper(num,0); } public int helper(int n,int c){ if(n==0) return c; if(n%2==0){ //check for even no. return helper(n/2,c+1); } return helper(n-1,c+1); } }
class Solution { public: int numberOfSteps(int num) { int count = 0; while (num > 0) { if (num % 2==0) { num = num/2; count++; } else { if(num > 1) { ...
var numberOfSteps = function(num) { let steps = 0 while (num > 0) { if (num % 2 === 0) { num = num/2 steps++ } if (num % 2 === 1) { num-- steps++ } } return steps };
Number of Steps to Reduce a Number to Zero
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers. Return an in...
class Solution: def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]: #we ADD flowers in the order in which they start, but we remove them in the order they #end. For this reason, we sort the flowers by starting time but put them in a heap, #in which we rem...
class Solution { public int[] fullBloomFlowers(int[][] flowers, int[] persons) { int n = persons.length; int[] result = new int[n]; TreeMap<Integer, Integer> treeMap = new TreeMap<>(); // See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clea...
class Solution { public: vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) { vector<vector<int>> line; for (auto& f : flowers) { line.push_back({f[0], +1}); line.push_back({f[1]+1, -1}); } sort(line.begin(), line.end()); ...
/** * @param {number[][]} flowers * @param {number[]} persons * @return {number[]} */ var fullBloomFlowers = function(flowers, persons) { // *** IDEATION *** // // key observation: // total number of flowers see on day i = // number of flowers has already bloomed so far on day i - number of flowers ...
Number of Flowers in Full Bloom
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n −...
class Solution: def hIndex(self, citations: List[int]) -> int: num = sorted(citations) h = 0 j = len(num)-1 for i in range(len(num)): if i+1 <=num[i] and j-i+1>=num[i]: h =max(num[i],h) elif i+1 <= num[i] and j-i+1<num[i]: h = m...
class Solution { public int hIndex(int[] citations) { int n = citations.length; Arrays.sort(citations); for(int i = 0; i < n; i++) { int hlen = (n-1) - i + 1; if(citations[i] >= hlen) { return hlen; } } return 0; } }
class Solution { public: int hIndex(vector<int>& citations) { sort(citations.begin(),citations.end(),greater<int>()); int ans=0; for(int i=0;i<citations.size();i++){ if(citations[i]>=i+1) ans=i+1; } return ans; } };
var hIndex = function(citations) { citations.sort((a,b)=>b-a) let i=0 while(citations[i]>i) i++ return i };
H-Index
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[15,7],[9,20],[3]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = ...
class Solution: def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: def dfs(node, level, result): if not node: return if level >= len(result): result.append([]) result[level].append(node.val) dfs(node.left, ...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * ...
class Solution { void dft(TreeNode* root, int level, map<int,vector<int>,std::greater<int>>& levelVals) { if (root == nullptr) return; if (levelVals.find(level) == levelVals.end()) levelVals[level] = {root->val}; else levelVals[level].push_bac...
var levelOrderBottom = function(root) { let solution = [] function dfs(node, level) { if(!node) return null if(!solution[level]) solution[level] = [] solution[level].push(node.val) dfs(node.left, level + 1) dfs(node.right, level + 1) } dfs(root, 0) return so...
Binary Tree Level Order Traversal II
Given a binary tree root, a node X in the tree is named&nbsp;good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. &nbsp; Example 1: Input: root = [3,1,4,3,null,1,5] Output: 4 Explanation: Nodes in blue are good. Root Node (3) is alwa...
# 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 goodNodes(self, root: TreeNode) -> int: def dfs(node,maxVal): if not node: ...
class Solution { int ans = 0; public int goodNodes(TreeNode root) { if (root == null) return 0; dfs(root, root.val); return ans; } void dfs(TreeNode root, int mx) { if (root == null) return; mx = Math.max(mx, root.val); if(mx <= root.val) ans++; ...
class Solution { public: int count=0; void sol(TreeNode* root,int gr){ if(!root)return; // base condition if(gr<=root->val){ //check point max element increase count gr=max(gr,root->val); count++; } if(root->left) sol(root->left,gr); ...
var goodNodes = function(root) { let ans = 0; const traverse = (r = root, mx = root.val) => { if(!r) return; if(r.val >= mx) { ans++; } let childMax = Math.max(mx, r.val); traverse(r.left, childMax); traverse(r.right, childMax); } traverse(); ...
Count Good Nodes in Binary Tree
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops...
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: graph = defaultdict(list) for u,v,w in flights: graph[u].append((v,w)) pq = [(0,src,0)] dis = [float('inf')]*n while pq: c,n,l = heappop(pq) if n==dst: return c if l > k or l>= dis[n]:...
class Solution { public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { // Initialize Prices arr with infinity & src 0 int[] prices = new int[n]; for(int i = 0; i < n; i++) prices[i] = Integer.MAX_VALUE; prices[src] = 0; // Build A...
class Solution { public: #define f first #define s second int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k){ priority_queue< array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq; unordered_map<int, vector<pair<int,int>>> g; for(auto& f : fl...
/** * @param {number} n * @param {number[][]} flights * @param {number} src * @param {number} dst * @param {number} k * @return {number} */ const MAX_PRICE=Math.pow(10,8); var findCheapestPrice = function(n, flights, src, dst, k) { let prev=[]; let step=0; let curr=[]; for(let i=0;i<n;i++){ ...
Cheapest Flights Within K Stops
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. Given a str...
class Solution: def restoreIpAddresses(self, s: str): def isValid(st): if(len(st)!=len(str(int(st)))): return False st = int(st) if(st>255 or st<0): return False return True validIps = [] for i in range(...
class Solution { public List<String> restoreIpAddresses(String s) { List<String> ans = new ArrayList<>(); int len = s.length(); for(int i = 1; i < 4 && i < len-2 ; i++ ){ for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){ for(int k = j+1 ; k < j + 4 && k < len ; ...
class Solution { public: vector<string> res; void dfs(string s,int idx,string curr_ip,int cnt) { if(cnt>4) return; if(cnt==4&&idx==s.size()) { res.push_back(curr_ip); // return; } for(int i=1;i<4;i++) { if(idx+i>s...
var restoreIpAddresses = function(s) { const results = []; const go = (str, arr) => { // if we used every character and have 4 sections, it's a good IP! if (str.length === 0 && arr.length === 4) { results.push(arr.join('.')); return; } // we already have ...
Restore IP Addresses
You are given an integer array nums that is sorted in non-decreasing order. Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous inte...
class Solution: from collections import defaultdict def isPossible(self, nums): # If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more. if len(nums) < 3: return False # 'count' dictionary stores the frequency of each numbe...
class Solution { public boolean isPossible(int[] nums) { int[] freq = new int[2002], subEnd = new int[2002]; for (int i : nums) { int num = i + 1001; freq[num]++; } for (int i : nums) { int num = i + 1001; if (freq[num] == 0) continue; // Num already in use freq[num]--; ...
class Solution { public: bool isPossible(vector<int>& nums) { priority_queue<int, vector<int>, greater<int>> pq; unordered_map<int, int> um; for(int &num : nums) { pq.push(num); um[num]++; } queue<int> q; int count = 0, prev; wh...
var isPossible = function(nums) { const need = new Map(); const hash = nums.reduce((map, num) => { const count = map.get(num) ?? 0; map.set(num, count + 1); return map; }, new Map()); for (const num of nums) { const current = hash.get(num); if (current === 0) continue; const currentNeed = need.get(num...
Split Array into Consecutive Subsequences
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the ...
class Solution: def minOperations(self, nums1: List[int], nums2: List[int]) -> int: # step1. determine the larger array and the smaller array, and get the difference on sum sum1 = sum(nums1) sum2 = sum(nums2) if sum1==sum2: return 0 elif sum1>sum2: ...
class Solution { public int minOperations(int[] nums1, int[] nums2) { int m = nums1.length, n = nums2.length; if (m > 6 * n || n > 6 * m) return -1; int sum1 = 0, sum2 = 0; for (int i : nums1) sum1 += i; for (int i : nums2) sum2 += i; int diff = sum1 - sum2; ...
/** * @brief * Given two array, return the minimum numbers we have to change the values to make two arrays sum equal * * [Observation] * Since the value is from 1 ~ 6 * * Min sum of the array = len(arr) * Max sum of the array = 6 len(arr) * * When to arrays range cannot overlap -> no answer * * If there is ...
var minOperations = function(nums1, nums2) { /* Two impossible cases: min1...max1 ... min2...max2 -> we can't make them equal min2...max2 ... min1...max1 -> we can't make them equal */ let min1 = nums1.length * 1; let max1 = nums1.length * 6; let min2 = nums2.length * 1; let max2 = n...
Equal Sum Arrays With Minimum Number of Operations
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. A subsequence is a sequence that can be derived from arr by deleting some or no elements wit...
class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int: d = defaultdict(int) for num in arr: if num - difference in d: d[num] = d[num - difference] + 1 else: d[num] = 1 return max((d[x] for x in d))
class Solution { public int longestSubsequence(int[] arr, int difference) { int max = 1; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { // find the target element using the current element and the given difference int target = arr[...
class Solution { public: int longestSubsequence(vector<int>& arr, int difference) { int n = arr.size(); unordered_map<int,int>mp; multiset<int>s; int ans = 1; for(int i=0;i<n;i++) { int req = arr[i] - difference; auto...
var longestSubsequence = function(arr, difference) { const map = new Map() let max = 0 for(let num of arr) { const prev = map.has(num - difference) ? map.get(num -difference) : 0 const val = prev + 1 map.set(num, val) max = Math.max(max, val) } return max };
Longest Arithmetic Subsequence of Given Difference
Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true If you can find a way to do that or false otherwise. &nbsp; Example 1: Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5 Output: true Explanat...
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: #The idea is to count the residues #If every residue has the counter residue #such that x+y == k,then we found a pair count = [0]*k for num in arr: count[num%k] +=1 ...
class Solution { public boolean canArrange(int[] arr, int k) { int[] frequency = new int[k]; for(int num : arr){ num %= k; if(num < 0) num += k; frequency[num]++; } if(frequency[0]%2 != 0) return false; for(int i = 1; i <= k/2; i++...
//ask the interviewer //can we have negative values? class Solution { public: bool canArrange(vector<int>& arr, int k) { unordered_map<int,int>memo;//remainder : occurence //we are storing the frequency of curr%k //i.e. the frequency of the remainder for(auto curr : arr) ...
var canArrange = function(arr, k) { let map = new Map(); let index = 0; for(let i = 0; i < arr.length; i++){ let val = arr[i] % k; if(val<0) val+=k; if(map.get(k-val)) map.set(k-val, map.get(k-val) - 1), index--; else if(map.get(-val)) map.set(-val, map.get(-val) - 1), index-...
Check If Array Pairs Are Divisible by k
Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. &nbsp; Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: false Example 3: Input: n = 1 Output: true &nbsp; Constraints: -231 &lt;=...
import math class Solution: def isPowerOfFour(self, n: int) -> bool: if n <= 0: return False return math.log(n, 4).is_integer()
class Solution { public boolean isPowerOfFour(int n) { return (Math.log10(n)/Math.log10(4))%1==0; } }
class Solution { public: bool isPowerOfFour(int n) { if(n==1) return true; long long p=1; for(int i=1;i<n;i++) { p=p*4; if(p==n) return true; if(p>n) return false; } return false; } };
var isPowerOfFour = function(n) { if(n==1){ return true } let a=1; for(let i=2;i<=30;i++){ a=a*4 if(a===n){ return true } } return false };
Power of Four
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. &nbsp; Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,1...
class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: # sort the index of element heap = list() n = len(nums) for i in range(n): m = len(nums[i]) for j in range(m): heapq.heappush(heap,[i+j,j,i]) # append the element...
class Solution { public int[] findDiagonalOrder(List<List<Integer>> nums) { HashMap<Integer , Stack<Integer>> map = new HashMap(); for(int i = 0 ; i < nums.size() ; i++){ for(int j = 0 ; j < nums.get(i).size() ; j++){ int z = i + j; if(map.containsKey(z)){ m...
class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& nums) { int n = nums.size(); int m = 0; for(vector<int> &v : nums) { int y = v.size(); m = max(m, y); } vector<int> D2[n+m-1]; for(int i = 0; i < n; i++) ...
var findDiagonalOrder = function(nums) { let vals = []; // [row, diagonal value, actual value] for (let i = 0; i < nums.length; i++) { for (let j = 0; j < nums[i].length; j++) { vals.push([i, i + j, nums[i][j]]); } } vals.sort((a, b) => { if (a[1] === b[1]) return b[0] - a[0]; return a[1] ...
Diagonal Traverse II
Given two binary strings a and b, return their sum as a binary string. &nbsp; Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" &nbsp; Constraints: 1 &lt;= a.length, b.length &lt;= 104 a and b consist&nbsp;only of '0' or '1' characters. Each string does no...
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return str(bin(int(a, base = 2)+int(b, base = 2)))[2:]
class Solution { public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int carry = 0; int i= a.length() -1; int j= b.length() -1; while(i>=0 || j>=0){ int sum = carry; if(i>=0) sum+=a.charAt(i--)-'0'; // ...
class Solution { public: string addBinary(string a, string b) { string ans; int i=a.length()-1,j=b.length()-1; int carry=0; while(carry||i>=0||j>=0){ if(i>=0){ carry+=a[i]-'0'; i--; } if(j>=0){ carry+...
var addBinary = function(a, b) { let i = a.length-1, j = b.length-1, carry = 0 let s =[] while(i >= 0 || j >= 0){ let sum = carry if(i >= 0) sum += a[i--].charCodeAt() - 48 if(j >= 0) sum += b[j--].charCodeAt() - 48 s.unshift(sum % 2) carry = ~~(sum/2) } ret...
Add Binary
Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between two strings is a string that is a subsequence of one but not the other. A subsequence of a string s is a string that can be o...
class Solution: def findLUSlength(self, a: str, b: str) -> int: if a == b: return -1 else: return max(len(a), len(b))
class Solution { public int findLUSlength(String a, String b) { if(a.equals(b)) return -1; return Math.max(a.length(),b.length()); } }
class Solution { public: int findLUSlength(string a, string b) { if(a==b){ return -1; } if(a.size()>=b.size()){ return a.size(); } return b.size(); } };
var findLUSlength = function(a, b) { if (a===b) return -1 return Math.max(a.length,b.length) };
Longest Uncommon Subsequence I
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queue that is represe...
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: n = len(people) people.sort() ans = [[]]*n i = 0 while people: h,p = people.pop(0) count= p for i in range(n): if count== 0 and ans[i] == []: ans[i] = [h,p] break elif not ans[i] or (ans[i] and...
class Solution { public int[][] reconstructQueue(int[][] people) { List<int[]> result = new ArrayList<>(); //return value Arrays.sort(people, (a, b) -> { int x = Integer.compare(b[0], a[0]); if(x == 0) return Integer.compare(a[1], b[1]); else return x; }); ...
#include <bits/stdc++.h> using namespace std; struct node { int h, k; node *next; node(int h, int k) : h(h), k(k), next(nullptr){} }; bool cmp(vector<int>& p1, vector<int>& p2) { return (p1[0] != p2[0]) ? (p1[0] > p2[0]) : (p1[1] < p2[1]); } void insert(vector<int>& p, node **target) { node *new_p = new no...
var reconstructQueue = function(people) { var queue = new Array(people.length); people = people.sort((a,b) => (a[0]-b[0])); for(let i =0;i<people.length;i++){ let count = 0; for(let j= 0;j<queue.length;j++){ if(!queue[j]){ if(count == people[i][1]){ ...
Queue Reconstruction by Height
Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them. &nbsp; Example 1: Input: root = [5,4,5,1,1,null,5] Outpu...
class Solution: max_path=0 def longestUnivaluePath(self, root: Optional[TreeNode]) -> int: self.dfs(root); return self.max_path def dfs(self,root): if root is None:return 0 left=self.dfs(root.left) right=self.dfs(root.right) if root.left and root.left.val == root.val: leftPath=left+1 else: le...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * ...
class Solution { public: int maxlen=0; pair<int,int> util(TreeNode* root,int val ){ if(!root) return {0,-1001}; // in pair we will the first part will return the no nodes , //and in the second part we will return the value associated with it pair<int,int> l=util(roo...
var longestUnivaluePath = function(root) { let max = 0; const dfs = (node = root, parentVal) => { if (!node) return 0; const { val, left, right } = node; const leftPath = dfs(left, val); const rightPath = dfs(right, val); max = Math.max(max, leftPath + rightPath); return val === parentVal ? Math.max(...
Longest Univalue Path
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large, ret...
from functools import lru_cache class Solution: def largestNumber(self, cost: List[int], target: int) -> str: @lru_cache(None) def dfs(t): if t == 0: return 0 res = float('-inf') for digit in range(1,10): if t - cost[digit-1] >= 0: ...
// Space Complexity = O(N*M) (N == length of cost array and M == target ) // Time Complexity = O(N*M) class Solution { Map<String,String> map = new HashMap<>(); String[][] memo; public String largestNumber(int[] cost, int target) { memo = new String[cost.length+1][target+1]; for( ...
class Solution { public: vector<vector<string>> dp ; string largestNumber(vector<int>& cost, int target) { dp.resize(10,vector<string>(target+1,"-1")); return solve(cost,0,target) ; } string solve(vector<int>& cost,int idx,int target){ if(!target) return ""; if(targe...
var largestNumber = function(cost, target) { const arr = new Array(target+1).fill('#'); arr[0] = ''; for (let i = 0; i < 9; i++) { for (let j = cost[i]; j <= target; j++) { if (arr[j-cost[i]] !== '#' && arr[j-cost[i]].length + 1 >= arr[j].length) { arr[j] = (i+1).toS...
Form Largest Integer With Digits That Add up to Target
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. Return the minimum number of operations needed to make nums strictly increasing. An array num...
class Solution: def minOperations(self, nums: List[int]) -> int: sol = 0 last = nums[0] for i in range(len(nums) - 1): if last >= nums[i + 1]: sol += last - nums[i + 1] + 1 last = last + 1 else: last = nums[i + 1] ...
class Solution { public int minOperations(int[] nums) { if (nums.length <= 1) { return 0; } int count = 0; int num = nums[0]; for (int i = 1; i < nums.length; i++) { if (num == nums[i]) { count++; num++; } e...
class Solution { public: int minOperations(vector<int>& nums) { int output=0; for(int i=0;i<nums.size()-1;i++){ if(nums[i]<nums[i+1]) continue; else{ output=output+(nums[i]+1-nums[i+1]); nums[i+1]=nums[i]+1; } ...
var minOperations = function(nums) { if(nums.length < 2) return 0; let count = 0; for(let i = 1; i<nums.length; i++) { if(nums[i] <= nums[i-1]) { let change = nums[i-1] - nums[i] + 1; count += change; nums[i] += change; } } return count; };
Minimum Operations to Make the Array Increasing
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute...
class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: min_possible = sum(min(row) for row in mat) if min_possible >= target: return min_possible - target curs = {0} for row in mat: curs = {x + y for x in row for y in curs if x + y <= 2...
class Solution { public int minimizeTheDifference(int[][] mat, int target) { Integer[][] dp = new Integer[mat.length][5001]; return minDiff(mat, 0, target,0, dp); } public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){ if(index == mat.length){ re...
class Solution { public: int dp[8000][71]; int n,m; int find(vector<vector<int>>&mat,int r,int sum,int &target) { if(r>=n) { return abs(sum-target); } if(dp[sum][r]!=-1) { return dp[sum][r]; } int ans=INT_MAX; for(i...
var minimizeTheDifference = function(mat, target) { const MAX = Number.MAX_SAFE_INTEGER; const m = mat.length; const n = mat[0].length; const memo = []; for (let i = 0; i < m; ++i) { memo[i] = new Array(4901).fill(MAX); } return topDown(0, 0); function to...
Minimize the Difference Between Target and Chosen Elements
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a ...
class Solution: def countPrefixes(self, words: List[str], s: str) -> int: return len([i for i in words if s.startswith(i)])
class Solution { public int countPrefixes(String[] words, String s) { int i = 0; int j = 0; int count = 0; for(int k = 0; k < words.length; k++){ if(words[k].length() > s.length()){ continue; } while(i < words[k].length...
class Solution { public: int countPrefixes(vector<string>& words, string s) { int res = words.size(); for (auto && word : words) { for (int i = 0; i < word.size(); i++) { if (s[i] != word[i]) { res--; break; } ...
var countPrefixes = function(words, s) { let cont = 0; for(i = 0; i < words.length; i++){ for(j = 1; j <= s.length; j++){ if(words[i] == s.slice(0, j)){ cont++; } } } return cont; };
Count Prefixes of a Given String
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string. &nbsp; Example 1: Input: patterns = ["a","abc","bc","d"], word = "abc" Output: 3 Explanation: - "a" appears as a substr...
class Solution: def numOfStrings(self, patterns: List[str], word: str) -> int: return sum([pattern in word for pattern in patterns])
class Solution { public int numOfStrings(String[] patterns, String word) { int count = 0; for(int i=0;i<patterns.length;i++){ if(word.contains(patterns[i])){ count++; } } return count; } }
class Solution { public: int numOfStrings(vector<string>& patterns, string word) { int count=0; for(int i=0;i<patterns.size();i++) { if(word.find(patterns[i])!=string::npos) count++; } return count; } };
/** * @param {string[]} patterns * @param {string} word * @return {number} */ var numOfStrings = function(patterns, word) { let result = 0; for(let char of patterns){ if(word.includes(char)){ result++; } else{ result += 0; } } retur...
Number of Strings That Appear as Substrings in Word
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Create a root node whose value is the maximum value in nums. Recursively build the left subtree on the subarray prefix to the left of the maximum value. Recursively build ...
class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: if not nums: return None m = max(nums) idx = nums.index(m) root = TreeNode(m) root.left = self.constructMaximumBinaryTree(nums[:idx]) root.right = self.constructMaximumBinaryTree(nums[idx+1:]) return root
class Solution { public TreeNode constructMaximumBinaryTree(int[] nums) { TreeNode root = construct(nums,0,nums.length-1); return root; } private TreeNode construct(int []nums, int start, int end) { if(start > end) return null; if(start == end) re...
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l...
var constructMaximumBinaryTree = function(nums) { if (nums.length === 0) return null; let max = Math.max(...nums); let index = nums.indexOf(max); let left = nums.slice(0, index); let right = nums.slice(index + 1); let root = new TreeNode(max); root.left = constructMaximumBinaryTree(left); ...
Maximum Binary Tree
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There is no...
class Codec: def encode(self, longUrl): return longUrl def decode(self, shortUrl): return shortUrl
public class Codec { // Encodes a URL to a shortened URL. public String encode(String longUrl) { return longUrl; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return shortUrl; } }
class Solution { private: unordered_map<string, string> hash; string server = "http://tinyurl.com/"; string all = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; public: // Encodes a URL to a shortened URL. string encode(string longUrl) { srand(time(NULL)); string...
let arr = new Array(); let size = 0; var encode = function(longUrl) { arr.push(longUrl) let i = longUrl.indexOf('/',11); longUrl.slice(i); longUrl += this.size; arr.push(longUrl); size += 2; return longUrl; }; var decode = function(shortUrl) { let i = 0; while(arr[i] !== shortUrl &...
Encode and Decode TinyURL
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). &nbsp; Example 1: Input: root = [1,2,2,3,4,4,3] Output: true Example 2: Input: root = [1,2,2,null,3,null,3] Output: false &nbsp; Constraints: The number of nodes in the tree is in the range [1, 1000]. ...
class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: return root is None or self.findSymmetric(root.left, root.right) def findSymmetric(self, left, right): if (left is None or right is None): return left == right if (left.val != right.val): r...
class Solution { public boolean isSymmetric(TreeNode root) { return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) { if(rootLeft == null && rootRight == null) {return true;} if(rootLeft == null || rootRight == null) {return fal...
class Solution { public: bool mirror(TreeNode* root1, TreeNode* root2){ if(root1==NULL and root2==NULL) return true; if(root1==NULL or root2==NULL) return false; if(root1->val!=root2->val) return false; return mirror(root1->left, root2->right) and mirror(root1->right,root2->left);...
var isSymmetric = function(root) { return helper(root.left, root.right); function helper(left, right){ if(!left && !right) return true; if((!left && right) || (left && !right) || (left.val !== right.val)) return false; return helper(left.left, right.right) && helper(left.right, right.le...
Symmetric Tree
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is cons...
class Solution: def findMiddleIndex(self, nums: List[int]) -> int: A = [0] + list(accumulate(nums)) + [0] total, n = sum(nums), len(nums) for i in range(n): if A[i] == total - A[i] - nums[i]: return i return -1
class Solution { public int findMiddleIndex(int[] nums) { for(int i=0;i<nums.length;i++) { int rsum=0; int lsum=0; for(int k=0;k<i;k++) lsum+=nums[k]; for(int k=i+1;k<nums.length;k++) rsum+=nums[k]; if(lsum==rsum){ return...
class Solution { public: int findMiddleIndex(vector<int>& nums) { int n=nums.size(); int left_sum=0; int right_sum=0; for(int i=0;i<n;i++) { right_sum+=nums[i]; } for(int i=0;i<n;i++) { right_sum-=nums[i]; if...
var findMiddleIndex = function(nums) { for (let i = 0; i < nums.length; i++) { let leftNums = nums.slice(0, i).reduce((a, b) => a + b, 0); let rightNums = nums.slice(i + 1).reduce((a, b) => a + b, 0); if (leftNums === rightNums) { return i; } } return -1; };
Find the Middle Index in Array
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -&gt; s1 -&gt; s2 -&gt; ... -&gt; sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 &lt;= i &lt;= k is in wordList. Note that beginWord does not need to be i...
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: e = defaultdict(list) m = len(beginWord) for word in wordList + [beginWord]: for i in range(m): w = word[:i] + "*" + word[i + 1:] e[w].append(word) ...
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { int count = 1; Set<String> words = new HashSet<>(wordList); Queue<String> q = new LinkedList<String>(); q.add(beginWord); while(!q.isEmpty()) { int size = ...
// For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { // 1. Create a set and insert all wordList to the set to have // easy search of O(1) unordered_set<string> wordS...
/** * @param {string} beginWord * @param {string} endWord * @param {string[]} wordList * @return {number} */ // Logic is same as One direction, just from both side tword mid, much faster. // One Direction solution is here -> // https://leetcode.com/problems/word-ladder/discuss/2372376/Easy-Fast-Simple-83.95-235-m...
Word Ladder
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] &gt; nums[i] for all 0 &lt; i &lt; nums.length. Return the number of steps performed until nums becomes a non-decreasing array. &nbsp; Example 1: Input: nums = [5,3,4,4,7,3,6,11,8,5,11] Output: 3 Explanation: The...
class Solution: def totalSteps(self, nums: List[int]) -> int: st = [] ans = 0 for i in nums: t = 0 while st and st[-1][0] <= i: t = max(t, st.pop()[1]) x = 0 if st: x = t+1 st.append([i, x]) ...
class Solution { public int totalSteps(int[] nums) { int n = nums.length; int ans = 0; Stack<Pair<Integer,Integer>> st = new Stack(); st.push(new Pair(nums[n-1],0)); for(int i=n-2;i>=0;i--) { int ...
class Solution { public: using pi = pair<int, int>; int totalSteps(vector<int>& nums) { int N = nums.size(); map<int, int> mp; vector<pi> del; // stores pairs of (previous id, toDelete id) for (int i = 0; i < N; ++i) { mp[i] = nums[i]; if (i+1 < N && nu...
var totalSteps = function(nums) { let stack = [], dp = new Array(nums.length).fill(0), max = 0 for (let i = nums.length - 1; i >= 0; i--) { while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) { dp[i] = Math.max(++dp[i], dp[stack.pop()]) max = Math...
Steps to Make Array Non-decreasing
Given a m&nbsp;* n&nbsp;matrix seats&nbsp;&nbsp;that represent seats distributions&nbsp;in a classroom.&nbsp;If a seat&nbsp;is&nbsp;broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but h...
class Solution: def maxStudents(self, seats: List[List[str]]) -> int: m, n = len(seats), len(seats[0]) match = [[-1]*n for _ in range(m)] def dfs(i, j, visited): for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]: if 0 <= x < m and 0 <= y < n an...
class Solution { private Integer[][] f; private int n; private int[] ss; public int maxStudents(char[][] seats) { int m = seats.length; n = seats[0].length; ss = new int[m]; f = new Integer[1 << n][m]; for (int i = 0; i < m; ++i) { for (int j = 0; j <...
class Solution { public: int dp[8][(1 << 8) - 1]; int maxStudents(vector<vector<char>>& seats) { memset(dp, -1, sizeof(dp)); return helper(seats, 0, 0); } int helper(vector<vector<char>>& seats, int prevAllocation, int idx) { if (idx == seats.size()) return 0; int sz = seats[0].size(), masks = ...
var maxStudents = function(seats) { if (!seats.length) return 0; // precalculate the seat that will be off the matrix const lastPos = 1 << seats[0].length; // encode the classroom into binary where 1 will be an available seat and 0 will be a broken seat const classroom = seats.map((row) => ( ...
Maximum Students Taking Exam
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. &nbsp; Example 1: Input: n = 3 Output: 3 Example 2: Input: n = 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. ...
class Solution: def findNthDigit(self, n: int) -> int: low, high = 1, 0 place = 1 sum_ = 0 while True: high = 10**place -1 digits_sum = (high - low +1 ) * place if sum_<= n <= digits_sum + sum_: break ...
class Solution { public int findNthDigit(int n) { if(n < 10) return n; long currDigitIndex = 10; int tillNextIncrease = 90; int currNumberSize = 2; int currNumber = 10; int next = tillNextIncrease; while(currDigitIndex < n) { currNu...
class Solution { public: #define ll long long int findNthDigit(int n) { if(n<=9) return n; ll i=1; ll sum=0; while(true){ ll a=(9*pow(10,i-1))*i; if(n-a<0){ break; } else{ sum+=9*pow(10,i-1); ...
var findNthDigit = function(n) { var len = 1; var range = 9; var base = 1; while(n>len*range) { n -= len *range; range *= 10; base *= 10; len++; } // [100, 101, 102,...] // 100 should have offset 0, use (n-1) to make the counting index from 0-based. va...
Nth Digit
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down...
class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: x, y = entrance m, n, infi = len(maze), len(maze[0]), int(1e5) reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1) @lru_cache(None) def dfs(i, j): ...
class Solution { public int nearestExit(char[][] maze, int[] entrance) { int rows = maze.length, cols = maze[0].length, queueSize; Queue<int[]> queue = new LinkedList<>(); boolean[][] visited = new boolean[rows][cols]; int[] curr; int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}}; ...
class Solution { public: //checks if the coordinates of the cell are that of an unvisited valid empty cell bool isValid(int x,int y,int n,int m, vector<vector<char>>& maze,vector<vector<int>>& visited){ if(x>=0 && x<n && y>=0 && y< m && maze[x][y]!='+' && visited[x][y]!=1){ return true; ...
function nearestExit(maze, entrance) { const queue = []; // queue for bfs const empty = "."; const [height, width] = [maze.length, maze[0].length]; const tried = [...Array(height)].map(() => Array(width).fill(false)); const tryStep = (steps, row, col) => { // don't reuse once it's already been tried i...
Nearest Exit from Entrance in Maze
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original ...
import random class Solution: def __init__(self, nums: List[int]): self.nums = nums def reset(self) -> List[int]: return self.nums def shuffle(self) -> List[int]: shuffled_array = self.nums.copy() # randomly generates the idx of the element that'll be the ith element o...
class Solution { int a[]; int b[]; public Solution(int[] nums) { a=nums.clone(); b=nums.clone(); } public int[] reset() { a=b.clone(); return a; } public int[] shuffle() { for(int i=0;i<a.length;i++){ int ren=(int)(Math.random()*a.lengt...
class Solution { public: vector<int> ans; vector<int> res; Solution(vector<int>& nums) { ans=nums; res=nums; } vector<int> reset() { return res; } vector<int> shuffle() { next_permutation(ans.begin(),ans.end()); return ans; } };
var Solution = function(nums) { this.nums = nums; this.resetArray = [...nums]; }; Solution.prototype.reset = function() { return this.resetArray; }; Solution.prototype.shuffle = function() { const n = this.nums.length; const numsArray = this.nums; for (let i = 0; i < n; i++) { const ...
Shuffle an Array
Given a rows x cols&nbsp;binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. &nbsp; Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 6 Explanation: The maximal rectangle is shown in the a...
class Solution: def maxArea(self,arr: List[List[int]]) -> int: maxA = 0 #local max variable to return max area of a 1D array stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing arr.append(-1) # value for stack ind...
class Solution { public int maximalRectangle(char[][] matrix) { ArrayList<Integer> list = new ArrayList<>(); int n = matrix[0].length; for(int i=0; i<n; i++){ list.add(Character.getNumericValue(matrix[0][i])); } int maxArea = maximumArea(list); int m = ma...
class Solution { private: vector<int> nextSmallerElement(int *arr , int n){ stack<int> st; st.push(-1); vector<int> ans(n); for(int i = n - 1 ; i >= 0 ; i--){ int curr = arr[i]; while(st.top() != -1 && arr[st.top()] >= curr){ ...
var maximalRectangle = function(matrix) { const m = matrix.length; const n = matrix[m - 1].length; const prefixSum = new Array(m).fill().map(() => new Array(n).fill(0)); for(let i = 0; i < m; i += 1) { for(let j = 0; j < n; j += 1) { prefixSum[i][j] = parseInt(matrix[i][j]); ...
Maximal Rectangle
A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East". The robot can be instructed to move f...
class Robot: def __init__(self, width: int, height: int): self.perimeter = 2*width + 2*(height - 2) self.pos = 0 self.atStart = True self.bottomRight = width - 1 self.topRight = self.bottomRight + (height - 1) self.topLeft = self.topRight + (width - 1) def step...
class Robot { int p; int w; int h; public Robot(int width, int height) { w = width - 1; h = height - 1; p = 0; } public void step(int num) { p += num; } public int[] getPos() { int remain = p % (2 * (w + h)); if (remain <= w) ...
class Robot { private: int width, height, perimeter; int dir = 0; int x = 0, y = 0; map<int, string> mp = {{0, "East"}, {1, "North"}, {2, "West"}, {3, "South"}}; public: Robot(int width, int height) { this->width = width; this->height = height; this->perimeter = 2 * (height ...
const EAST = "East"; const NORTH = "North"; const WEST = "West"; const SOUTH = "South"; const DIRECTIONS = [EAST, NORTH, WEST, SOUTH]; const ORIGIN = [0,0]; /** * @param {number} width * @param {number} height */ var Robot = function(width, height) { this.width = width; this.height = height; this.path...
Walking Robot Simulation II
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i]. When a customer is paying, their bill is represented as two parallel integer arr...
class Cashier: def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): self.n = n self.discount = discount self.price = { } self.customer = 0 for i in range(len(products)) : self.price[products[i]] = prices[i] ...
class Cashier { private Map<Integer, Integer> catalogue; private int n; private double discount; private int orderNumber; public Cashier(int n, int discount, int[] products, int[] prices) { this.catalogue = new HashMap<>(); for (int i = 0; i < prices.length; i++) {...
class Cashier { public: int nn = 0; double dis = 0; vector<int> pro; vector<int> pri; int currCustomer = 0; //Declaring these variables here to use it in other fxns as well Cashier(int n, int discount, vector<int>& products, vector<int>& prices) { nn = n; dis = discount; ...
var Cashier = function(n, discount, products, prices) { this.n = n; this.cc = 0; this.discount = (100 - discount) / 100; this.products = new Map(); const len = products.length; for(let i = 0; i < len; i++) { this.products.set(products[i], prices[i]); } }; Cashier.prototype.getBill =...
Apply Discount Every n Orders
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are uniqu...
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: path = [] answer = [] def dp(idx, total): if total == target: answer.append(path[:]) return if total > target: return ...
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<Integer> cur = new ArrayList<>(); List<List<Integer>> result = new ArrayList<>(); Arrays.sort(candidates); dfs(0, candidates, target, 0, cur, result); return result; } publ...
class Solution { void combination(vector<int>& candidates, int target, vector<int> currComb, int currSum, int currIndex, vector<vector<int>>& ans){ if(currSum>target) return; //backtrack if(currSum==target){ ans.push_back(currComb); //store the solution and backtrack return; ...
function recursion(index, list, target, res, arr){ if(index == arr.length){ if(target == 0){ res.push([...list]); } return; } if(arr[index] <= target){ list.push(arr[index]); recursion(index, list, target - arr[index], res, arr); list.pop();...
Combination Sum
You are given an n x n integer matrix. You can do the following operation any number of times: Choose any two adjacent elements of matrix and multiply each of them by -1. Two elements are considered adjacent if and only if they share a border. Your goal is to maximize the summation of the matrix's elements. Retur...
class Solution: def maxMatrixSum(self, matrix: List[List[int]]) -> int: # count -'s count = 0 for row in matrix: for col_num in row: if col_num < 0: count += 1 tot_sum = sum([sum([abs(x) for x in row]) for row in ...
class Solution { public long maxMatrixSum(int[][] matrix) { long ans = 0; int neg = 0; int min = Integer.MAX_VALUE; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ if(matrix[i][j] < 0) { neg++; ...
/** * @author : archit * @GitHub : archit-1997 * @Email : architsingh456@gmail.com * @file : maximumMatrixSum.cpp * @created : Saturday Aug 21, 2021 20:11:56 IST */ #include <bits/stdc++.h> using namespace std; class Solution { public: long long maxMatrixSum(vector<vector<int>>& m...
var maxMatrixSum = function(matrix) { const MAX= Number.MAX_SAFE_INTEGER; const m = matrix.length; const n = matrix[0].length; let negs = 0; let totAbsSum = 0; let minAbsNum = MAX; for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) { if (matrix[i][j] < 0) ++neg...
Maximum Matrix Sum
Given an n x n grid&nbsp;containing only values 0 and 1, where&nbsp;0 represents water&nbsp;and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance.&nbsp;If no land or water exists in the grid, return -1. The distance used in this problem is the Ma...
from collections import * class Solution: def maxDistance(self, grid) -> int: m,n=len(grid),len(grid[0]) queue=deque([]) for i in range(m): for j in range(n): if grid[i][j]==1: queue.append((i,j)) c=-1 while queue: #...
class Solution { class Point { int x, y; public Point(int x, int y){ this.x=x; this.y=y; } } int[][] dist; int n,ans; int[] dx={0, 0, +1, -1}; int[] dy={+1, -1, 0, 0}; public int maxDistance(int[][] grid) { n=grid.length; dist =...
class Solution { vector<int> dr = {0,0,1,-1}; vector<int> dc = {1,-1,0,0}; public: bool isPos(int r,int c,int n){ return ( r>=0 && c>=0 && r<n && c<n ); } int maxDistance(vector<vector<int>>& grid) { int n = grid.size(); vector< vector<int> > dist(n,vector<int>(n,-1)); ...
/** * @param {number[][]} grid * @return {number} */ const DIR = [ [0,1], [0,-1], [1,0], [-1,0] ]; var maxDistance = function(grid) { const ROWS = grid.length; const COLS = grid[0].length; const cost = new Array(ROWS).fill().map(()=>new Array(COLS).fill(Infinity)); const que = []; ...
As Far from Land as Possible
There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp ...
class Solution: def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: rows = collections.Counter() cols = collections.Counter() diags1 = collections.Counter() diags2 = collections.Counter() lamps = {tuple(lamp) for lamp in lamps} ...
class Solution { public int[] gridIllumination(int n, int[][] lamps, int[][] queries) { //we take 5 hashmap //1st hashmap for row HashMap<Integer, Integer> row = new HashMap<>(); //2nd hashmap for column HashMap<Integer, Integer> col = new HashMap<>(); //3rd hashmap f...
class Solution { public: // store info about rows , coulms and diagonal that is illuminated // if (i,j) is lamp , then every cell (x,y) is illuminated if // x==i (row) || y==j (column) || x+y == i+j (anti diagonal) || x-y == i-j (main diagonal) vector<int> gridIllumination(int n, vector<vector<int>>& l...
var gridIllumination = function(n, lamps, queries) { const directions = [[0,0], [-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]]; const lampCoord = new Map(); const rowHash = {}, colHash = {}, leftDiag = {}, rightDiag = {}; // First, illuminate the lamps for (let [r, c] of lamp...
Grid Illumination
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space. &nbsp; Example 1: Input: nums = [3,6,9,1] Output: 3 Explanation: The...
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums)<2: return 0 #radix sort #N = length of nums #find number of digits in largest number - O(K) where K = length of largest number longest = 0 for i in nums: longest = max(long...
class Solution { public int maximumGap(int[] nums) { Arrays.sort(nums); int res=0; if(nums.length==0){ return 0; } for (int i =0;i<nums.length-1;i++){ res=Math.max(Math.abs(nums[i]-nums[i+1]),res); } return res; } }
class Solution { public: int maximumGap(vector<int>& nums) { sort(nums.begin(),nums.end()); int res; int maxx=INT_MIN; map<int,int> m; if(nums.size()==1) return 0; for(int i =0;i<nums.size()-1;i++) { m[i]=nums[i+1]-nums[i]; } ...
/** * The buckets solution. * * Time Complexity: O(n) * Space Complexity: O(n) * * @param {number[]} nums * @return {number} */ var maximumGap = function(nums) { const n = nums.length if (n < 2) { return 0 } if (n < 3) { return Math.abs(nums[0] - nums[1]) } let maxNum ...
Maximum Gap
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. &nbsp; Example...
class Solution: def minimumRounds(self, tasks: List[int]) -> int: dic={} c=0 for i in tasks: if i in dic.keys(): dic[i]+=1 else: dic[i]=1 for i in dic.keys(): if dic[i]==1: return -1 while...
/** Each round, we can complete either 2 or 3 tasks of the same difficulty level Time: O(n) Space: O(n) */ class Solution { public int minimumRounds(int[] tasks) { int round = 0; Map<Integer, Integer> taskMap = new HashMap<>(); // map of <task, number of each task> for (int i = 0; ...
class Solution { public: int minimumRounds(vector<int>& tasks) { map<int,int> hm; for(int i=0;i<tasks.size();i++){ hm[tasks[i]]++; } int num,freq,ans=0; for (auto i : hm){ freq = i.second; if(freq==1) return -1; ...
var minimumRounds = function(tasks) { const hash = {}; let minRounds = 0; for (const task of tasks) { hash[task] = hash[task] + 1 || 1; } for (const count of Object.values(hash)) { if (count < 2) return -1; minRounds += Math.ceil(count / 3); } return minRounds; };
Minimum Rounds to Complete All Tasks
A sequence x1, x2, ..., xn is Fibonacci-like if: n &gt;= 3 xi + xi+1 == xi+2 for all i + 2 &lt;= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. A subsequence is derived from anot...
class Solution(object): #DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A) def lenLongestFibSubseq(self, A): index = {Ai: i for i, Ai in enumerate(A)} dp = collections.defaultdict(lambda: 2) ans = 0 for k, Ak in enumerate(A): #Following IJK idiom here fo...
class Solution { /* * dp[i][j] is the max length of fibbonacci series whose last two elements * are A[i] & A[j] * for any integer A[k] we need to find two number A[i] & A[j] such that * i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time * complexity. * if there exist i,j,...
class Solution { public: int help(int i,int j, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp){ if(dp[i][j]!=-1) return dp[i][j]; int x=nums[i]+nums[j]; if(mp.find(x)!=mp.end()) { dp[i][j]=help(j,mp[x],mp,nums,dp); return...
var lenLongestFibSubseq = function(arr) { let ans = 2; const set = new Set(arr); const len = arr.length for(let i = 0; i < len; i++) { for(let j = i + 1; j < len; j++) { let a = arr[i], b = arr[j], len = 2; while(set.has(a + b)) { len++; le...
Length of Longest Fibonacci Subsequence
A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy. Return the final string after the deletion. It can be shown that the answer will always be unique. &nbsp; Example 1: Input: s = "leeetcode" Output: ...
class Solution: def makeFancyString(self, s: str) -> str: if len(s) < 3: return s ans = '' ans += s[0] ans += s[1] for i in range(2,len(s)): if s[i] != ans[-1] or s[i] != ans[-2]: ans += s[i] return ans
class Solution { public String makeFancyString(String s) { char prev = s.charAt (0); int freq = 1; StringBuilder res = new StringBuilder (); res.append (s.charAt (0)); for (int i = 1; i < s.length (); i++) { if (s.charAt (i) == prev) freq++; ...
class Solution { public: string makeFancyString(string s) { int cnt=1; string ans=""; ans.push_back(s[0]); for(int i=1;i<s.length();++i) { cnt=s[i]==s[i-1]? cnt+1:1; if(cnt<3) { ans.push_back(s[i]); } } return ans; ...
var makeFancyString = function(s) { let res = ''; let currCount = 0; for (let i = 0; i < s.length; i++) { if (currCount === 2 && s[i] === s[i - 1]) continue; else if (s[i] === s[i - 1]) { currCount++; res += s[i]; } else { ...
Delete Characters to Make Fancy String
A square matrix is said to be an X-Matrix if both of the following conditions hold: All the elements in the diagonals of the matrix are non-zero. All other elements are 0. Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false. &nbsp;...
class Solution: def checkXMatrix(self, grid: List[List[int]]) -> bool: n = len(grid) for i in range(n): for j in range(n): if i==j or (i+j) ==n-1: if grid[i][j] == 0: return False elif grid[i][j] != 0: ...
class Solution { public boolean checkXMatrix(int[][] grid) { int n = grid.length; for(int i=0; i<n; i++){ for(int j=0; j<n; j++ ){ if ( i == j || i + j == n - 1 ) { if ( grid[i][j] == 0 ) return false; } ...
class Solution { public: bool checkXMatrix(vector<vector<int>>& grid) { int n = grid.size(); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i == j or i == n - j - 1){ if(!grid[i][j]) return false; }el...
var checkXMatrix = function(grid) { for (let i=0; i<grid.length; i++) { for (let j=0; j<grid[i].length; j++) { let leftDiagonal = grid[i].length - 1; if (i === j && grid[i][j] !== 0 || j === leftDiagonal - i && grid[i][j] !== 0) { continue; } i...
Check if Matrix Is X-Matrix
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)....
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): # escape condition if (not root) or (root == p) or (root == q): return root # search left and right subtree ...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { List<TreeNode> path_to_p= new ArrayLis...
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root) { return NULL; } if(root==p or root == q) { return root; } TreeNode *left=lowestCommonAncestor(root->left,p,q); Tr...
var lowestCommonAncestor = function(root, p, q) { if(!root || root.val == p.val || root.val == q.val) return root; let left = lowestCommonAncestor(root.left, p, q); let right = lowestCommonAncestor(root.right, p, q); return (left && right) ? root : left || right; };
Lowest Common Ancestor of a Binary Tree
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring ...
class Solution: def countPoints(self, r: str) -> int: ans = 0 for i in range(10): i = str(i) if 'R'+i in r and 'G'+i in r and 'B'+i in r: ans += 1 return ans
class Solution { public int countPoints(String rings) { Map<Integer,Set<Character>> m=new HashMap<>(); for(int i=0;i<rings.length();i=i+2){ char c=rings.charAt(i); int index=(int)rings.charAt(i+1); if(m.containsKey(index)){ Set<Character> x=m.get(i...
class Solution { public: int countPoints(string rings) { int n=rings.length(); //It is given that number of rod is 10 0 to 9 so we have to place ring any of these vector<int>vp(10,0);//store the no of rings for(int i=0;i<n;i+=2) { char col=rings[i]; v...
/** * @param {string} rings * @return {number} */ var countPoints = function(rings) { let rods = Array(10).fill(""); for(let i = 0; i < rings.length; i += 2){ if(!(rods[rings[i+1]].includes(rings[i]))) rods[rings[i+1]] += rings[i] } return rods.filter(rod => rod.length > 2).length };
Rings and Rods
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with a memory complexity better than O(n2). &nbsp; Example 1: Inp...
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted(list(sum(matrix, [])))[k-1]
/** * Using PriorityQueue * * Time Complexity: * O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually. * If we were adding all elements in one go, then the complexity would be O(min(N,K)) * ...
class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int n = matrix.size(), start = matrix[0][0], end = matrix[n-1][n-1]; unordered_map<int, int>mp; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) mp[matrix[i][j]]++; ...
var kthSmallest = function(matrix, k) { let arr = matrix.flat() arr.sort((a,b)=>a-b) return arr[k-1] };
Kth Smallest Element in a Sorted Matrix
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1,1,0] horizontally results in [0,1,1]. To invert an image means that each 0 is replaced by 1, and eac...
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: return [[(1 - i) for i in row[::-1]] for row in image]
class Solution { public int[][] flipAndInvertImage(int[][] image) { for (int i = 0; i < image.length; ++i) { flip(image[i]); } for (int i = 0; i < image.length; ++i) { for (int j = 0; j < image[i].length; ++j) { image[i][j] = image[i][j] == 1 ? 0:1; ...
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) { int n = image.size(); vector<int >ans; for(int i=0;i<image.size();i++){ ans=image[i]; reverse(ans.begin(),ans.end()); image[i]=ans; } for(int i = ...
var flipAndInvertImage = function(image) { const resversedArr = [] for(let i=0; i<image.length; i++){ resversedArr.push(resverseArr(image[i])); } return resversedArr; }; function resverseArr(arr){ const lastIndex = arr.length -1, reversedArr = []; for(i=0; i<=lastIndex; i++){ if(...
Flipping an Image
Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length. &nbsp; Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You n...
#lets start adding elements to stack. We have to fin the min length [a, b] interval (corresponding to the problem description). # a has to be the first element's index we pop from the array. lets say y is the last element's index we pop. # and max_pop is the maximum element(not index) we pop during stacking.After stack...
class Solution { public int findUnsortedSubarray(int[] nums) { int[] numsClone = nums.clone(); Arrays.sort(nums); int s = Integer.MAX_VALUE; int e = Integer.MIN_VALUE; for(int i = 0; i<nums.length; i++) { if(numsClone[i] != nums[i]) { s = Math.mi...
class Solution { public: int max_value = 1000000; int min_value = -1000000; int findUnsortedSubarray(vector<int>& nums) { // max_list refers to: the max value on the left side of the current element // min_list refers to: the min value on the right side of the current element vector<int> ma...
var findUnsortedSubarray = function(nums) { let left = 0; let right = nums.length - 1; const target = [...nums].sort((a, b) => a - b); while (left < right && nums[left] === target[left]) left += 1; while (right > left && nums[right] === target[right]) right -= 1; const result = right - left; ...
Shortest Unsorted Continuous Subarray
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i &lt; j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are i...
class Solution: def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: ratios = defaultdict(int) for x, y in rectangles: ratios[x/y] += 1 res = 0 for val in ratios.values(): res += (val*(val-1)//2) return res
class Solution { public long interchangeableRectangles(int[][] rectangles) { Map <Double, Long> hash = new HashMap<>(); for (int i = 0; i < rectangles.length; i++) { Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]); hash.put(tmp,...
class Solution { public: long long interchangeableRectangles(vector<vector<int>>& rectangles) { int n = rectangles.size(); unordered_map<double,int> mp; for(int i = 0;i<n;i++){ double ratio = rectangles[i][0]/(double)rectangles[i][1]; mp[ratio]++; } lo...
/** * @param {number[][]} rectangles * @return {number} */ var interchangeableRectangles = function(rectangles) { let map = new Map(); for (let i = 0; i < rectangles.length; i++) { let [a, b] = rectangles[i]; let val = a / b; if (!map.get(val)) map.set(val, [0, 0]); else { ...
Number of Pairs of Interchangeable Rectangles
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. &nbsp; Example 1...
class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: arr = [] hashmap = {char: arr1.count(char) for char in arr1} [arr.extend([char] * hashmap.pop(char)) for char in arr2] return arr + sorted([int(key) * hashmap[key] for key in hashmap]
class Solution { public int[] relativeSortArray(int[] arr1, int[] arr2) { Map <Integer, Integer> map = new TreeMap(); for(int i = 0; i<arr1.length; i++){ if(map.containsKey(arr1[i])){ map.replace(arr1[i], map.get(arr1[i]),map.get(arr1[i])+1); } els...
class Solution { public: vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) { map<int,int>sk; vector<int>res; for(auto i:arr1){ sk[i]++; } for(auto j:arr2){ for(auto z:sk){ if(z.first==j){ int x=z.se...
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number[]} */ var relativeSortArray = function(arr1, arr2) { const indices = new Map(); arr2.forEach(indices.set, indices); return arr1.sort((a, b) => { if (indices.has(a)) { return indices.has(b) ? indices.get(a) - indices.get(b) : -1...
Relative Sort Array
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists&nbsp;two indices i and j such that : i != j 0 &lt;= i, j &lt; arr.length arr[i] == 2 * arr[j] &nbsp; Example 1: Input: arr = [10,2,5,3] Output: true E...
class Solution(object): def checkIfExist(self, arr): """ :type arr: List[int] :rtype: bool """ ''' 执行用时:24 ms, 在所有 Python 提交中击败了59.63%的用户 内存消耗:13 MB, 在所有 Python 提交中击败了58.72%的用户 ''' arr = sorted(arr) # 排序 for i in range(len(arr) ...
class Solution { public boolean checkIfExist(int[] arr) { /* 执行用时:3 ms, 在所有 Java 提交中击败了29.57%的用户 内存消耗:41 MB, 在所有 Java 提交中击败了42.27%的用户 2022年8月3日 14:36 */ int l, mid = 0, r; int val1, val2; Arrays.sort(arr); // 排序 for(int i=0; i < arr...
class Solution { public: bool checkIfExist(vector<int>& arr) { sort(arr.begin(), arr.end()); int i =0; int j = 1; int n = arr.size(); while(i<n && j<n) { if( arr[i]<0 && arr[j]<0 && arr[i]==2*arr[j])return true;...
/** * @param {number[]} arr * @return {boolean} */ var checkIfExist = function(arr) { for(let i=0;i<arr.length;i++){ for(let j=0;j<arr.length;j++){ if ( i!==j && arr[i]==2*arr[j]){ return true; } } } return false; };
Check If N and Its Double Exist
There are n people&nbsp;that are split into some unknown number of groups. Each person is labeled with a&nbsp;unique ID&nbsp;from&nbsp;0&nbsp;to&nbsp;n - 1. You are given an integer array&nbsp;groupSizes, where groupSizes[i]&nbsp;is the size of the group that person&nbsp;i&nbsp;is in. For example, if&nbsp;groupSizes[1...
class Solution(object): def groupThePeople(self, groupSizes): """ :type groupSizes: List[int] :rtype: List[List[int]] """ dict_group={} for i in range(len(groupSizes)): if groupSizes[i] not in dict_group: dict_group[groupSizes[i]]=[i] ...
class Solution { public List<List<Integer>> groupThePeople(int[] groupSizes) { List<List<Integer>> temp = new ArrayList<List<Integer>>(); List<List<Integer>> result = new ArrayList<List<Integer>>(); for(int i = 0; i<groupSizes.length; i++){ int k = groupSizes[i]; boo...
class Solution { public: vector<vector<int>> groupThePeople(vector<int>& groupSizes) { vector<vector<int>>ans; unordered_map<int,vector<int>> store; for(int i=0;i<groupSizes.size();i++){ if(store[groupSizes[i]].size()==groupSizes[i]){ ans.push_back(store[g...
/** * @param {number[]} groupSizes * @return {number[][]} */ var groupThePeople = function(groupSizes) { let indices = [], result = []; groupSizes.forEach((x, idx) => { if (indices[x]) indices[x].push(idx); else indices[x] = [idx]; if (indices[x].length === x) { result.pus...
Group the People Given the Group Size They Belong To
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k &lt;= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserve...
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: m = len(nums1) n = len(nums2) dp = {} # get the max number string with "length" from index "i" in nums1 and index "j" in nums2 # using number string to easy to compare ...
class Solution { public int[] maxNumber(int[] nums1, int[] nums2, int k) { String ans=""; for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq String one = solve(nums1, i); // find the best seq matching len of i ...
class Solution { public: vector<int> maxArray(vector<int>&nums,int k){ int n=nums.size(); stack<int>seen; for(int i=0;i<n;i++){ int right=n-i-1; while(not seen.empty() and seen.top()<nums[i] and right+seen.size()>=k)seen.pop(); if(seen.size()<k)seen.push(n...
const maxNumber = (a, b, k) => { let m = a.length, n = b.length; let res = []; for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) { let maxA = maxArray(a, i), maxB = maxArray(b, k - i); let merge = mergeArray(maxA, maxB); if (merge > res) res = merge; } return res; };...
Create Maximum Number
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. &nbsp; Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Inpu...
class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t)
class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] haha1 = new int[26];//26 because input contains of only lower english letters int[] haha2 = new int[26]; for (int i = 0; i < s.length(); ++i) { haha1[(int)s.c...
class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); if(s != t) return false; return true; } };
var isAnagram = function(s, t) { if(s.length !== t.length) return false let charFreq = {} for(let char of s){ charFreq[char] ? charFreq[char] +=1 : charFreq[char] = 1 } for(let char of t){ if(!(charFreq[char])) return false charFreq[char] -= 1 } return ...
Valid Anagram
Given an integer n, break it into the sum of k positive integers, where k &gt;= 2, and maximize the product of those integers. Return the maximum product you can get. &nbsp; Example 1: Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: n = 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 ...
class Solution: def integerBreak(self, n: int) -> int: dp = [0 for _ in range(n+1)] dp[1] = 1 for i in range(2, n+1): for j in range(1, i//2+1): dp[i] = max(j * (i-j), j * dp[i-j], dp[i]) return dp[-1]
class Solution { public int integerBreak(int n) { //dp array: maximum product of splitling int i int[] dp = new int[n + 1]; // traverse for (int i = 2; i <= n; i++) { for (int j = 1; j <= i / 2; j++) { dp[i] = Math.max(Math.max(j * (i - j), j * d...
class Solution { public: int integerBreak(int n) { if (n == 2) return 1; if (n == 3) return 2; if (n == 4) return 4; int k = n / 3; int m = n % 3; int ans; if (m == 0) ans = pow(3, k); else if (m == 1...
var integerBreak = function(n) { if(n == 2) return 1; if(n == 3) return 2; if(n == 4) return 4; let c = ~~(n/3); let d = n % 3; if(d === 0){ return 3 ** c; } if(d === 1){ return 3 ** (c-1) * 4; } if(d === 2){ ret...
Integer Break
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. Arrow...
class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: points.sort() ans=[points[0]] for i in points[1:]: if(i[0]<=ans[-1][1]): ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])] else: ans.append(i) return ...
class Solution { public int findMinArrowShots(int[][] points) { int minNumArrows = 1; Arrays.sort(points, new Comparator<int[]>(){ @Override public int compare(int[] i1, int[] i2) { if(i1[0] < i2[0]) return -1; ...
class Solution { public: static bool cmp(vector<int>&a,vector<int>&b) { return a[1]<b[1]; } int findMinArrowShots(vector<vector<int>>& points) { sort(points.begin(),points.end(),cmp); //burst the first ballon at least int arrow=1; int end=points[0][1]; for...
var findMinArrowShots = function(points) { points.sort((a, b) => a[0] - b[0]) let merged = [points[0]]; let earliestEnd = points[0][1]; for (let i = 1; i < points.length; i++) { let lastEnd = merged[merged.length - 1][1]; let currStart = points[i][0]; let currEnd = points[i][1...
Minimum Number of Arrows to Burst Balloons
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. int add(int val) Appends the in...
class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.hp = [] for x in nums: self.add(x) return None def add(self, val: int) -> int: heapq.heappush(self.hp, (val)) if len(self.hp) > self.k: heapq.heappop(self.hp) ...
class KthLargest { PriorityQueue<Integer> queue=new PriorityQueue(); int k=0; public KthLargest(int k, int[] nums) { this.k=k; for(int i:nums) add(i); } public int add(int val) { if(k>queue.size()) queue.add(val); else if(val>q...
class KthLargest { int k; priority_queue<int, vector<int>, greater<int>> minheap; int n; public: KthLargest(int k, vector<int>& nums) { this->k=k; this->n=nums.size(); // push the initial elements in the heap for(auto x : nums){ minheap.push...
var KthLargest = function(k, nums) { // sort ascending because I am familiar with it // when applying my binary search algorithm this.nums = nums.sort((a,b) => a - b); this.k = k; }; KthLargest.prototype.add = function(val) { // search a place to push val // using binary search let ...
Kth Largest Element in a Stream
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. &nbsp; Example 1: Input: nums = [1,2,2,3,1] Output: 2...
class Solution: def findShortestSubArray(self, nums): # Group indexes by element type d = defaultdict(list) for i,x in enumerate(nums): d[x].append(i) # # Find highest Degree m = max([ len(v) for v in d.values() ]) # # Find shortest span fo...
class Solution { public int findShortestSubArray(int[] nums) { int ans = Integer.MAX_VALUE; Map<Integer, Integer> count = new HashMap<>(); Map<Integer, Integer> startIndex = new HashMap<>(); Map<Integer, Integer> endIndex = new HashMap<>(); for (int i = 0; i < nums.length; i+...
class Solution { public: int findShortestSubArray(vector<int>& nums) { unordered_map<int,int> cnt,first; int deg=0,ans=0; for(int i=0;i<nums.size();i++) { if(cnt[nums[i]]==0) first[nums[i]]=i; cnt[nums[i]]++; if(cnt[nums[i]]>deg...
/** * 1. compute all positions for each number * 2. filter arrays of max length * 3. select minimum difference between its first and last elems */ var findShortestSubArray = function(nums) { const numPositions = {}; for (let i=0; i<nums.length; i++) { const num = nums[i]; if (numPositions[nu...
Degree of an Array
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val. Return the minimum cost to make...
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: cost = 0 heap = [] #set to store past points to prevent cycle visited = set([0]) #i == the index of current point i = 0 while len(visited) < len(points): #Add all c...
class Solution { public int minCostConnectPoints(int[][] points) { int n = points.length; PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[0]-b[0]); for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { pq.add(new int[]{calDis(points,i,j),i,j}); } } int c = 0, ans = 0; UnionFind uf ...
class Solution { public: int minCostConnectPoints(vector<vector<int>>& points) { ios_base::sync_with_stdio(false); cin.tie(NULL); int n = points.size(); priority_queue<vector<int>> q; unordered_set<int> vis; int ans = 0; q.push({0,0,0}); vector<int> c...
/** * @param {number[][]} points * @return {number} */ //By Kruskal Approach let union_find,mapping_arr,count,maxCost,rank const find=(root)=>{ if(union_find[root]===root)return root; return union_find[root]= find(union_find[root]); } const union=([src,dst,d])=>{ let rootX=find(src); let rootY=find(d...
Min Cost to Connect All Points
You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item...
class Solution: def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: items.sort() dic = dict() res = [] gmax = 0 for p,b in items: gmax = max(b,gmax) dic[p] = gmax keys = sorted(dic.keys()) for q in querie...
class Solution { public int[] maximumBeauty(int[][] items, int[] queries) { int[] ans = new int[queries.length]; Arrays.sort(items, (a, b) -> (a[0] - b[0])); int maxBeautySoFar = Integer.MIN_VALUE; int[] maxBeauty = new int[items.length]; for(int i = 0; i < items.len...
class Solution { public: vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) { vector<vector<int>> v; int n = queries.size(); for(int i = 0; i < n; i++){ v.push_back({queries[i],i}); } sort(v.begin(),v.end()); sort(items.begin(),item...
var maximumBeauty = function(items, queries) { items.sort((a,b) => a[0]-b[0]); const n = items.length; let mx = items[0][1]; for (let i = 0; i<n; i++) { mx = Math.max(mx, items[i][1]); items[i][1] = mx; } const ans = []; for (const q of queries) ...
Most Beautiful Item for Each Query
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. Note that the root node is at depth 1. The adding rule is: Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left ...
#!/usr/bin/python # -*- coding: utf-8 -*- # 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 Solve( self, root, val, dep...
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * ...
#!/usr/bin/python # -*- coding: utf-8 -*- # 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 Solve( self, root, val, dep...
/** * 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 * @param {number} val * @param {number} dep...
Add One Row to Tree
You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj &gt;= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval ex...
class Solution: def findRightInterval(self, A: List[List[int]]) -> List[int]: n = len(A) ans = [-1] * n for i in range(n): A[i].append(i) A.sort() heap = [] for i in range(n): if A[i][0] == A[i][1]: ans[A[i][2]] = A[i][2] ...
/* - Time: O(N*log(N)) Loop through the array with n elements and run binary search with log(N) time for each of them. - Space: O(N) Used a hashmap map of size N to store the original indeces of intervals */ class Solution { public int[] findRightInterval(int[][] intervals) { int n = intervals.length; ...
class Solution { public: vector<int> findRightInterval(vector<vector<int>>& intervals) { map<int, int> mp; int n = intervals.size(); for(int i = 0; i < n; i++) mp[intervals[i][0]] = i; vector<int> ans; for(auto &i : intervals) { auto it = mp...
var findRightInterval = function(intervals) { const data = intervals .map((interval, i) => ({ interval, i })) .sort((a, b) => a.interval[0] - b.interval[0]); const res = Array(intervals.length).fill(-1); for (let pos = 0; pos < data.length; pos++) { let left = pos; let righ...
Find Right Interval
You have n&nbsp;&nbsp;tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles. &nbsp; Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", ...
class Solution: def numTilePossibilities(self, tiles: str) -> int: n= len(tiles) tiles=list(tiles) s1=set() for i in range(1,n+1): s1.update(permutations(tiles,i)) return len(s1)
class Solution { private int result=0; public int numTilePossibilities(String tiles) { Map<Character,Integer> map = new HashMap<>(); for(char c:tiles.toCharArray()){ map.put(c,map.getOrDefault(c,0)+1); } find(map); return result-1; } public void find(M...
class Solution { public: void recur(vector<string> &ans, string tiles, int index, int &res) { res++; for(int i=index; i<tiles.size(); i++) { if(i != index && tiles[i] == tiles[index]) continue; swap(tiles[i], tiles[index]); recur(ans, ...
//""This solution isn`t the best way but it`s simple"" var numTilePossibilities = function(tiles) { return search(tiles); }; // this function takes a state and check if it`s valid or ! // valid state is not null state and unique // e.g ["","A","A"]=>is not valid state because is has null state and repeated // valu...
Letter Tile Possibilities
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Every week, you will finish exactly one milestone of one project. You&nbsp;must&nbsp;work ev...
class Solution: def numberOfWeeks(self, m: List[int]) -> int: return min(sum(m), 2 * (sum(m) - max(m)) + 1)
class Solution { public long numberOfWeeks(int[] milestones) { int i,j,max=-1,n=milestones.length; long sum=0; for(i=0;i<n;i++) { max=Math.max(max, milestones[i]); sum+=milestones[i]; } long x=sum-max; if(max-x>1) return sum-(max-x-1); ...
class Solution { public: long long numberOfWeeks(vector<int>& milestones) { long long unsigned int maxel = *max_element(milestones.begin(), milestones.end()); long long unsigned int sum = 0; for (auto& m : milestones) sum += m; if (sum - maxel >= maxel) return sum; return (su...
var numberOfWeeks = function(milestones) { let maxElement = 0,arraySum = 0; for(let milestone of milestones){ arraySum += milestone; maxElement = Math.max(maxElement,milestone); } let rest = arraySum - maxElement; let difference = maxElement - rest; if(difference <= 1) return ...
Maximum Number of Weeks for Which You Can Work
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. &nbsp; Example 1: Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 ...
class Solution: def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: res = 0 def dfs(node): nonlocal res if not node: return if node.val >= low and node.val <= high: ...
class Solution { private int sum = 0; public int rangeSumBST(TreeNode root, int low, int high) { dfs(root, low, high); return sum; } public void dfs(TreeNode root, int low, int high){ if(root == null) return; if(root.val < low) dfs(root.right, low, high); ...
class Solution { public: int solve(TreeNode* root, int low, int high){ if(root == NULL) return 0; int sum = 0; if(low <= root->val && root->val <= high){ sum = root->val; } return sum + solve(root->left, low, high) + solve(root->right, low, high); ...
var rangeSumBST = function(root, low, high) { let sum = 0; const summer = (root) => { if(!root) { return; } sum = root.val >= low && root.val <= high ? root.val + sum : sum; summer(root.left) summer(root.right) } summer(root); return sum; };
Range Sum of BST
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the res...
class Solution(object): def plusOne(self, digits): for i in range(len(digits)-1, -1, -1): if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 return digits return [1] + digits
class Solution { public int[] plusOne(int[] digits) { int len = digits.length; //last digit not a 9, just add 1 to it if(digits[len - 1] != 9){ digits[len - 1] = digits[len - 1] + 1; return digits; } //last digit is a 9, find the closest digit that ...
class Solution { public: vector<int> plusOne(vector<int>& digits) { int len = digits.size(), carry = 0, temp = 0; vector<int> arr; for(int i=len-1; i>=0; i--) { // traverse from back to front temp = digits[i] + carry; if(i == len-1) { ...
var plusOne = function(digits) { for(let i=digits.length-1; i>=0; i--){ if(digits[i] === 9){ digits[i] = 0 }else{ digits[i] += 1 return digits } } digits.unshift(1) return digits };
Plus One
Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for: i - k &lt;= r &lt;= i + k, j - k &lt;= c &lt;= j + k, and (r, c) is a valid position in the matrix. &nbsp; Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,...
class Solution: def matrixBlockSum(self, matrix: List[List[int]], k: int) -> List[List[int]]: ROWS, COLS = len(matrix), len(matrix[0]) prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)] for r in range(1, ROWS + 1): for c in range(1, COLS + 1): prefix_sums...
class Solution { public int[][] matrixBlockSum(int[][] mat, int k) { int m = mat.length,n = mat[0].length; int[][] answer = new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ int val = 0; // take new variables to get starting index of mat[r...
class Solution { public: vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) { int n = mat.size(), m = mat[0].size(); vector<vector<int>> pref(n+1, vector<int>(m+1, 0)); // Calculating prefix sum for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ ...
/** * @param {number[][]} mat * @param {number} k * @return {number[][]} */ var matrixBlockSum = function(mat, k) { let sum = 0; let dp = Array(mat.length + 1); dp[0] = Array(mat[0].length).fill(0); // sum of row el for (let i = 0; i < mat.length; i++){ dp[i + 1] = Array(mat[0].length)....
Matrix Block Sum
You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to buil...
class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: @cache def dfs(i, sum_): if i == len(nums): if sum_ == target: return 1 else: return 0 return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i]) if abs(targe...
class Solution { public int findTargetSumWays(int[] nums, int target) { int sum = 0; for(int i:nums){ sum += i; } if(target>sum || target<-sum || ((target+sum)&1)!=0) return 0; return subsetSum(nums,(target+sum)/2); } private int subsetSum(int[] nums,int t...
class Solution { // YAA public: int solve(vector<int>& nums, int target, int idx, unordered_map<string, int> &dp) { if(idx == nums.size()) { if(target == 0) { return 1; } return 0; } string key = to_string(idx) + " " + to_string(target...
var findTargetSumWays = function(nums, target) { const memo = new Map() return backtrack(0, 0) function backtrack(i, cur){ const key = `${i} ${cur}` if(i == nums.length) return cur == target ? 1 : 0 if(!memo.has(key)) memo.set(key, backtrack(i + 1, -nums[i] + cur) + backtrack(i ...
Target Sum
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree. The value of each non-leaf node is equal to the product of the largest leaf value in its left and right s...
class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: n = len(arr) d = {} def findMax(start,end): if (start,end) in d: return d[(start,end)] maxx = start for i in range(start+1,end+1): if arr[maxx] < arr[i] : maxx = i ...
class Solution { public int mctFromLeafValues(int[] arr) { int sum = 0; Stack<Integer> stack = new Stack<>(); for (int num: arr) { sum += cleanUpStack(num, stack); } sum += cleanUpStack(17, stack); return sum; } private int c...
class Solution { public: int dp[40][40]={0}; int solve(vector<int> arr,int start,int end) { if(start==end) return 0; if(dp[start][end]!=0) return dp[start][end]; int mn=INT_MAX; for(int i=start;i<=end-1;i++) { int left=solve(arr,sta...
var mctFromLeafValues = function(arr) { const dp = []; for (let i = 0; i < arr.length; i++) { dp[i] = []; } return treeBuilder(0, arr.length - 1); function treeBuilder(start, end) { if (start == end) { return 0; } if (dp[start][end]) { return dp[start][end]; } let min...
Minimum Cost Tree From Leaf Values
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3. Note...
class Solution: def checkZeroOnes(self, s: str) -> bool: s1 = s.split('0') s0 = s.split('1') r1 = max([len(i) for i in s1]) r0 = max([len(i) for i in s0]) return r1>r0
class Solution { public boolean checkZeroOnes(String s) { int length1 = 0; int length0 = 0; int i = 0; while(i < s.length()){ int temp = 0; while(i < s.length() && s.charAt(i) == '1'){ //counting 1s temp++; i++; } ...
class Solution { public: bool checkZeroOnes(string s) { int count1=0; int count2=0; int max1=0;int max2=0; for(int i=0;i<s.size();i++) { if(s[i]=='1') { count1++; if(s[i+1]!=s[i]) { max...
var checkZeroOnes = function(s) { let longest1 = 0; let longest0 = 0; let count1 = 0; let count0 = 0; for (let i = 0; i < s.length; i++) { const bit = s.charAt(i); if (bit === "1") count1++; else count1 = 0; if (bit === "0") count0++; else count0 = 0; ...
Longer Contiguous Segments of Ones than Zeros
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day). For example, the period [10, 10000] (in seconds) would be parti...
import bisect class TweetCounts: def __init__(self): self.tweets = {} def recordTweet(self, tweetName: str, time: int) -> None: if not tweetName in self.tweets: self.tweets[tweetName] = [] index = bisect.bisect_left(self.tweets[tweetName], time) self.tweets...
class TweetCounts { Map<String, List<Integer>> map; public TweetCounts() { map = new HashMap<>(); } public void recordTweet(String tweetName, int time) { map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time); } public List<Integer> getTweetCountsPerFrequency(String fre...
#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; //less_equal to use it as a multiset typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; class TweetCounts { public: unordered_map<string,...
var TweetCounts = function() { this.map = new Map(); }; TweetCounts.prototype.recordTweet = function(tweetName, time) { if (!this.map.has(tweetName)) this.map.set(tweetName, []); this.map.get(tweetName).push(time); }; TweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, ...
Tweet Counts Per Frequency