algo_input
stringlengths
240
3.91k
solution_py
stringlengths
10
6.72k
solution_java
stringlengths
87
8.97k
solution_c
stringlengths
10
7.38k
solution_js
stringlengths
10
4.56k
title
stringlengths
3
77
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.   Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2   Co...
class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ result = 0 depths = [] self.handler(root, result, depths) return max(depths) def handler(self, root, result, depths): if root: result +=...
class Solution { public int maxDepth(TreeNode root) { // Base Condition if(root == null) return 0; // Hypothesis int left = maxDepth(root.left); int right = maxDepth(root.right); // Induction return Math.max(left, right) + 1; } }
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return max(left, right) + 1; } };
var maxDepth = function(root) { if(root == null) return 0 let leftDepth = maxDepth(root.left) let rightDepth = maxDepth(root.right) let ans = Math.max(leftDepth,rightDepth) + 1 return ans };
Maximum Depth of Binary Tree
Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.   Example 1: Input: nums = [2,3,4,6] Output: 8 Explanation: There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) ...
class Solution: def tupleSameProduct(self, nums: List[int]) -> int: from itertools import combinations mydict=defaultdict(int) ans=0 for a,b in combinations(nums,2): mydict[a*b]+=1 for i,j in mydict.items(): if j>1: ans+=(j*(j-1)//2)...
class Solution { public int tupleSameProduct(int[] nums) { if(nums.length < 4){ return 0; } int res = 0; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length - 1; i++){ for(int...
class Solution { public: int tupleSameProduct(vector<int>& nums) { int n = nums.size(); unordered_map<int,int> map; int res = 0; for(int i = 0 ; i < n ; i++){ for(int j = i+1 ; j < n ; j++){ int prod = nums[i] * nums[j]; map[prod]++;//store...
var tupleSameProduct = function(nums) { let tupleCount = 0; let products = {}; // we'll keep track of how many times we've seen a given product before for (let a = 0; a < nums.length; a++) { for (let b = a + 1; b < nums.length; b++) { let product = nums[a] * nums[b]; if (prod...
Tuple with Same Product
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] ...
import heapq class Solution(object): def eatenApples(self, apples, days): """ :type apples: List[int] :type days: List[int] :rtype: int """ heap = [(days[0], apples[0])] heapq.heapify(heap) day = 0 rtn = 0 while heap or day < len(days):...
class Solution { public int eatenApples(int[] apples, int[] days) { PriorityQueue<Apple> minHeap = new PriorityQueue<Apple>((a, b) -> (a.validDay - b.validDay)); //start from day 1 int currentDay = 1; int eatenAppleCount = 0; for(int i = 0; i < apples.length...
class Solution { public: int eatenApples(vector<int>& apples, vector<int>& days) { ios_base::sync_with_stdio(0);cin.tie(0); priority_queue<int,vector<int>,greater<int>>p; unordered_map<int,int>m; int ans=0; int i=0; while(p.size() || i<days.size()){ if(i<d...
var eatenApples = function(apples, days) { const heap = new MinPriorityQueue({priority: x => x[0]}); let totalApple = 0; for(let i = 0; i < apples.length; i++) { heap.enqueue([i + days[i], apples[i]]); while(!heap.isEmpty()) { const [expire, count] = heap.front().el...
Maximum Number of Eaten Apples
You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards...
class Solution: def minimumCardPickup(self, cards: List[int]) -> int: d={} x=[] for i in range(len(cards)): if cards[i] not in d: d[cards[i]]=i else: x.append(i-d[cards[i]]) d[cards[i]]=i if len(x)<=0: ...
class Solution { public int minimumCardPickup(int[] cards) { Map<Integer,Integer> map = new HashMap<>(); int min = Integer.MAX_VALUE; for(int i = 0; i < cards.length; i++) { if(map.containsKey(cards[i])) min = Math.min(i-map.get(cards[i])+1,min); // Ch...
class Solution { public: int minimumCardPickup(vector<int>& cards) { int res (INT_MAX), n(size(cards)); unordered_map<int, int> m; for (auto i=0; i<n; i++) { // number of consecutive cards you have to pick up to have a pair of matching cards == (Diference between 2 indexes of sa...
var minimumCardPickup = function(cards) { let cardsSeen = {}; let minPicks = Infinity; for (let i = 0; i < cards.length; i++) { if (!(cards[i] in cardsSeen)) { cardsSeen[cards[i]] = i; } else { const temp = i - cardsSeen[cards[i]] + 1; minPicks = Math.min(...
Minimum Consecutive Cards to Pick Up
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integ...
class Solution(object): def triangularSum(self, nums): while len(nums) > 1: arr = [] for i in range(len(nums)-1): arr.append((nums[i] + nums[i+1]) % 10) nums = arr return nums[0]
class Solution { public int triangularSum(int[] nums) { return find(nums,nums.length); } public int find(int[] a, int n){ if(n == 1) return a[0]; for(int i=0;i<n-1;i++){ a[i] = (a[i] + a[i+1])%10; } return find(a,n-1); } ...
class Solution { public: int triangularSum(vector<int>& nums) { int n=nums.size(); for(int i=n-1;i>=1;i--){ for(int j=0;j<i;j++){ nums[j]=(nums[j]+nums[j+1])%10; } } return nums[0]; } };
var triangularSum = function(nums) { while(nums.length > 1){ let arr = [] for(let i=0; i<nums.length-1; i++){ arr.push((nums[i] + nums[i+1]) % 10) } nums = arr } return nums[0] };
Find Triangular Sum of an Array
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. &nbsp; Example 1: Input: root = ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def dfs(self, node, path): if not node: return if not node.left and not...
class Solution { public int pseudoPalindromicPaths (TreeNode root) { return helper(root, 0); } public int helper(TreeNode node, int freq) { if (node == null) return 0; freq = freq ^ (1 << node.val); if (node.left == null && node.right == null) { retu...
class Solution { private: void dfs(TreeNode* root,int &ans,unordered_map<int,int> &m){ if(!root) return; m[root -> val]++; if(!root -> left and !root -> right){ int oddCnt = 0; for(auto it : m){ if(it.second % 2 != 0) oddCnt++; } if(oddCnt <= 1) ans++; } dfs(root -> left,ans,m); dfs(roo...
var pseudoPalindromicPaths = function(root) { if(!root) return 0; // if even it's zero or it's power of two when odd const ways = (r = root, d = 0) => { if(!r) return 0; d = d ^ (1 << r.val); // leaf if(r.left == r.right && r.left == null) { const hasAllEven = d ...
Pseudo-Palindromic Paths in a Binary Tree
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. &nbsp; Example 1: Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4 Example 2: Input: matrix = [["0","1"],["1","0"]] Output: 1 E...
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[-1]) dp = [[0] * n for _ in range(m)] max_area = 0 for i in range(m): for j in range(n): if i - 1 < 0 or j - 1 < 0: if matr...
class Solution { public int maximalSquare(char[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[][] dp = new int[m][n]; int max = 0; for (int i = 0; i < m; i++) { dp[i][0] = matrix[i][0] - 48; if (matrix[i][0] == '1') max = 1; ...
class Solution { public: int dp[305][305]; int ans; int getMax(vector<vector<char>>& mat, int i, int j){ int n=mat.size(), m=mat[0].size(); if(i>=n || j>=m) return 0; if(dp[i][j] != -1) return dp[i][j]; // getting min of the perfect squares formed by left adjacen...
var maximalSquare = function(matrix) { let max = 0; const height = matrix.length-1; const width = matrix[0].length-1; for (let i=height; i>=0; i--) { for (let j=width; j>=0; j--) { const right = j < width ? Number(matrix[i][j+1]) : 0; const diag = i < height && j < width ...
Maximal Square
A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '. A token is a valid word if all three of the following are true: It on...
import re class Solution: def countValidWords(self, sentence: str) -> int: # parse and get each word from sentence words = sentence.split() # regular expression pattern for valid words pattern = re.compile( r'^([a-z]+\-?[a-z]+[!\.,]?)$|^([a-z]*[!\.,]?)$' ) ...
class Solution { public int countValidWords(String sentence) { String regex = "^([a-z]+(-?[a-z]+)?)?(!|\\.|,)?$"; String r2 = "[^0-9]+"; String[] arr = sentence.split("\\s+"); int ans = 0; for(String s: arr) { if(s.matches(regex) && s.matches(r2)) ...
#include <regex> class Solution { public: int countValidWords(string sentence) { int count = 0; // Defining the regex pattern regex valid_word("[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?"); // splitting the sentence to words stringstream s(sentence); string word; wh...
/** * @param {string} sentence * @return {number} */ var countValidWords = function(sentence) { let list = sentence.split(' ') let filtered = list.filter(s => { if (/\d/.test(s) || s === '') return false //removes anything with numbers or is blank if (/^[!,.]$/.test(s)) return true ...
Number of Valid Words in a Sentence
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) &lt;= k. &nbsp; Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2...
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for i, n in enumerate(nums): if n in seen and i - seen[n] <= k: return True seen[n] = i return False
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) { return true; } ...
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> m; for(int i=0;i<nums.size();i++){ if(m.count(nums[i]) && i-m[nums[i]]<=k) return true; m[nums[i]]=i; } return false; } };
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function(nums, k) { const duplicateCheck = {}; let isValid = false; for(var indexI=0; indexI<nums.length;indexI++){ if(duplicateCheck[nums[indexI]] > -1) { if(Math.abs(duplicateChec...
Contains Duplicate II
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1. &nbsp; Example 1: Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements)...
class Solution: def minMoves(self, nums: List[int]) -> int: return sum(nums)-min(nums)*len(nums)
class Solution { public int minMoves(int[] nums) { int min=Integer.MAX_VALUE; int count=0; for(int i:nums) min=Math.min(i,min); for(int i=0;i<nums.length;i++) { count+=nums[i]-min; } return count; } }
class Solution { public: int minMoves(vector<int>& nums) { // sorting the array to get min at the first sort(nums.begin(), nums.end()); int cnt = 0, n = nums.size(); // Now we have to make min equal to every number and keep adding the count for(int i = 1; i < n; i++) ...
var minMoves = function(nums) { let minElm = Math.min(...nums); let ans = 0; for(let i=0; i<nums.length; i++){ ans += (nums[i]-minElm) } return ans };
Minimum Moves to Equal Array Elements
A password is said to be strong if it satisfies all the following criteria: It has at least 8 characters. It contains at least one lowercase letter. It contains at least one uppercase letter. It contains at least one digit. It contains at least one special character. The special characters are the characters in ...
class Solution: def strongPasswordCheckerII(self, pwd: str) -> bool: return ( len(pwd) > 7 and max(len(list(p[1])) for p in groupby(pwd)) == 1 and reduce( lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0 ...
class Solution { public boolean strongPasswordCheckerII(String password) { HashSet<Integer> intAscii = new HashSet<>(); String specialCharacters = "!@#$%^&*()-+"; for (int i = 0; i < specialCharacters.length(); i++) { int ascii = specialCharacters.charAt(i); intAsc...
class Solution { public: bool strongPasswordCheckerII(string password) { if(password.size() < 8) //8 char length return false; bool lower = 0, upper = 0; bool digit = 0, special = 0; for(int i=0; i<password.size(); i++){ //check rest conditions if(i>0 && pass...
const checkLen = (password) => password.length >= 8; const checkSmallLetter = (password) => { for(let i=0;i<password.length;i++){ const ind = password.charCodeAt(i); if(ind > 96 && ind < 123){ return true; } } return false; } const checkCapitalLetter = (password) => { ...
Strong Password Checker II
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest ...
class Solution: def largestComponentSize(self, nums: List[int]) -> int: def find(node): if parent[node] == -1: return node else: parent[node] = find(parent[node]) return parent[node] def union(idx1,idx2): par1,par2...
class Solution { public int largestComponentSize(int[] nums) { int maxNum = getMaxNum(nums); Map<Integer, Integer> numToFirstPrimeFactor = new HashMap<>(); DisjointSet ds = new DisjointSet(maxNum + 1); for (int num : nums) { if (num == 1) { continue; ...
class Solution { private: vector<bool> sieve(int n) { vector<bool> prime(n + 1); for (int i = 0; i <= n; i++) prime[i] = 1; for (int p = 2; p * p <= n; p++) { if (prime[p] == 1) { for (int i = p * p; i <= n; i += p) prime[i] = 0; ...
var largestComponentSize = function(nums) { const rootByFactor = new Map(); const parents = new Array(nums.length); function addFactor(i, factor) { if (rootByFactor.has(factor)) { let r = rootByFactor.get(factor); while (parents[i] != i) i = parents[i]; while (parents[r] != r) r = parents[r...
Largest Component Size by Common Factor
A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "". Note that the strings are considered in the order in which they appear in the arra...
class Solution: def kthDistinct(self, arr: List[str], k: int) -> str: hash_map = {} for string in arr: hash_map[string] = hash_map.get(string, 0) + 1 for string in arr: if hash_map[string] == 1: k -= 1 if k == 0: ret...
class Solution { public String kthDistinct(String[] arr, int k) { Map<String,Integer> map=new HashMap<>(); for(String s:arr){ if(map.containsKey(s)) map.put(s,map.get(s)+1); else map.put(s,1); } int i=0; for(String s:arr){ ...
class Solution { public: string kthDistinct(vector<string>& arr, int k) { unordered_map<string,int>m; for(int i=0;i<arr.size();i++) { m[arr[i]]++; } for(int i=0;i<arr.size();i++) { if(m[arr[i]]==1) { k--; ...
var kthDistinct = function(arr, k) { const map = {} // used for arr occurences const distinctArr = [] // store the distinct values (only appearing once) // increment the occurence to the map arr.forEach(letter => map[letter] = map[letter] + 1 || 1) // store all the distinct values in order f...
Kth Distinct String in an Array
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. &nbsp; Example 1: Input: matrix = [ &nbsp; [0,1,1,1], &nbsp; [1,1,1,1], &nbsp; [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squ...
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: m = len(matrix) n = len(matrix[0]) dp = [[0 for _ in range(n)] for _ in range(m)] total = 0 for i in range(m): for j in range(n): if i == 0: dp[i][j] = ...
class Solution { public int countSquares(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[][] res = new int[m][n]; for(int j=0; j<n; j++) res[0][j] = matrix[0][j]; for(int i=0; i<m; i++) res[i][0] = matrix[i][0];...
class Solution { public: int solve( vector<vector<int>>&mat , int n , int m , vector<vector<int>>&dp){ if(n<0 or m<0 or mat[n][m] == 0 ) return 0; if(dp[n][m] != -1 ) return dp[n][m]; return dp[n][m] = ( 1 + min({ solve( mat , n-1 , m , dp ), ...
/** * @param {number[][]} matrix * @return {number} */ var countSquares = function(matrix) { let count = 0; for (let i = 0; i < matrix.length; ++i) { for (let j = 0; j < matrix[0].length; ++j) { if (matrix[i][j] === 0) continue; if (i > 0 && j > 0) { matrix[i][j] += Math.min(matrix[i - 1]...
Count Square Submatrices with All Ones
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new strin...
class Solution(object): def countPalindromicSubsequence(self, s): d=defaultdict(list) for i,c in enumerate(s): d[c].append(i) ans=0 for el in d: if len(d[el])<2: continue a=d[el][0] b=d[el][-1] ans+=len(set(s...
class Solution { public int countPalindromicSubsequence(String s) { int n = s.length(); char[] chArr = s.toCharArray(); int[] firstOcc = new int[26]; int[] lastOcc = new int[26]; Arrays.fill(firstOcc, -1); Arrays.fill(lastOcc, -1); ...
class Solution { public: int countPalindromicSubsequence(string s) { vector<pair<int, int> > v(26, {-1, -1} ); //to store first occurance and last occurance of every alphabet. int n = s.length(); //size of the string for (int i = 0 ; i< n ;i++ ){ if (v...
var countPalindromicSubsequence = function(s) { const charToIndices = {}; for (let i = 0; i < s.length; i++) { const char = s[i]; if (charToIndices[char]) { charToIndices[char].push(i); } else { charToIndices[char] = [i]; } } let count = 0; fo...
Unique Length-3 Palindromic Subsequences
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group. For the last group, if the string does ...
class Solution: def divideString(self, s: str, k: int, fill: str) -> List[str]: l, i, N = [], 0, len(s) while i<N: l.append(s[i:i+k]) i += k last = l[-1] if(len(last)<k): l[-1] += fill*(k-len(last)) return l
class Solution { public String[] divideString(String s, int k, char fill) { int rem = 0; if( s.length() % k != 0){ rem = k - s.length() % k; //counting the total positions where we have to fill the char "fill". } for(int i = 0; i < rem; i++){ s = s+fill; //ap...
class Solution { public: vector<string> divideString(string s, int k, char fill) { vector<string> v; for(int i=0;i<s.size();i=i+k) { string t=s.substr(i,k); // make substring of size atmost k if(t.size()==k) // if size if k then push { v.p...
/** * @param {string} s * @param {number} k * @param {character} fill * @return {string[]} */ var divideString = function(s, k, fill) { var ans=[]; for(let i=0;i<s.length;i+=k) { ans.push(s.substring(i,i+k)); } let str=ans[ans.length-1]; if(str.length==k) { return ans; } for(...
Divide a String Into Groups of Size k
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another ta...
import math class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: count_dict = {} total_days = 0 for task in tasks: if task not in count_dict: count_dict[task] = -math.inf total_days = max(total_days + 1, count_dict[task] + sp...
class Solution { public long taskSchedulerII(int[] tasks, int space) { HashMap<Integer, Long> map = new HashMap<>(); long day = 0; for (int item : tasks) { if (map.containsKey(item) && map.get(item) > day) day = map.get(item); day++; map....
class Solution { public: long long taskSchedulerII(vector<int>& tasks, int space) { unordered_map<int,long long int> hash; long long int curday=0; for(int i=0;i<tasks.size();i++){ if(hash.count(tasks[i])) curday=max(curday,hash[tasks[i]]); hash[tasks[i]]=curday+space+1; ...
var taskSchedulerII = function(tasks, n) { const config = {}; let totalIteration = 0; let currentTime = 0; for (const iterator of tasks) { currentTime++; if (!config[iterator]) { config[iterator] = 0; } else { if (config[iterator] > currentTime) { let difference = config[iterator] - currentTime; ...
Task Scheduler II
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you ca...
class Solution: def canBeTypedWords(self, text: str, brokenLetters: str) -> int: text = text.split() length = len(text) brokenLetters = set(brokenLetters) for word in text: for char in word: if char in brokenLetters: length -= 1 ...
class Solution { public int canBeTypedWords(String text, String brokenLetters) { int count = 1; boolean isBad = false; for (char c : text.toCharArray()) { if (c == ' ') { isBad = false; count++; } else { if (!isBad && br...
class Solution { public: int canBeTypedWords(string text, string brokenLetters) { vector<int> ch(26,0); // store the broken letters in ch vector for(char c: brokenLetters){ ch[c-'a']=1; } int cnt=0,ans=0; //traversing the text string for(int i=0;i<text.length(...
var canBeTypedWords = function(text, brokenLetters) { let regexp="["+brokenLetters+"]\+" let word=text.split(" "), count=0; for(let i=0; i<word.length; i++){ let work=true; // if matches, means word[i] contains malfunction letters. if(word[i].match(regexp)){work=false}; if(wo...
Maximum Number of Words You Can Type
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9...
class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ full = set('123456789') # lets keep rows, columns and boxes sets in hashmaps rows = [set() for _ in range(9)] cols = [set() for _ in...
class Solution { public void solveSudoku(char[][] board) { solve(board); } boolean solve(char board[][]){ for(int i = 0; i<board.length; i++){ for(int j = 0; j<board[0].length; j++){ if(board[i][j] == '.') { for(char c = '1'; c<='9'; c++){ ...
class Solution { public: bool issafe(vector<vector<char>> &board,int row,int col,char c) { for(int i=0;i<9;i++) { if(board[row][i]==c) return 0; if(board[i][col]==c) return 0; if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c) ...
var solveSudoku = function(board) { let intBoard = convertBoardToInteger(board); let y = 0, x = 0; while (y <= 8){ x = 0; while (x <= 8){ if (isFreeIndex(board, x, y)){ intBoard[y][x]++; while (!isPossibleValue(intBoard, x, y) && intBoard[y][x] <...
Sudoku Solver
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the origi...
class Solution: def maxConsecutiveAnswers(self, string: str, k: int) -> int: result = 0 j = 0 count1 = k for i in range(len(string)): if count1 == 0 and string[i] == "F": while string[j] != "F": j+=1 count1+=1 ...
class Solution { // Binary Search + Sliding Window fixed public int maxConsecutiveAnswers(String answerKey, int k) { int start = 1 ; int end = answerKey.length(); int max_length = 0 ; while(start <= end) { int mid = start+(end-start)/2 ; if(isMax(answe...
class Solution { public: int maxConsecutiveAnswers(string answerKey, int k) { return max(helper(answerKey,k,'T'),helper(answerKey,k,'F')); } int helper(string answerKey, int k,char c){ int start = 0; int end = 0; int count = 0; int ans = 0; while(end<answerKe...
var maxConsecutiveAnswers = function(answerKey, k) { let [left, right, numOfTrue, numOfFalse, max] = new Array(5).fill(0); const moreChanges = () => numOfTrue > k && numOfFalse > k; while (right < answerKey.length) { if(answerKey[right] === 'T') numOfTrue++; if(answerKey[right] === 'F') numO...
Maximize the Confusion of an Exam
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 &lt;= i &lt; j &lt; n and nums[i] &lt; nums[j]. Return the maximum difference. If no such i and j exists, return -1. &nbsp; Example 1: Input: nums = [7,1,5,4] Output: 4 Expla...
class Solution: def maximumDifference(self, nums: List[int]) -> int: curmin = nums[0] diff = 0 for num in nums: diff = max(diff, num - curmin) curmin = min(curmin, num) return diff or -1
class Solution { public int maximumDifference(int[] nums) { if(nums.length < 2) return -1; int result = Integer.MIN_VALUE; int minValue = nums[0]; for(int i = 1; i < nums.length; i++) { if(nums[i] > minValue) result = Math.max(result, nums[i] -...
class Solution { public: int maximumDifference(vector<int>& nums) { int mn = nums[0], res = 0; for (int i = 1; i < nums.size(); i++) { res = max(res, nums[i] - mn); mn = min(mn, nums[i]); } return res == 0 ? -1 : res; } };
var maximumDifference = function(nums) { var diff=-1 for(let i=0;i<nums.length;i++){ for(let j=i+1;j<nums.length;j++){ if (nums[j]> nums[i]) diff=Math.max(nums[j]-nums[i],diff) } } return diff };
Maximum Difference Between Increasing Elements
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[...
class Solution: def diagonalSort(self, A: List[List[int]]) -> List[List[int]]: n, m, d = len(A), len(A[0]), defaultdict(list) any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m)) any(d[sum_].sort(reverse=1) for sum_ in d) return [[d[i-j].pop() for j in range(m)] for i in...
class Solution { public int[][] diagonalSort(int[][] mat) { int n = mat.length; int m = mat[0].length; for(int i=0;i<m;i++){ give(0,i,mat,n,m); } for(int i=1;i<n;i++){ give(i,0,mat,n,m); } return mat; } public void give(int i,i...
class Solution { public: void sortmat(int i,int j,vector<vector<int>>& mat,int m,int n,vector<int>& temp){ if(i>=m || j>=n){ sort(temp.begin(),temp.end()); return ; } temp.push_back(mat[i][j]); sortmat(i+1,j+1,mat,m,n,temp); mat[i][j]=temp.back(); temp.pop_back(); } vector<vector<int>> diagonalSor...
/** * @param {number[][]} mat * @return {number[][]} */ var diagonalSort = function(mat) { const res=new Array(mat.length); for(let i=0;i<mat.length;i++) res[i]=new Array(mat[i].length); for(let i=0;i<mat.length;i++){ for(let j=0;j<mat[i].length;j++){ if(i===0 || j===0){ const ...
Sort the Matrix Diagonally
A cell (r, c) of an excel sheet is represented as a string "&lt;col&gt;&lt;row&gt;" where: &lt;col&gt; denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. &lt;row&gt; is the row number ...
class Solution: def cellsInRange(self, s: str) -> List[str]: start, end = s.split(':') start_letter, start_num = start[0], int(start[-1]) end_letter, end_num = end[0], int(end[1]) alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') alphabet_slice = \ alphabet[alphabet.i...
class Solution { public List<String> cellsInRange(String s) { char sc = s.charAt(0), ec = s.charAt(3); char sr = s.charAt(1), er = s.charAt(4); List<String> res = new ArrayList<>(); for (char i = sc; i <= ec; ++i){ for (char j = sr; j <= er; ++j){ ...
class Solution { public: vector<string> cellsInRange(string s) { vector<string>ans; for(char ch=s[0];ch<=s[3];ch++) { for(int i=s[1]-'0';i<=s[4]-'0';i++) { string res=""; res+=ch; res+=to_string(i); ans...
const toCharCode = (char) => char.charCodeAt() var cellsInRange = function(s) { const result = [] for(let i = toCharCode(s[0]) ; i <= toCharCode(s[3]) ; i++){ for(let j = s[1] ; j <= s[4] ; j++){ result.push(String.fromCharCode(i) +j) } } return result };
Cells in a Range on an Excel Sheet
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. Return...
class Solution: def candy(self, ratings: List[int]) -> int: n=len(ratings) temp = [1]*n for i in range(1,n): if(ratings[i]>ratings[i-1]): temp[i]=temp[i-1]+1 if(n>1): if(ratings[0]>ratings[1]): temp[0]=2 for i in range...
class Solution { public int candy(int[] ratings) { int[] left = new int[ratings.length]; Arrays.fill(left, 1); // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy for(int i = 0; i<rating...
class Solution { public: int candy(vector<int>& ratings) { ios_base::sync_with_stdio(false); cin.tie(NULL); int ans = 0, i; vector<int> store(ratings.size(), 1); for (i = 0; i < ratings.size()-1; i++) if(ratings[i+1] > ratings[i]) store[i+1] = store[i]+1; for (i = rat...
/** * @param {number[]} ratings * @return {number} */ var candy = function(ratings) { const n = ratings.length; let candies = [...Array(n)].fill(1); let index = 0; let copy = [ratings[0]]; let isDecreasing = true; for(let i = 1; i < n; i++) { if (ratings[i] > ratings[i...
Candy
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x &lt;= y. The result of this smash is: If x == y, both ...
class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones = [-x for x in stones] heapq.heapify(stones) while len(stones) > 1: mx1 = -heapq.heappop(stones) mx2 = -heapq.heappop(stones) if mx1 - mx2: heapq.heappush(stones, ...
class Solution { public int lastStoneWeight(int[] stones) { PriorityQueue<Integer> pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x)); for (int i = 0; i < stones.length; i++) { pq.add(stones[i]); } while (pq.size() > 1) { int r1 = pq.poll(); i...
class Solution { public: int lastStoneWeight(vector<int>& stones) { while(stones.size()>1){ sort(stones.begin(), stones.end(), greater<int>()); stones[1] = (stones[0]-stones[1]); stones.erase(stones.begin()); } return stones[0]; } };
var lastStoneWeight = function(stones) { let first = 0, second = 0; stones.sort((a,b) => a - b); while(stones.length > 1) { first = stones.pop(); second = stones.pop(); stones.push(first - second); stones.sort((a,b) => a - b); } return stones[0]; };
Last Stone Weight
Given n points on a 2D plane where points[i] = [xi, yi], Return&nbsp;the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. ...
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: # only taking x-axis point as it's relevant arr = [i[0] for i in points] arr.sort() diff = -1 for i in range(1, len(arr)): diff = max(diff, arr[i] - arr[i - 1]) ...
class Solution { public int maxWidthOfVerticalArea(int[][] points) { int L = points.length; // y-coordinate of a point does not matter in width int arr[] = new int[L]; for(int i=0;i<L;i++){ arr[i]=points[i][0]; } Arrays.sort(arr); int diff = Integ...
class Solution { public: int maxWidthOfVerticalArea(vector<vector<int>>& points) { sort(begin(points),end(points)); int n=points.size(); int m=0; for(int i=0;i<n-1;i++) m=max(points[i+1][0]-points[i][0],m); return m; } };
var maxWidthOfVerticalArea = function(points) { let ans = 0; points = points.map(item => item[0]).sort((a, b) => a - b); for(let i = 1; i < points.length; i++){ ans = Math.max(ans, points[i] - points[i-1]); } return ans; };
Widest Vertical Area Between Two Points Containing No Points
Given an array arr,&nbsp;replace every element in that array with the greatest element among the elements to its&nbsp;right, and replace the last element with -1. After doing so, return the array. &nbsp; Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Explanation: - index 0 --&gt; the greatest eleme...
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: maxright = arr[-1] for i in range(len(arr) -1,-1,-1): temp = arr[i] arr[i] = maxright if temp > maxright: maxright = temp arr[-1] = -1 return arr
class Solution { public int[] replaceElements(int[] arr) { int greatElement = -1; for(int i = arr.length-1; i >= 0; i--) { int temp = arr[i]; arr[i] = greatElement; greatElement = Math.max(temp, greatElement); } return arr; } }
class Solution { public: vector<int> replaceElements(vector<int>& arr) { int n=arr.size(); //taking last index as greatest for now int g=arr[n-1]; //setting last index as -1 arr[n-1]=-1; for(int i=n-2;i>=0;i--) { //storing last index value to be chang...
* @param {number[]} arr * @return {number[]} */ var replaceElements = function(arr) { let max = arr[arr.length -1] for(let j=arr.length - 2; j>=0; --j){ let curr = arr[j]; arr[j] = max max = Math.max(max,curr) } arr[arr.length -1] = -1; return arr; };
Replace Elements with Greatest Element on Right Side
You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i]. The following are the types of poker hands you can make from best to worst: "Flush": Five cards of the same suit. "Three of a Kind": Three cards of the same rank. "P...
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: s={} for i in suits: if i in s: s[i]+=1 if s[i]==5: return 'Flush' else: s[i]=1 r={} max_ = 0 for i in ra...
class Solution { public String bestHand(int[] ranks, char[] suits) { int max = 0; int card = 0; char ch = suits[0]; int[] arr = new int[14]; for(int i = 0; i < 5; i++){ arr[ranks[i]]++; max = Math.max(max,arr[ranks[i]]); if(suits[i] == ch) card++; } if(card ==...
class Solution { public: string bestHand(vector<int>& ranks, vector<char>& suits) { map<int, int> m1; int mn = INT_MIN; int all_same = count(begin(suits), end(suits), suits[0]); int n = ranks.size(); for (int i = 0; i < n; i++) { m1[ranks[i]]++; mn = m...
var bestHand = function(ranks, suits) { let suitsMap = {} for (let i=0; i<suits.length; i++) { if (suitsMap[suits[i]]) { suitsMap[suits[i]]++; } else { suitsMap[suits[i]] = 1; } } if (Object.keys(suitsMap).length === 1) return "Flush"; let pair = false...
Best Poker Hand
Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. &nbsp; Example 1: Input: root = [1,2,3,4,5,nul...
""" # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def findRightMost(self, root, level, requiredLevel): if not root:...
class Solution { public Node connect(Node root) { if (root == null) { return root; } Node head = null; //the start node of next level, the first left of next level Node prev = null; //the next pointer Node curr = root; while (curr != null) { /...
// method-1 class Solution { public: Node* connect(Node* root) { if(!root) return NULL; queue<Node*> q; q.push(root); root->next=NULL; while(!q.empty()){ int size=q.size(); Node* prev=NULL; for(int i=0;i<size;i++){ ...
var connect = function(root) { let curr = root; while (curr != null) { let start = null; // (1) let prev = null; while (curr != null) { // (2) if (start == null) { // (3) if (curr.left) start = curr.left; else if (curr.right) start = ...
Populating Next Right Pointers in Each Node II
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. Ther...
class Solution(object): def numberOfBeams(self, bank): ans, pre = 0, 0 for s in bank: n = s.count('1') if n == 0: continue ans += pre * n pre = n return ans
class Solution { public int numberOfBeams(String[] bank) { int ans = 0, pre = 0; for (int i = 0;i < bank.length; i ++) { int n = 0; for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++; if (n == 0) continue; ans += pre * n;; ...
class Solution { public: int numberOfBeams(vector<string>& bank) { int rowLaserCount=0,totalLaserCount=0,prevCount=0; for(int i=0;i<bank.size();i++) { rowLaserCount=0; for(char j:bank[i]) { if(j=='1') rowLaserCount++; }total...
var numberOfBeams = function(bank) { let totalBeams = 0; const maximumSecurityDevicePerRow = bank.map(row => (row.match(/1/g) || []).length).filter(Boolean) for (let index = 0; index < maximumSecurityDevicePerRow.length - 1; index++) totalBeams+= maximumSecurityDevicePerRow[index] * maximumSecurity...
Number of Laser Beams in a Bank
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 &lt; j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., ...
class Solution: def threeEqualParts(self, arr: List[int]) -> List[int]: n = len(arr) count_one = arr.count(1) if count_one == 0: return [0,n-1] if count_one % 3!= 0: return [-1,-1] target_ones = count_one // 3 breaks = [] one_count = 0 for i , bit in e...
class Solution { public int[] threeEqualParts(int[] arr) { List<Integer> ones = new ArrayList<>(); for (int i = 0; i < arr.length; i++){ if (arr[i]==1){ ones.add(i); } } if (ones.size()==0){ // edge case return new int[]{0,2}; ...
class Solution { public: vector<int> threeEqualParts(vector<int>& v) { vector<int> one; int n=v.size(); for(int i=0;i<n;i++){ if(v[i]==1) one.push_back(i+1); } if(one.size()==0){ return {0,2}; } if(one.size()%3) return {-1,-1}; ...
/** * @param {number[]} arr * @return {number[]} */ var threeEqualParts = function(arr) { const ones = arr.reduce((s, n) => s + n, 0); if (ones === 0) return [0, 2]; if (ones % 3 !== 0) return [-1, -1]; let onesToFind = ones / 3; let k = arr.length; while (onesToFind > 0) if (arr[--k] === 1) --onesToFind...
Three Equal Parts
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed ...
class Solution: def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]: g = [[[] for _ in range(2)] for _ in range(n)] for i,j in redEdges: g[i][0] += [j] for i,j in blueEdges: g[i][1] += [j] dis...
class Solution { // g1-> graph with red edges // g2-> graph with blue edges List<Integer> g1[], g2[]; int[] dist1, dist2, ans; int MX = (int) 2e9; public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { dist1 = new int[n]; dist2 = new int[n]; ...
#define red 1 #define blue 2 class Solution { public: vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) { vector<vector<pair<int,int>>> graph(n); vector<vector<int>> visited(n, vector<int>(3, false)); for(int i = 0;i<redEdges.size();i+...
const RED = "red"; const BLUE = "blue"; function mapAllEdges(edges) { const map = new Map(); for(let edge of edges) { if(!map.has(edge[0])) { map.set(edge[0], []); } map.get(edge[0]).push(edge[1]) } return map; } function bfs(color, redNodeMap, blueNodeMap, result) ...
Shortest Path with Alternating Colors
You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances i...
class Solution: def numberOfMatches(self, n: int) -> int: return n - 1
class Solution { public int numberOfMatches(int n) { // This is the problem's base case; we know that if n == 1, // the number of matches played must be 0, since the last team left // can't play a match against themselves. if (n == 1) return 0; // We declare an int to hold our recursive sol...
class Solution { public: int numberOfMatches(int n) { int count=0; while(n>1) { if(n%2==0) { int a=n/2; n=n/2; count=count+a;} else { int a=(n-1)/2; n=a+1; count=count...
/** * @param {number} n * @return {number} */ var numberOfMatches = function(n) { let matches = 0,current = n; while(current > 1){ if(current % 2 === 0){ matches += current/2; current = current/2 }else{ matches += (current-1)/2; current = (curre...
Count of Matches in Tournament
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be pl...
class Solution(object): def removeDuplicates(self, nums): n=len(nums) if n==2: return 2 if n==0: return 0 if n==1: return 1 same=0 start=-1 end=-1 i=0 while i<n-1: if nums[i]==nums[i+1] and same==...
class Solution { public int removeDuplicates(int[] nums) { int index = 1; int count = 0; for(int i = 1;i<nums.length;i++){ if(nums[i] == nums[i-1]){ count++; } else{ count = 0; } if(count <= 1){ ...
class Solution { public: int removeDuplicates(vector<int>& nums) { int l = 1; int last_selected = nums[0]; int count = 1; int n = nums.size(); for(int i = 1;i<n;i++) { if(nums[i]!=last_selected){ count = 1; last_selected = nu...
var removeDuplicates = function(nums) { let i = 0; let count = 0; for(let num of nums) { (num == nums[i - 1]) ? count++ : count = 1; if(i == 0 || (num >= nums[i - 1] && count <= 2)) nums[i++] = num; } return i; };
Remove Duplicates from Sorted Array II
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adj...
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: n = len(land) m = len(land[0]) groups = [] visited = set() for y in range(n): for x in range(m): if land[y][x] == 0: continue ...
class Solution { int[] arr; public int[][] findFarmland(int[][] land) { List<int[]> res = new ArrayList<>(); for(int i=0;i<land.length;i++) for(int j=0;j<land[0].length;j++){ if(land[i][j] == 1){ arr = new int[]{i,j,0,0}; dfs(la...
class Solution { public: vector<vector<int>> nbrs = {{0,1},{1,0},{-1,0},{0,-1}}; pair<int, int> dfs(vector<vector<int>> &land, int i, int j, vector<vector<bool>> &visited) { visited[i][j] = true; pair<int, int> res = make_pair(i, j); for(auto &nbr: nbrs) { int x = i + nbr[0];...
var findFarmland = function(land) { let height = land.length; let width = land[0].length; let results = []; let endRow = 0; let endCol = 0; let go = (i, j) => { if (i < 0 || j < 0 || i >= height || j >= width || land[i][j] === 0) { return; } endRow = Math.ma...
Find All Groups of Farmland
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you ha...
class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: total_cards = len(cardPoints) total = sum(cardPoints) window_size = total_cards - k window_total = 0 if total_cards == k: return total for i in range(total_cards - k): ...
class Solution { public int maxScore(int[] cardPoints, int k) { int n = cardPoints.length; int[] totalSum = new int[n]; int sum = 0; for(int i=0;i<n;i++){ sum += cardPoints[i]; totalSum[i] = sum; } if(n==k){ return sum; } ...
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int max_s = 0, left =0, right = 0, n = cardPoints.size(); //getting sum of k right elements for(int i = 0; i<k; i++){ right += cardPoints[n-i-1]; } // Assumming max as sum of k right elemen...
/** * @param {number[]} cardPoints * @param {number} k * @return {number} */ // Obtaining k cards from the beginning or end of the row for the largest sum, meaning leaving the // array with n-k adjacent cards with the min sum // therefore, this transform the problem to finding the minSum of subarray of length n-k ...
Maximum Points You Can Obtain from Cards
There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c. A city's skyline is the the outer contour for...
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: mxr = [max(i) for i in grid] mxc = [0 for _ in range(len(grid[0]))] for i in range(len(grid)): for j in range(len(grid[0])): mxc[j] = max(grid[i][j],mxc[j]) ans =0 for i in range(len(grid)): for j in range(len(grid)...
class Solution { public int maxIncreaseKeepingSkyline(int[][] grid) { int n = grid.length; int[] row = new int[n]; int[] col = new int[n]; int ans = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ row[i] = Math.max(row[i],grid[i][j]); ...
class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int n=grid.size(); //get max for every Column vector<int> maxfromcol(n,INT_MIN); for(int j=0;j<n;j++){ for(int i=0;i<n;i++){ maxfromcol[j]=max(maxfromcol[j],grid[i][j]); ...
/** * @param {number[][]} grid * @return {number} */ var maxIncreaseKeepingSkyline = function(grid) { let n = grid.length; let sum = 0; let cache = []; for (let i = 0; i < n; i++) { const rowMax = Math.max(...grid[i]); for (let j = 0; j < n; j++) { let colMax = cache[j];...
Max Increase to Keep City Skyline
Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'. In C++, there are two types of comments, line comments, and block com...
class Solution: def removeComments(self, source: List[str]) -> List[str]: ans, inComment = [], False new_str = "" for c in source: if not inComment: new_str = "" i, n = 0, len(c) # inComment, we find */ while i < n: if inComment...
class Solution { public List<String> removeComments(String[] source) { boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. //It is initally set to false since we haven't read anything until now. List<String> result = new A...
class Solution { public: vector<string> removeComments(vector<string>& source) { bool commentStart = false; vector<string> res; bool multiComment = false; // are we having a multi-line comment? for (string &eachS : source) { if (!multiComment) { r...
var removeComments = function(source) { let result = []; let multi_line_comment = false; let str = ""; source.forEach(line => { for(let idx=0; idx < line.length; ++idx) { // if /* is not ongoing, check for start of a comment or not if(!multi_line_comment) { ...
Remove Comments
You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer. ...
class Solution: def evaluate(self, expression: str) -> int: loc = {} stack = [] for i, x in enumerate(expression): if x == "(": stack.append(i) elif x == ")": loc[stack.pop()] = i def fn(lo, hi, mp): """Return value of given expression."...
class Solution { String expression; int index; HashMap<String,Deque<Integer>> scope; //variable may be assigned many times, we use the peek value public int evaluate(String expression) { this.expression=expression; index=0; scope=new HashMap<>(); return ev...
class Context { unordered_map<string_view, int> _map; const Context *_parent{}; public: Context(const Context *parent) : _parent{parent} { ; } const Context* Parent() const { return _parent; } int GetValue(const string_view &key) const { auto it = _map.find(key); if (it != _map.end()) retu...
/** * @param {string} expression * @return {number} */ var evaluate = function(expression) { return helper(expression); }; const helper = (expr, map = {}) => { if (expr[0] !== '(') return /[0-9]|-/.test(expr[0]) ? +expr : map[expr]; map = Object.assign({}, map); const start = expr[1] === 'm...
Parse Lisp Expression
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is ...
class Solution: def longestNiceSubstring(self, s: str) -> str: def divcon(s): # string with length 1 or less arent considered nice if len(s) < 2: return "" pivot = [] # get every character that is not nice for i, ch in enumer...
class Solution { public String longestNiceSubstring(String s) { String result = ""; // take first index, go from 0 to length-1 of the string for (int i = 0;i<s.length(); i++){ // take second index, this should go up to the length of the string <= for (int j = i+1;j<=s.length...
class Solution { public: string longestNiceSubstring(string s) { int arr1[26]={}; int arr2[26]={}; if(s.length()<2) return ""; for(char ch:s) { if(ch>='A' && ch<='Z') arr1[(ch|32)-'a']++; else arr2[ch-'a...
const swapCase = (str) => str.split('').map((c) => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()).join(''); var longestNiceSubstring = function(s) { let ans = ""; for (let i = 0; i < s.length; i++) { for (let ii = i + 1; ii < s.length + 1; ii++) { let substring = s.s...
Longest Nice Substring
Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. x mod y denotes the remainder when x is divided by y. &nbsp; Example 1: Input: nums = [0,1,2] Output: 0 Explanation: i=0: 0 mod 10 = 0 == nums[0]. i=1: 1 mod 10 = 1 == nums[1]...
class Solution: def smallestEqual(self, nums: List[int]) -> int: for idx, n in enumerate(nums): if idx%10==n: return idx return -1
class Solution { public int smallestEqual(int[] nums) { int index = 0; for (int i = 0 ; i < nums.length; i++) { if (index == nums[i]) { return i; } if (++index== 10) { index = 0; } } return -1; } }
class Solution { public: int smallestEqual(vector<int>& nums) { int i = 0; while (i < nums.size() && i % 10 != nums[i]) i++; return i >= nums.size() ? -1 : i; } };
/** * @param {number[]} nums * @return {number} */ var smallestEqual = function(nums) { return nums.findIndex((n, i) => i % 10 === n) };
Smallest Index With Equal Value
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array buildings where...
class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: d = collections.defaultdict(list) for i,(start, end, height) in enumerate(buildings): d[start].append(height) d[end].append(-height) l = list(d.keys()) l...
class height implements Comparable<height>{ int val = -1; int pos = -1; boolean isStart = false; height(int a, int b, boolean c){ val = a; pos = b; isStart = c; } public int compareTo(height h){ if(this.pos != h.pos) return this.pos-h.pos; if(i...
/* 1.mark the starting and ending pt of each building -> let height of starting pt be negative and ending pt be positive [2,4,10] -> [[2,-10],[4,10]] 2.mark all consecutive building ->store every pair of x and y in pair sort it acc to x 3.get max y for all x values ->use heap-->(multiset) to store all bui...
var getSkyline = function(buildings) { let results = []; let points = []; for (let building of buildings) { points.push([building[0],building[2]]) points.push([building[1],-building[2]]) } let heights = []; points.sort((a,b)=>(b[1]-a[1])) points.sort(...
The Skyline Problem
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. &nbsp; Example 1: Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the interva...
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1) intervals.sort() res = 0 prevEnd = intervals[0][1] for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value if st...
// |-------| // |--| // |-------| //. |-------| // |-------| //. |-------| class Solution { public int eraseOverlapIntervals(int[][] intervals) { Arrays.sort(intervals, (a,b) -> a[0] - b[0]); int start = intervals[0][0]; int end = intervals[0][1]; int res = ...
class Solution { void solve(priority_queue <pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> &pq,int e,int &cnt){ while(!pq.empty() && pq.top().first<e){ e = min(e,pq.top().second); pq.pop(); cnt++; } } public: int eraseOverlapIn...
var eraseOverlapIntervals = function(intervals) { // sort by end's small to big intervals.sort((a, b) => a[1] - b[1]); let total = 1; let maxEnd = intervals[0][1]; for (let i = 1; i < intervals.length; i++) { let [start, end] = intervals[i]; if (start >= maxEnd) { ...
Non-overlapping Intervals
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements...
class Solution: def findOriginalArray(self, changed: List[int]) -> List[int]: counter = collections.Counter(changed) res = [] for k in counter.keys(): if k == 0: # handle zero as special case if counter[k] % 2 > 0: ...
class Solution { public int[] findOriginalArray(int[] changed) { Arrays.sort(changed); if(changed.length%2!=0) return new int[0]; int mid = changed.length/2; int[] res = new int[mid]; int[] freq = new int[100001]; for(int no : changed) freq[no]++; ...
class Solution { public: vector<int> findOriginalArray(vector<int>& changed) { unordered_map<int, int> freq; for (auto num : changed) freq[num]++; sort(changed.begin(), changed.end()); vector<int> res; for (auto num : changed) { if (freq[num] && ...
// Idea is to sort the input array first then start traversing the array // now if we saw half of the current element before and that half is unmatched then // match both of them otherwise note the occurence of current element inorder // to match it with its double element in the future // Time -> O(nlogn) due to sort...
Find Original Array From Doubled Array
You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target. In one operation, you can pick an index i where 0 &lt;= i &lt; n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' ...
class Solution: def minFlips(self, target: str) -> int: flip = False res = 0 for c in target: if (c == '1') != flip: flip = not flip res += 1 return res
class Solution { public int minFlips(String target) { boolean lastBit = false; int flips = 0; for(int i=0;i<target.length();i++){ if(target.charAt(i)=='1' && !lastBit){ flips++; lastBit = !lastBit; } else if(target.charAt...
class Solution { public: int minFlips(string target) { int count=0; // we see thye number of times the change occur for(int i=0; i<target.size()-1;i++){ if(target[i] != target[i+1] ){ count++; }} if(target[0]=='0'){return count;} else{return count+1...
var minFlips = function(target) { target = "0" + target; let count = (target.match(/01/g) || []).length * 2; return target[target.length -1] ==="0" ? count : count - 1; };
Minimum Suffix Flips
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. &nbsp; Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respe...
def is_leaf(x): return x.left is None and x.right is None class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: if root is None: return 0 if root.left and is_leaf(root.left): left = root.left.val else: left = self.sumOfLeftLeaves...
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; if(root.left!=null && root.left.left==null && root.left.right==null){ return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); }else{ return sum...
class Solution { int sum=0; public: bool solve(TreeNode* root){ if(root==NULL) return false; if(root->left==NULL && root->right==NULL) return true; if(solve(root->left)) sum+=root->left->val; solve(root->right); return false; } int sumOfLeftLeaves(TreeNode* root) ...
var sumOfLeftLeaves = function(root) { let total = 0; const go = (node, isLeft) => { if (isLeft && !node.left && !node.right) { total += node.val; return; } if (node.left) go(node.left, true); if (node.right) go(node.right, false) } go(ro...
Sum of Left Leaves
You are given an array tasks where tasks[i] = [actuali, minimumi]: actuali is the actual amount of energy you spend to finish the ith task. minimumi is the minimum amount of energy you require to begin the ith task. For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. Ho...
class Solution: def minimumEffort(self, tasks: List[List[int]]) -> int: tasks.sort(key=lambda x: x[0]-x[1]) def ok(mid): for actual, minimum in tasks: if minimum > mid or actual > mid: return False if minimum <= mid: mid -= actual return True ...
import java.util.*; class Solution { public int minimumEffort(int[][] tasks) { Arrays.sort(tasks, new Comparator<int[]>(){ @Override public int compare(int[] a, int[] b) { return (b[1]-b[0])-(a[1]-a[0]); } }); int sum=0, max...
class Solution { public: int minimumEffort(vector<vector<int>>& tasks) { int diff=INT_MAX,ans=0; for(auto i : tasks){ diff=min(diff,i[1]-i[0]); ans+=i[0]; } int val=0; for(auto i : tasks) val=max(val,i[1]); return max(ans+diff,val);...
var minimumEffort = function(tasks) { let minimumStartingEnergy = 0; let currentEnergy = 0; tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]) ); for (let task of tasks) { if (task[1] > currentEnergy) { minimumStartingEnergy += (task[1] - currentEnergy); currentEnergy = task[1]; } ...
Minimum Initial Energy to Finish Tasks
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned i...
class Solution: def solve(self,k,target,ans,temp,idx,nums): if idx==len(nums): if target==0 and k==0: ans.append(list(temp)) return if nums[idx]<=target: temp.append(nums[idx]) self.solve(k-1,target-n...
//Recursion class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); //int[] arr = new int{1,2,3,4,5,6,7,8,9}; List<Integer> ds = new ArrayList<>(); helper(1, n, k, ds, ans); return ans; } p...
class Solution { public: vector<vector<int>> ans; //declare temp global vector in this vector we will store temprary combinations vector<int> temp; void solve(int k,int n,int order){ //check if our target became zero and combination size became zero then push temp vector inside the ans it means ...
/** * @param {number} k * @param {number} n * @return {number[][]} */ var combinationSum3 = function(k, n) { const ans = []; const st = []; function dfs(start, t) { if (t === 0 && st.length === k) { ans.push(Array.from(st)); return; } for (let i = start; ...
Combination Sum III
Given an array of integers&nbsp;nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue&nbsp;plus&nbsp;elements in nums&nbsp;(from left to right). Return the minimum positive value of&nbsp;startValue such that the step by step sum is never less th...
class Solution: def minStartValue(self, nums: List[int]) -> int: return max(1, 1 - min(accumulate(nums)))
class Solution { public int minStartValue(int[] nums) { int lowest_sum = 0; int sum = 0; for(int i=0; i<nums.length; i++) { sum += nums[i]; if(lowest_sum > sum) { lowest_sum = sum; } } return 1-lowest_sum; } }
class Solution { public: int minStartValue(vector<int>& nums) { int result=min(nums[0],0); for(int i=1;i<nums.size();i++){ nums[i]+=nums[i-1]; result = min(result,nums[i]); } return abs(result)+1; } };
var minStartValue = function(nums) { var min = 1; var sum = 0; for(var i=0;i<nums.length;i++){ sum = sum+nums[i]; min = Math.min(min,sum); } if(min == 1){ return min; } // add 1 to negative of min value obtained to keep the sum always positive return (-1*min)+1; };
Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 &lt;= i, j &lt; nums.length i != j nums[i] - nums[j] == k Notice that |val| denotes the absolute value of val. &nbsp; Exa...
class Solution: def findPairs(self, nums: List[int], k: int) -> int: nums.sort() dict1={} s=0 res=[] for n in nums: if dict1.get(n,None) is not None: res.append(n) dict1[n+k]=n res=list(set(res)) return len(res)
// O(n) Time Solution class Solution { public int findPairs(int[] nums, int k) { Map<Integer, Integer> map = new HashMap(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int result = 0; for (int i : map.keySet()) if (k > 0 && map.containsKey(i + k) || k == 0 && map.ge...
class Solution { public: int findPairs(vector<int>& nums, int k) { unordered_map<int,int> a; for(int i:nums) a[i]++; int ans=0; for(auto x:a) { if(k==0) { if(x.second>1) ans++; } ...
var findPairs = function(nums, k) { nums.sort((a, b) => b - a); const { length } = nums; const hash = new Set(); let left = 0; let right = 1; while (left < length - 1) { while (right < length) { const diff = nums[left] - nums[right]; diff === k && hash.add(`${nums[left]},${nums[right]}`); diff > k ...
K-diff Pairs in an Array
Given the root of a binary tree, return the preorder traversal of its nodes' values. &nbsp; Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] &nbsp; Constraints: The number of nodes in the tree is in the range [0, 100]. -1...
from collections import deque from typing import List, Optional class Solution: """ Time: O(n) """ def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if root is None: return [] queue = deque([root]) preorder = [] while queue: n...
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); preorderTraversal2(root, result); return result; } public List<Integer> preorderTraversal2(TreeNode root,List<Integer> result) { if(root!=null){ ...
class Solution { void solve(TreeNode *root, vector<int> &ans){ if(root == NULL) return; ans.push_back(root->val); solve(root->left, ans); solve(root->right, ans); } public: vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; solve(root, ans); ...
var preorderTraversal = function(root) { let res = [] const check = node => { if(node === null) return else res.push(node.val) if(node.left !== null) check(node.left) if(node.right !== null) check(node.right) } check(root) return res };
Binary Tree Preorder Traversal
You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1. You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people. ...
class UnionFindSet(object): def __init__(self, n): self.data = range(n) def find(self, x): while x <> self.data[x]: x = self.data[x] return x def union(self, x, y): self.data[self.find(x)] = self.find(y) def speedup(self): for i in range(len(self.da...
class Solution { int[] parent; boolean[] result; public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) { parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } result = new boolean[requests.length]; for (...
/ Standard DSU Class class DSU { vector<int> parent, size; public: DSU(int n) { for(int i=0; i<=n; i++) { parent.push_back(i); size.push_back(1); } } int findParent(int num) { if(parent[num] == num) return num; return parent[num] = findParent(par...
/* DSU Class Template */ class DSU { constructor() { this.parents = new Map(); this.rank = new Map(); } add(x) { this.parents.set(x, x); this.rank.set(x, 0); } find(x) { const parent = this.parents.get(x); if (parent === x) return x; const se...
Process Restricted Friend Requests
You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x. Return the maximum number of consecutive integer values that you can make with your coi...
class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: coins.sort() res = 1 for coin in coins: if (res >= coin): res += coin return res
class Solution { public int getMaximumConsecutive(int[] coins) { if(coins.length==0 && coins==null) return 0; TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>(); for(int i:coins) map.put(i,map.getOrDefault(i,0)+1); int range=0; for(int i:map.keySet()){ ...
class Solution { public: int getMaximumConsecutive(vector<int>& coins) { sort(coins.begin(), coins.end()); int n = coins.size(); int ans = 1; for(int i = 0; i < n; i++) { if(coins[i] > ans) return ans; ans += coins[i]; } return ans; } };
// we iterate from the smallest number while maintaining an integer sum. sum means that we can produce all number from 0 to sum. // when we can make numbers from 0 to sum, and we encounter a new number, lets say arr[2]. // it is obvious that we can create all numbers from sum to sum + arr[2]. // if there is a gap if(ar...
Maximum Number of Consecutive Values You Can Make
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum ...
class Solution: def waysToSplit(self, nums: List[int]) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) ans = 0 for i in range(1, len(nums)): j = bisect_left(prefix, 2*prefix[i]) k = bisect_right(prefix, (prefix[i] + prefix[-1])//2) ...
class Solution { public int waysToSplit(int[] nums) { int size = nums.length; for (int i = 1; i < size; ++i) { nums[i] += nums[i - 1]; } int res = 0; int mod = 1_000_000_007; for (int i = 0; i < size - 2; ++i) { int left = searchLeft(nums, i, s...
class Solution { public: int waysToSplit(vector<int>& nums) { int n = nums.size(), mod = 1e9 + 7; long long ans = 0; vector<int> prefix(n); partial_sum(nums.begin(), nums.end(),prefix.begin()); for (int i = 0; i < n - 2; i++) { int left = prefix[i], remain = (prefix[n - ...
var waysToSplit = function(nums) { const mod = 1000000007; const lastIndex = nums.length - 2; const total = nums.reduce((sum, num) => sum + num) let midLeftPtr = -1; let midRightPtr = -1; let leftSum = 0; let midLeftSum = 0; let midRightSum = 0; let numWaysToSplit = 0; ...
Ways to Split Array Into Three Subarrays
Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows. The points are then calculated as follows: The target has integer scoring sections ranging from 0 to 11 inclusive. For each section of t...
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: self.bestScore = 0 self.bestBobArrows = None def backtracking(k, remainArrows, score, bobArrows): if k == 12: if score > self.bestScore: s...
class Solution { int bobPoint = 0; int[] maxbob = new int[12]; public int[] maximumBobPoints(int numArrows, int[] aliceArrows) { int[] bob = new int[12]; calculate(aliceArrows, bob, 11, numArrows, 0); //Start with max point that is 11 return maxbob; ...
class Solution { public: int maxscore; vector<int> ans; void helper(vector<int> &bob, int i, vector<int>& alice, int remarrows, int score) { if(i == -1 or remarrows <= 0) { if(score >= maxscore) { maxscore = score; ans = bo...
var maximumBobPoints = function(numArrows, aliceArrows) { let max = 0, n = aliceArrows.length, res; backtrack(numArrows, 0, 0, Array(n).fill(0)); return res; function backtrack(arrows, idx, points, bobArrows) { if (idx === n || arrows === 0) { let origVal = bobArrows[n - 1]; if (arrows > 0) bob...
Maximum Points in an Archery Competition
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target. In case of a tie, return the minimum such integer. Noti...
class Solution: def findBestValue(self, arr: List[int], t: int) -> int: def getsum(x): s = 0 for i in range(n): if arr[i] > x: s += x*(n-i) break else: s += arr[i] return s a...
class Solution { int max = 0; int len; public int findBestValue(int[] arr, int target) { this.len = arr.length; for (int i = 0; i < len; i++) max = Math.max(max, arr[i]); int l = 0; int r = max; while(l < r){ int mid = l + (r-l) / 2; ...
// This Question Includes Both Binary Search And bit of Greedy Concept also. // See We Know Ans Always Lies Between 0 and maximum element according to given question condition Because // sum value at maximum element is same as any other element greater than it. // So we get our sum from getval function after that you n...
/** * @param {number[]} arr * @param {number} target * @return {number} */ var findBestValue = function(arr, target) { const sortedArr = [...arr].sort(function (a, b) { return a - b; }); var lowestValue = Math.min(sortedArr[arr.length-1], Math.floor(target/arr.length)); var higestValue = Math.min(sort...
Sum of Mutated Array Closest to Target
Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a...
class Solution: def checkAlmostEquivalent(self, w1: str, w2: str) -> bool: return all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())
class Solution { public boolean checkAlmostEquivalent(String word1, String word2) { Map<Character,Integer> map = new HashMap(); for (int i = 0; i < word1.length(); i++) { map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1); map.put(word2.charAt(i), map.getOrDe...
class Solution { public: bool checkAlmostEquivalent(string word1, string word2) { unordered_map<char, int> m; for(int i = 0; i < word1.size(); i++){ m[word1[i]]++; } for(int i = 0; i < word2.size(); i++){ m[word2[i]]--; } for(auto i : m){ if(abs(i.second) > 3){ return false; } } return ...
var checkAlmostEquivalent = function(word1, word2) { const hm = new Map() const addToHm = (ch, add) => { if (hm.has(ch)) hm.set(ch, hm.get(ch) + (add ? +1 : -1)) else hm.set(ch, (add ? +1 : -1)) } for (let i = 0; i < word1.length; i++) { addToHm(w...
Check Whether Two Strings are Almost Equivalent
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is...
# Added on 2022-08-18 15:51:55.963915 var minWindow = function(s, t) { const tf = {}, sf = {}; for(let c of t) { tf[c] = (tf[c] || 0) + 1; } let l = 0, r = 0, rs = t.length; let ml = -1, mr = -1; for(; r < s.length; r++) { const c = s[r]; if(!tf[c]) continue; c...
class Solution { public String minWindow(String s, String t) { HashMap<Character, Integer> child = new HashMap<>(); HashMap<Character, Integer> parent = new HashMap<>(); int left = -1, right = -1, match = 0; String window = ""; for(int i = 0; i < t.length(); i++){ ...
class Solution { public: string minWindow(string s, string t) { unordered_map<char,int> ump; for(auto i:t){ ump[i]++; } int i =0,j =0,count =0; int ans =INT_MAX,answer =0; for (;j < s.size();j++) { if(ump[s[j]]>0) { count++; } ump[s[j]]--...
var minWindow = function(s, t) { const tf = {}, sf = {}; for(let c of t) { tf[c] = (tf[c] || 0) + 1; } let l = 0, r = 0, rs = t.length; let ml = -1, mr = -1; for(; r < s.length; r++) { const c = s[r]; if(!tf[c]) continue; const sc = sf[c] || 0; sf[c] = s...
Minimum Window Substring
You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memo...
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: inverted = False if memory2>memory1: memory2, memory1 = memory1, memory2 inverted = True #Compute the number of steps in first stage - 1 i_start = solve_quadratic(1,2*(memory1-me...
class Solution { public int[] memLeak(int memory1, int memory2) { int i = 1; while(Math.max(memory1, memory2) >= i){ if(memory1 >= memory2) memory1 -= i; else memory2 -= i; i++; } return new int[]{i, memory1, memory2...
class Solution { public: vector<int> memLeak(int memory1, int memory2) { int time = 1; while (max(memory1, memory2) >= time) { if (memory1 >= memory2) { memory1 -= time; } else { memory2 -= time; } ++time; } ...
var memLeak = function(memory1, memory2) { var count=1; while(true) { if(memory1>=memory2 && memory1>=count) memory1-=count; else if(memory2>=memory1 && memory2>=count) memory2-=count else return [count, memory1, memory2...
Incremental Memory Leak
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number ...
class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: def findNei(board): directs = [[0, 1], [0, -1], [1, 0], [-1, 0]] boards = [] for i in range(2): for j in range(3): if board[i][j] == 0: for ...
class Solution { int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}}; public int slidingPuzzle(int[][] board) { String tar="123450"; String src=""; for(int i =0;i<board.length;i++){ for(int j=0;j<board[i].length;j++){ src+=board[i][j]; } ...
class Node{ public: int row; int col; vector<vector<int>>state; }; class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { vector<vector<int>>target={{1,2,3},{4,5,0}}; queue<Node>q; int n=2; int m=3; vector<vector<int>>dir={{1,0},{-1,0},{0,1},{0,-1}}; for(int i=0;i<board...
/** * @param {number[][]} board * @return {number} */ class BoardState { constructor(board, currStep) { this.board = this.copyBoard(board); this.boardString = this.flatToString(board); this.emptyIndex = this.findIndexOf0(board); this.currStep = currStep; } findIndexOf0(bo...
Sliding Puzzle
An n-bit gray code sequence is a sequence of 2n integers where: Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differs by exactly one bit, and The binary representation...
import math class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)] grayCodes = [0] for diff in allowedDiffs: grayCodes += [code + diff for code in reversed(gra...
class Solution { public List<Integer> grayCode(int n) { ArrayList list=new ArrayList(); for(int i=0;i<(1<<n);i++){ list.add(i^(i>>1)); } return list; } }
class Solution { public: vector<int> grayCode(int n) { vector<int> dp = {0,1}; int cnt = 1; for(int i = 2; i < n+1; i++) { int mod = pow(2, cnt); int index = dp.size()-1; while(index >= 0) { dp.push_back(dp[index] + mod); in...
/** * @param {number} n * @return {number[]} */ var grayCode = function(n) { return binaryToInt(dfs(n, ['0', '1'])) }; const dfs = (n, arr) => { if (n === 1) return arr const revArr = [...arr].reverse() addOneBefore('0', arr) addOneBefore('1', revArr) return dfs(n - 1, [...arr, ...revArr]...
Gray Code
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: multiply the number on display by 2, or subtract 1 from the number on display. Given two integers startValue and target, return the minimum number of operations needed to display target on the calcula...
class Solution(object): def brokenCalc(self, startValue, target): """ :type startValue: int :type target: int :rtype: int """ res = 0 while target > startValue: res += 1 if target % 2: target += 1 else: ...
class Solution { public int brokenCalc(int startValue, int target) { if(startValue >= target) return startValue - target; if(target % 2 == 0){ return 1 + brokenCalc(startValue, target / 2); } return 1 + brokenCalc(startValue, target + 1); } }
class Solution { public: int brokenCalc(int startValue, int target) { int result=0; while(target>startValue) { result++; if(target%2==0) target=target/2; else target+=1; } result=result+(startValue-target); ...
/** * @param {number} startValue * @param {number} target * @return {number} */ var brokenCalc = function(startValue, target) { let steps = 0; while(target !== startValue){ if(startValue > target){ return steps + startValue - target; } if(target %2 === 0){ t...
Broken Calculator
You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get. &nbsp; Example 1: Input: num = 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: num = 9973 Output: 9973 Explanation: No swap. &nb...
class Solution: def maximumSwap(self, num: int) -> int: digits = [int(x) for x in str(num)] n = len(digits) for i in range(n): maxx = digits[i] indx = i for j in range(i+1,n): if digits[j]>=maxx and digits[j]!=digits[i...
class Solution { public int maximumSwap(int num) { char str[]=String.valueOf(num).toCharArray(); char arr[]=str.clone(); Arrays.sort(arr); int i=0; int j=str.length-1; while(i<str.length && j>=0 && arr[j]==str[i]){i++;j--;} int search=j; if(i==str.leng...
class Solution { public: int maximumSwap(int num) { string st_n=to_string(num); int maxNum=-1,maxIdx=-1; int leftidx=-1,rightidx=-1; for(int i=st_n.size()-1;i>=0;i--) { if(st_n[i]>maxNum) { maxNum=st_n[i]; maxIdx=i; ...
var maximumSwap = function(num) { const nums = `${num}`.split(''); for (let index = 0; index < nums.length - 1; index++) { const current = nums[index]; const diff = nums.slice(index + 1); const max = Math.max(...diff); if (current >= max) continue; const swapIndex = index + diff.lastIndexOf(`${max}`) + 1;...
Maximum Swap
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it w...
class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return odd, even_start, even = head, head.next, head.next while odd is not None and even is not None: odd.next = even.next if odd.next is not None: ...
class Solution { public ListNode oddEvenList(ListNode head) { if(head == null) { return head; } ListNode result = head, evenHalf = new ListNode(0), evenHalfPtr = evenHalf; for(; head.next != null; head = head.next) { evenHalfPtr = evenHalfPtr.next = head.next;...
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head == NULL || head->next == NULL || head->next->next == NULL){ return head; } ListNode *first = head; ListNode *second = head->next; ListNode *last = head; int count = 1; while(l...
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var oddEvenList = function(head) { if (!head || !head.next) return head; ...
Odd Even Linked List
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the cust...
class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: return max(map(sum, accounts))
class Solution { public int maximumWealth(int[][] accounts) { int res = 0; for(int i =0;i<accounts.length;i++){ int temp = 0; for(int j = 0;j<accounts[i].length;j++){ temp+=accounts[i][j]; } res = Math.max(res,temp); } r...
class Solution { public: int maximumWealth(vector<vector<int>>& accounts) { int maxWealth = 0; for (auto account : accounts) { int currentSum = 0; for (int x : account) currentSum += x; if (currentSum > maxWealth) maxWealth = currentSum; } retur...
var maximumWealth = function(accounts) { var res = 0; for(var i =0;i<accounts.length;i++){ var temp = 0; for(var j = 0;j<accounts[i].length;j++){ temp+=accounts[i][j]; } res = Math.max(res,temp); } return res; };
Richest Customer Wealth
You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string that can be derived from ...
class Solution: def longestSubsequence(self, s: str, k: int) -> int: end, n = len(s)-1, s.count("0") while end >=0 and int(s[end:], 2)<= k: end-=1 return n+ s[end+1:].count("1")
class Solution { public int longestSubsequence(String s, int k) { int numOfZeros = 0; int numOfOnes = 0; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(ch == '0'){ numOfZeros++; } } int sum = 0; ...
class Solution { public: int ans = 0; int f(int i,int size, int sum, string &s, vector<vector<int>>&dp){ if(i<0){ return 0; } if(dp[i][size] != -1){ return dp[i][size]; } int no = f(i-1,size,sum,s,dp); int yes = 0; if((sum-(s[i]-'0'...
/** * @param {string} s * @param {number} k * @return {number} */ var longestSubsequence = function(s, k) { let count = 0; let j = s.length - 1; // starting from the last digit let i = 0; // binary number position let acc = 0; while(j >= 0){ let positionNumber = Number(s[j]) * Math.pow...
Longest Binary Subsequence Less Than or Equal to K
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged&nbsp;IP address&nbsp;replaces every period "." with "[.]". &nbsp; Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" &nbsp; Constraints: The ...
class Solution: def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]')
class Solution { public String defangIPaddr(String address) { return address.replace(".","[.]"); } }
class Solution { public: string defangIPaddr(string address) { string res; for(int i=0;i<address.length();i++){ if(address[i]=='.'){ res+="[.]"; } else{ res+=address[i]; } } return res; } };
var defangIPaddr = function(address) { return address.split("").map((x)=>{ if(x=='.') return "[.]" else return x }).join("") };
Defanging an IP Address
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Re...
vowels = "aeiouAEIOU" class Solution: def halvesAreAlike(self, S: str) -> bool: mid, ans = len(S) // 2, 0 for i in range(mid): if S[i] in vowels: ans += 1 if S[mid+i] in vowels: ans -=1 return ans == 0
class Solution { public boolean halvesAreAlike(String s) { //add vowels to the set Set<Character> set = new HashSet<>(); set.add('a'); set.add('e'); set.add('i'); set.add('o'); set.add('u'); set.add('A'); set.add('E'); set.add('I'); ...
class Solution { public: bool halvesAreAlike(string s) { unordered_set<char> set = {'a', 'e', 'i', 'o', 'u','A','I','E','O','U'}; int i=0,j=s.size()/2,cnt=0; while(j<s.size()){ if(set.find(s[i])!=set.end()) cnt++; if(set.find(s[j])!=set.end()) cnt--; i++; ...
var halvesAreAlike = function(s) { let isVowel = ["a","e","i","o","u","A","E","I","O","U"]; let count = 0; for (let i = 0; i < s.length / 2; i++) { if (isVowel.indexOf(s[i]) !== -1) { count++; } } for (let i = s.length / 2; i < s.length; i++) { if (isVowel.indexOf...
Determine if String Halves Are Alike
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). &nbsp; Exa...
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] self.explore(graph, graph[0], [0], res) return res def explore(self, graph, candidates, step, res): if step[-1] == len(graph)-1: res.append(list(step)) els...
Approach : Using dfs+ backtracking we can solve it class Solution { public List<List<Integer>> allPathsSourceTarget(int[][] graph) { List<List<Integer>> ans=new ArrayList<>(); List<Integer> temp=new ArrayList<>(); boolean []visit=new boolean [graph.length]; helper(graph,0,graph.length-1,ans,temp,visi...
class Solution { public: // setting a few class variables, so that we do not have to pass them down all the time in the recursive dfs calls int target; vector<vector<int>> res; vector<int> tmp; void dfs(vector<vector<int>>& graph, int currNode = 0) { // updating tmp tmp.push_back(currNo...
/** * @param {number[][]} graph * @return {number[][]} */ const allPathsSourceTarget = function(graph) { const n = graph.length; const result = []; const dfs = (node, path) => { if (node === n-1) { result.push([...path, node]); // Add the current path to the result if we have reached ...
All Paths From Source to Target
Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order. &nbsp; Example 1: Input: n = 2 Output: ["1/2"] Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to...
class Solution: def simplifiedFractions(self, n: int) -> List[str]: collect = {} for b in range(2, n+1): for a in range(1, b): if a/b not in collect: collect[a/b] = f"{a}/{b}" return list(collect.values())
class Solution { public List<String> simplifiedFractions(int n) { List<String> list = new ArrayList<>() ; for(int numerator = 1; numerator< n ; numerator++) { for(int denominator = numerator+1; denominator<=n; denominator++) { if(gcd(numerator,denominator) == 1) { ...
class Solution { public: bool simplified(int n, int i){ while(i>0){ n-=i; if(i>n)swap(n,i); } if(n>1) return false; else return true; } vector<string> simplifiedFractions(int n) { vector<string> ans; while(n>1){ int i=1; ...
var simplifiedFractions = function(n) { const res = []; const checkValid = (a, b) => { if(a === 1) return 1; let num = 2; while(num <= a) { if(b % num === 0 && a % num === 0) return num; num++; } return 1; } let i = 1; while(i / n < 1) ...
Simplified Fractions
Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a chara...
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: dict1={} m="" #creating a dictionary by mapping each element from string S to string T for i,j in zip(s,t): # this for the cases like "badc" and "baba" so we dont want two keys mapping to same value hence we can reject direc...
class Solution { public boolean isIsomorphic(String s, String t) { ArrayList<Integer>list1 = new ArrayList<>(); ArrayList<Integer>list2 = new ArrayList<>(); for(int i=0;i<s.length();i++){ list1.add(s.lastIndexOf(s.charAt(i))); list2.add(t.lastIndexOf(t.charAt...
class Solution { public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; unordered_map<char,char>mp; for(int i=0;i<s.size();i++){ if(mp.find(s[i])==mp.end()){ for(auto it:mp){ if(it.second==t[i])return false; ...
/** * @param {string} s * @param {string} t * @return {boolean} */ var isIsomorphic = function(s, t) { const obj = {}; const setValues = new Set(); let isIso = true; for(var indexI=0; indexI<s.length;indexI++) { if(obj[s[indexI]] || setValues.has(t[indexI])) { if (obj[s[indexI]] ...
Isomorphic Strings
You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; nums2.length, is valid if both i &lt;= j and nums1[i] &lt;= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pa...
class Solution: def maxDistance(self, n1: List[int], n2: List[int]) -> int: i = j = res = 0 while i < len(n1) and j < len(n2): if n1[i] > n2[j]: i += 1 else: res = max(res, j - i) j += 1 return res
class Solution { public int maxDistance(int[] nums1, int[] nums2) { int max = 0; for (int i = 0; i < nums1.length; i++) { int r = nums2.length - 1; int l = i; int m = i; while (l <= r) { m = l + (r - l) / 2; if (nums1[i]...
class Solution { public: int maxDistance(vector<int>& nums1, vector<int>& nums2) { reverse(nums2.begin(),nums2.end()); int ans = 0; for(int i=0;i<nums1.size();++i){ auto it = lower_bound(nums2.begin(),nums2.end(),nums1[i]) - nums2.begin(); //Finds first element greater than or e...
var maxDistance = function(nums1, nums2) { let i = 0, j = 0; let ans = 0; while (i < nums1.length && j < nums2.length) { // maintain the i <= j invariant j = Math.max(j, i); // we want to maximize j so move it forward whenever possible while (nums1[i] <= nums2[j...
Maximum Distance Between a Pair of Values
You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color&nbsp;you currently have in your inventory. For example, if you own 6 yellow balls, the customer w...
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) inventory += [0] res = 0 k = 1 for i in range(len(inventory)-1): if inventory[i] > inventory[i+1]: if k*(inventory[i]-inventory[...
class Solution { private long mod = 1000000007L; public int maxProfit(int[] inventory, int orders) { // we use pq to find the most balls PriorityQueue<Long> pq = new PriorityQueue<>((x, y) -> Long.compare(y, x)); pq.offer(0L); // we use map to count the balls Map<Long, Long>...
#define ll long long const int MOD = 1e9+7; class Solution { public: ll summation(ll n) { return (n*(n+1)/2); } int maxProfit(vector<int>& inventory, int orders) { ll n = inventory.size(), i = 0, ans = 0; inventory.push_back(0); sort(inventory.rbegin(), inventory....
var maxProfit = function(A, k) { //rangeSum Formula let rangesum=(i,j)=>{ i=BigInt(i),j=BigInt(j) return ((j*((j+1n))/2n)-(i*(i+1n)/2n)) } A.unshift(0) //prepend the sentinel 0 A.sort((a,b)=>a-b) let n=A.length,result=0n,mod=BigInt(1e9+7),i=n-1 // can use all current levels ...
Sell Diminishing-Valued Colored Balls
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate...
class Solution: def shortestPath(self, grid: List[List[int]], k: int) -> int: Q = [[0, 0, k]] # m, n, remaining elimination quota rows, cols = len(grid), len(grid[0]) V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited while Q: f...
class Solution { int rowLen = 0; int colLen = 0; int MAXVAL = 0; public int shortestPath(int[][] grid, int k) { rowLen = grid.length; colLen = grid[0].length; MAXVAL = rowLen * colLen + 1; int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowL...
class Solution { public: vector<vector<int>> directions{{-1,0},{1,0},{0,1},{0,-1}}; int shortestPath(vector<vector<int>>& grid, int k) { int m = grid.size(),n = grid[0].size(),ans=0; queue<vector<int>> q; bool visited[m][n][k+1]; memset(visited,false,sizeof(visited)); q.p...
var shortestPath = function(grid, k) { const dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const m = grid.length; const n = grid[0].length; let q = [[0,0,k]]; const visited = new Set(); visited.add(`0:0:${k}`); let cnt = 0; while(q.length>0) { const size = q.length; ...
Shortest Path in a Grid with Obstacles Elimination
You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: If i % 2 == 0, then arr[i] = perm[i / 2]. If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. You will then assign a...
class Solution: def reinitializePermutation(self, n: int) -> int: ans = 0 perm = list(range(n)) while True: ans += 1 perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)] if all(perm[i] == i for i in range(n)): return ans
class Solution { public int reinitializePermutation(int n) { int ans = 1; int num = 2; if(n == 2) return 1; while(true){ if(num % (n-1) == 1)break; else { ans++; num = (num * 2) % (n-1); } } return a...
class Solution { public: vector<int> change(vector<int>arr,vector<int>v){ int n=v.size(); for(int i=0;i<n;i++){ if(i%2==0){ arr[i]=v[i/2]; } else{ arr[i]=v[(n/2) + ((i-1)/2) ]; } } return arr; } ...
* @param {number} n * @return {number} */ var reinitializePermutation = function(n) { if (n < 2) return 0; let prem = []; let count = 0; for (var i = 0; i < n; i++) { prem[i] = i; } let newArr = []; newArr = helper(prem, newArr); const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); ...
Minimum Number of Operations to Reinitialize a Permutation
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. &nbsp; Example 1: Input: nums = [1,2,3] Output: 4...
class Solution: def subArrayRanges(self, nums: List[int]) -> int: n = len(nums) # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray # so totalsum = maxsu...
class Solution { class Node{ long val, displace; Node(long val, long displace){ this.val = val; this.displace = displace; } } public long subArrayRanges(int[] nums) { //lesser than current element Stack<Node> stack = new Stack<>(); ...
class Solution { public: long long subArrayRanges(vector<int>& nums) { int n=nums.size(); long long res=0; for(int i=0;i<n-1;i++){ int maxi=nums[i], mini=nums[i]; for(int j=i+1;j<n;j++){ if(nums[j]>maxi)maxi=nums[j]; else if(nums[j]<min...
// O(n^3) time | O(1) space var subArrayRanges = function(nums) { let res = 0 for (let i = 1; i < nums.length; i++) { for (let j = 0; j < i; j++) { let smallest = nums[i], biggest = nums[i] for (let k = j; k < i; k++) { smallest = Math.min(smallest, nums[k]) ...
Sum of Subarray Ranges
You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the ith token face up, l...
class Solution: def bagOfTokensScore(self, tokens, power): tokens.sort() n = len(tokens) i, j = 0, n while i < j: if tokens[i] <= power: power -= tokens[i] i += 1 elif i - (n - j) and j > i + 1: j -= 1 ...
class Solution { public int bagOfTokensScore(int[] tokens, int power) { //initially score is 0, that's why in these conditions, return 0. if(tokens.length == 0 || power < tokens[0]) return 0; Arrays.sort(tokens); //sort the array int i = 0; ...
class Solution { public: int bagOfTokensScore(vector<int>& tokens, int power) { sort(tokens.begin(),tokens.end()); int start=0,end=tokens.size()-1,score=0,ans=0; while(start<=end){ if(power>=tokens[start]){ ans=max(ans,++score); power-=tokens[start...
var bagOfTokensScore = function(tokens, power) { const n = tokens.length; tokens.sort((a, b) => a - b); let maxScore = 0; let currScore = 0; let left = 0; let right = n - 1; while (left <= right) { const leftPower = tokens[left]; const rightPower = tokens[...
Bag of Tokens
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three. &nbsp; Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 Explanation: S...
class Solution: def maxSumDivThree(self, nums: List[int]) -> int: dp = [0, float('-inf'), float('-inf')] for x in nums: dp_cp = dp[:] for left in range(3): right = (left + x) % 3 dp[right] = max(dp_cp[right], dp_cp[left] + x) return dp...
class Solution { public int maxSumDivThree(int[] nums) { int r0 = 0; int r1 = 0; int r2 = 0; for (int i = 0; i < nums.length; i++) { int nr0 = r0; int nr1 = r1; int nr2 = r2; int a = r0 + nums[i]; int b = r1 + nums[i]; ...
class Solution { public: int maxSumDivThree(vector<int>& nums) { vector<int> twos = {(int)1e4+1, (int)1e4+1}, ones = {(int)1e4+1, (int)1e4+1}; int res = 0; for(int i: nums) { if(i%3 == 2) { if(i <= twos[0]) { twos[1] = twos[0], twos[0] = i; ...
var maxSumDivThree = function(nums) { // there are 3 options for how the sum fit's into 3 via mod % 3 // track those 3 options via indices in the dp array // dp[0] = %3 === 0 // dp[1] = %3 === 1 // dp[2] = %3 === 2 let dp = new Array(3).fill(0); for (let num of nums) { for (let i of ...
Greatest Sum Divisible by Three
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats ...
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo = 0 hi = len(people)-1 boats = 0 while lo <= hi: if people[lo] + people[hi] <= limit: lo += 1 hi -= 1 else: ...
class Solution { public int numRescueBoats(int[] people, int limit) { int boatCount = 0; Arrays.sort(people); int left = 0; int right = people.length - 1; while(left <= right){ int sum = people[left] + people[right]; if(sum <= limit){ ...
// πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰Please upvote if it helps πŸ˜‰πŸ˜‰πŸ˜‰πŸ˜‰ class Solution { public: int numRescueBoats(vector<int>& people, int limit) { // sort vector sort(people.begin(),people.end()); int i = 0, j = people.size() - 1,cnt = 0; while(i <= j) { ...
/** * @param {number[]} people * @param {number} limit * @return {number} */ var numRescueBoats = function(people, limit) { people = people.sort((a,b) => a - b) let left = 0 let right = people.length - 1 let res = 0 while (left <= right) { if (people[left] + people[right] <= limit) ...
Boats to Save People
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). &nbsp; Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1...
class Solution: def maxProduct(self, nums: List[int]) -> int: # mx1 - max element, mx2 - second max element mx1 = nums[0] if nums[0] > nums[1] else nums[1] mx2 = nums[1] if nums[0] > nums[1] else nums[0] for num in nums[2:]: if num > mx1: mx1, mx2 = num, m...
class Solution { public int maxProduct(int[] nums) { int max = Integer.MIN_VALUE; int maxi = -1; for (int i = 0; i < nums.length; ++i) { if (nums[i] > max) { max = nums[i]; maxi = i; } } nums[maxi] = Integer.MIN_VALUE; ...
class Solution { public: int maxProduct(vector<int>& nums) { int n = nums.size(); sort(nums.begin(), nums.end()); return (nums[n -1]-1)* (nums[n-2]-1); } };
var maxProduct = function(nums) { let val = []; for(let i=0; i<nums.length; i++){ for(let j=i+1; j<nums.length; j++){ val.push((nums[i]-1)*(nums[j]-1)) } } return Math.max(...val) };
Maximum Product of Two Elements in an Array
We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again...
class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: # make sure left and right are not empty without changing the answer left.append(0) right.append(n) return max(max(left), n - min(right))
class Solution { public int getLastMoment(int n, int[] left, int[] right) { int max = 0; for (int i = 0; i < left.length; i++) { if (left[i] > max) max = left[i]; } for (int i = 0; i < right.length; i++) { if (n - right[i] > max) ...
class Solution { public: int getLastMoment(int n, vector<int>& left, vector<int>& right) { int mx=0; for(auto&i:left)mx=max(mx,i); for(auto&i:right)mx=max(mx,n-i); return mx; } };
var getLastMoment = function(n, left, right) { const maxLeft = Math.max(...left); const minRight = Math.min(...right); return Math.max(n - minRight, maxLeft); };
Last Moment Before All Ants Fall Out of a Plank
You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'. Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root. As a reminder, any shorter prefix of a string is lexicographically smaller. For example...
class Solution: res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13 def smallestFromLeaf(self, root: TreeNode) -> str: def helper(node: TreeNode, prev): prev = chr(97 + node.val) + prev if not node.left and not node.right: ...
class Solution { String result = null; public String smallestFromLeaf(TreeNode root) { build(root, new StringBuilder()); return result; } public void build(TreeNode root, StringBuilder str) { if (root == null) return; StringBuilder sb = new StringBuilder(str).insert(0, ...
/** * 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 smallestFromLeaf = function(root) { if(root === null) return ''; let queue = [[root, ''+giveCharacter(root.val)]]; let leafLevelFound = false; let possibleSmallString = []; while(queue.length > 0){ let currentLevelLength = queue.length; f...
Smallest String Starting From Leaf
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length &gt;= 3 There exists some i with 0 &lt; i &lt; arr.length - 1 such that: arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1] ...
# """ # This is MountainArray's API interface. # You should not implement it, or speculate about its implementation # """ #class MountainArray: # def get(self, index: int) -> int: # def length(self) -> int: class Solution: def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: ...
class Solution { public int findInMountainArray(int target, MountainArray mountainArr) { int peak = findPeak(mountainArr); int left =binary(0,peak,mountainArr,target,true); if(left!=-1){ return left; } int right= binary(peak+1,mountainArr.leng...
/** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * class MountainArray { * public: * int get(int index); * int length(); * }; */ class Solution { public: //----------------------- find peak --------------------------------------- ...
/** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * function MountainArray() { * @param {number} index * @return {number} * this.get = function(index) { * ... * }; * * @return {number} * this.length = fu...
Find in Mountain Array
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1. Each node has a score. To find the score of a node, consider if t...
class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: graph = collections.defaultdict(list) for node, parent in enumerate(parents): # build graph graph[parent].append(node) n = len(parents) # total number of nodes d = collec...
class Solution { long max = 0, res = 0; public int countHighestScoreNodes(int[] parents) { Map<Integer, List<Integer>> hm = new HashMap(); for(int i = 0; i < parents.length; i++) { // build the tree hm.computeIfAbsent(parents[i], x ->new ArrayList<>()).add(i); } dfs...
class Solution { public: // Steps : // 1 - For each node, you need to find the sizes of the subtrees rooted in each of its children. // 2 - How to determine the number of nodes in the rest of the tree? // Can you subtract the size of the subtree rooted at the node from the total number of...
var countHighestScoreNodes = function(parents) { const n = parents.length; const adj = []; for (let i = 0; i < n; ++i) { adj[i] = []; } for (let i = 1; i < n; ++i) { const parent = parents[i]; adj[parent].push(i); } let maxProd = 0; let maxCount = ...
Count Nodes With the Highest Score
We run a&nbsp;preorder&nbsp;depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.&nbsp; If the depth of a node is D, the depth of its immediate child is D + 1.&nbsp; The depth of the root nod...
class Solution: def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: i = 0 dummy_head = TreeNode() depth = 0 while i < len(traversal): if traversal[i].isdigit(): value, i = get_value(traversal, i) insert_node(dummy_head, dep...
class Solution { public TreeNode recoverFromPreorder(String traversal) { if(!traversal.contains("-")) return new TreeNode(Integer.parseInt(traversal)); String number = ""; int i = 0; while(traversal.charAt(i)!='-'){ number+=traversal.charAt(i); i++...
class Solution { public: // Returns the index of '-' if present otherwise returns the string length int findIndex(int ind, string &traversal){ int req = traversal.size(); for(int i=ind; i<traversal.size(); i++){ if(traversal[i] == '-'){ req = i; break...
var recoverFromPreorder = function(traversal) { let n = traversal.length; // Every layer in dfs handles the depth+1 of '-' only. // ex: // depth=0 -> find '-' as splitter // depth=1 -> find '--' as splitter // depth=2 -> find '---' as splitter let dfs = (str,depth)=>{ ...
Recover a Tree From Preorder Traversal
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position, you c...
class Solution: def getMaximumGold(self, grid): answer = [0] def visit(visited, i, j, gold_sum): val = grid[i][j] if val == 0 or (i,j) in visited: answer[0] = max(answer[0], gold_sum) return gold_sum_new = gold_sum + val ...
class Solution { int r = 0; int c = 0; int max = 0; public int getMaximumGold(int[][] grid) { r = grid.length; c = grid[0].length; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(grid[i][j] != 0) { dfs(grid, i, j, 0); ...
class Solution { public: int maxgold=0; int m,n; void gold(int i,int j,vector<vector<int>>& grid,vector<vector<int>>& vis,int count){ // Down if(i+1<m && !vis[i+1][j] && grid[i+1][j]){ vis[i][j]=1; gold(i+1,j,grid,vis,count+grid[i+1][j]); vis[i][j]=0; } //...
var getMaximumGold = function(grid) { let max = 0; // This is our internal dfs function that will search all possible directions from a cell const mine = (x, y, n) => { // We can't mine any gold if the position is out of the grid, or the cell doesnt have any gold if (x < 0 || y < 0 || x > gri...
Path with Maximum Gold
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. &nbsp; Example 1: Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1...
class Solution: def countSmaller(self, nums: List[int]) -> List[int]: # build the binary indexed tree num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0 tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1 ...
class Solution { public List<Integer> countSmaller(int[] nums) { int min = 20001; int max = -1; for (int num : nums) { min = Math.min(min, num); max = Math.max(max, num); } min--; int[] count = new int[max-min+1]; Integer[]...
typedef struct _SmallerValueCount { _SmallerValueCount(const int &value, const int &originalIndex) : mValue(value), mOriginalIndex(originalIndex) {} int mValue = 0; int mOriginalIndex = 0; } SmallerValueCount; class Solution { public: vector<int> countSmaller(vector<int>& nums) { v...
var countSmaller = function(nums) { if(nums===null || nums.length == 0) return [] let N = nums.length const result = new Array(N).fill(0) const numsWithIdx = new Array(N).fill(0) for(let i = 0; i < nums.length; i++) { const curr = nums[i] numsWithIdx[i] = {val:curr...
Count of Smaller Numbers After Self
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. &nbsp; Example 1: Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]] Example 2: Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]] &nbsp...
class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: if not mat or not mat[0]: return [] m, n = len(mat), len(mat[0]) queue = deque() MAX_VALUE = m * n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE. ...
class Solution { // BFS // We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it. boolean visited[][]; // Could also convert the indexes to a single numbe...
class Solution { bool isValid(vector<vector<int>>& grid,int r,int c,int nr,int nc,int m,int n){ if(nr>=0 && nc>=0 && nr<m && nc<n && grid[nr][nc]==-1){ if(grid[r][c]==0) grid[nr][nc]=1; else grid[nr][nc]=grid[r][c]+1; return 1; } ...
/** * @param {number[][]} mat * @return {number[][]} */ var updateMatrix = function(mat) { const rows = mat.length, cols = mat[0].length; if (!rows) return mat; const queue = new Queue(); const dist = Array.from({length: rows}, () => new Array(cols).fill(Infinity)); for (let i = 0; i < row...
01 Matrix
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. &nbsp; Example 1: Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] Output: true Explanation: We can rotate mat 90 degrees clockwise to make mat equal...
class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: # if already equal if target == mat: return True # there are 4 different rotation with 90 deg. # We need to check at most 3 more rotation. for i in range(3): ...
class Solution { public boolean findRotation(int[][] mat, int[][] target) { if (mat == target) return true; int n = mat.length; int[] res[] = new int[n][n]; for (int i = 0; i < n; i++) { //clockwise 90 for (int j = 0; j < n; j++) { res[i][j] = mat[n - 1 - ...
class Solution { public: bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) { int n = mat.size(); if(mat == target) { // rotation by 0 degree. return true; } int deg = 3; // more rotations with 90, 180, 270 degree's. while(deg --) { ...
var findRotation = function(mat, target) { let width = mat[0].length; let height = mat.length; let normal = true; let rightOneTime = true; let rightTwoTimes = true; let rightThreeTimes = true; for (let i = 0; i < height; i++) { for (let j = 0; j < width; j++) { // d...
Determine Whether Matrix Can Be Obtained By Rotation
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. If isWater[i][j] == 0, cell (i, j) is a land cell. If isWater[i][j] == 1, cell (i, j) is a water cell. You must assign each cell a height in a way that follows these rules: The height of each cell must be non-n...
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: arr = collections.deque() m, n = len(isWater), len(isWater[0]) for i in range(m): for j in range(n): if isWater[i][j] == 1: arr.append((0, i, j)) ...
class Solution { static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; int rows; int cols; int[][] isWater; public int[][] highestPeak(int[][] isWater) { this.isWater = isWater; rows = isWater.length; cols = isWater[0].length; ...
class Solution { public: vector<vector<int>> highestPeak(vector<vector<int>>& isWater) { int r = isWater.size(); int c = isWater[0].size(); queue <pair<int,int>> curr; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { //set the land cell to -1 ...
var highestPeak = function(isWater) { const RN = isWater.length, CN = isWater[0].length; const output = [...Array(RN)].map(() => Array(CN).fill(-1)); const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]] let queue = [] for(let r = 0; r < RN; r++) { for(let c = 0; c < CN; c++) { if(isWa...
Map of Highest Peak
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location...
class Solution: def isPathCrossing(self, path: str) -> bool: c = set() x,y = 0,0 c.add((x,y)) for i in path: if i == 'N': y+=1 elif i == 'E': x+=1 elif i == 'W': x-=1 else: ...
// Path crossing // Leetcode class Solution { public boolean isPathCrossing(String path) { Set<String> visited = new HashSet<>(); int x = 0, y = 0; visited.add(x + "," + y); for (char c : path.toCharArray()) { if (c == 'N') y++; else if (c == 'S') y--; ...
class Solution { public: bool isPathCrossing(string path) { set<pair<int, int>>st; int x=0,y=0; st.insert({0, 0}); for(int i=0;i<path.length();i++){ if(path[i]=='N'){ x++; } else if(path[i]=='S'){ x--; ...
var isPathCrossing = function(path) { let set = new Set(); let curr = [0, 0] let start = `${curr[0]}, ${curr[1]}` set.add(start) for (let el of path) { if (el === 'N') curr[1]++; else if (el === 'S') curr[1]--; else if (el === 'E') curr[0]++; else curr[0]--;...
Path Crossing
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 &lt;= i &lt; pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of p...
#Hierholzer Algorithm from collections import defaultdict class Solution: def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]: G = defaultdict(list) din = defaultdict(int) dout = defaultdict(int) for v, w in pairs: G[v].append(w) dout[v] += 1...
class Solution { public int[][] validArrangement(int[][] pairs) { int n = pairs.length; int[][] ans = new int[n][2]; for (int[] a : ans) { a[0] = -1; a[1] = -1; } Map<Integer, Integer> outdegree = new HashMap<>(); Map<Integer,...
class Solution { public: vector<vector<int>> validArrangement(vector<vector<int>>& pairs) { int m = pairs.size(); // Eulerian Path unordered_map<int, stack<int>> adj; unordered_map<int, int> in; unordered_map<int, int> out; // reserve spaces for unordered_map may help...
var validArrangement = function(pairs) { let graph = {}; let degrees = {}; // outdegree: positive, indegree: negative for (var [x, y] of pairs) { if (!graph[x]) graph[x] = []; graph[x].push(y); if (degrees[x] === undefined) degrees[x] = 0; if (degrees[y] === undefined) degrees[y] = 0; degrees[...
Valid Arrangement of Pairs
There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another ...
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: def computeArrivalTime(curr_pos, curr_speed): nonlocal target return (target - curr_pos) / curr_speed # avoid integer division, as a car may arrive at 5.2s and another at 5.6s ...
class Solution { class pair implements Comparable<pair>{ int pos; double time; pair(int pos,double time){ this.pos=pos; this.time=time; } public int compareTo(pair o){ return o.pos-this.pos; } } public int carFleet(int targe...
class Solution { public: int carFleet(int target, vector<int>& position, vector<int>& speed) { int n = position.size(); vector<pair<int,int>> cars; for(int i=0; i<n; i++)cars.push_back({position[i], speed[i]}); sort(cars.begin(),cars.end()); ...
var carFleet = function(target, position, speed) { for (let i = 0 ; i < position.length ; i ++) { position[i] = [target - position[i], speed[i]] } position.sort((a, b) => { return a[0] - b[0] }) let count = 1, prev = position[0][0] / position[0][1] for (let i = 1 ; i < position.length ; i ++...
Car Fleet
You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot in...
class Solution: def maxValue(self, n: str, x: int) -> str: if int(n)>0: ans = "" flag = False for i in range(len(n)): if int(n[i])>=x: ans += n[i] else: a = n[:i] b = n[i:] ...
class Solution { public String maxValue(String n, int x) { StringBuilder res= new StringBuilder(); int i=0, j=0; if(n.charAt(0)=='-'){ res.append(n.charAt(0)); for(j=1; j<n.length(); j++){ char ch= n.charAt(j); int val= ch-'0'; ...
class Solution { public: string maxValue(string s, int x) { int p=0,flag=0; char ch='0'+x; //change int to char string str; if(s[0]=='-') { //for negative numbers for(int i=1;i<s.size();i++) { if(ch<s[i] && !flag){ str+=ch; str+=s[i]; ...
var maxValue = function(n, x) { let i; // if the number if positive, find the first // number that is less than x if (n[0] !== '-') { for (i = 0; i < n.length; i++) { if (Number(n[i]) < x) break; } // if the number is negative, find the first // number t...
Maximum Value after Insertion
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any...
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: res, N = [], len(pattern) for query in queries: if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N: res.append(False) else:...
class Solution { public List<Boolean> camelMatch(String[] queries, String pattern) { List<Boolean> list = new ArrayList<>(); for (var q : queries) { int index = 0; boolean flag = true; for (var c : q.toCharArray()) { if(index < pattern.length() && c == pattern.cha...
class Solution { public: vector<bool> camelMatch(vector<string>& queries, string pattern) { vector<bool> res(queries.size()); for (int i = 0; i < queries.size(); i++) { int patRef = 0; bool isCamel = true; for (const char& lt...
var camelMatch = function(queries, pattern) { function camelMatch(q, p){ let qlist=[] let plist=[] for(let a of q) if(a<='Z') qlist.push(a); for(let a of p) if(a<='Z') plist.push(a); return plist.join('') === qlist.join('') } function seqMatch(q, p){ if(!camel...
Camelcase Matching
You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English al...
class Solution: def decodeMessage(self, key: str, message: str) -> str: alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] i=0 d={} for j in key: if j!=" " and j not in d: d[j]=alpha[i] ...
class Solution { public String decodeMessage(String key, String message) { StringBuilder ans = new StringBuilder();//Using String Builder to append the string key = key.replaceAll(" ", ""); //Removing the spaces HashMap<Character,Character> letters = new HashMap<>(); //Mappin...
class Solution { public: string decodeMessage(string key, string message) { vector <char> alpha {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; int i=0; map<char,char> d; for(int j=0;j<26;j++){ d[alpha[j]]='0'; ...
var decodeMessage = function(key, message) { let result = '' key = Array.from(new Set(key.split(' ').join(''))) const hash = new Map() const alpha = 'abcdefghijklmnopqrstuvwxyz' for (let i = 0; i < alpha.length; i++) { hash.set(key[i], alpha[i]) } for (let chr of message) { result += hash.get(...
Decode the Message
Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Ret...
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: if len(arr) < k*m: return False n = len(arr) pattern = arr[0:m] repeats = 1 for i in range(m, n - m + 1, m): if arr[i:i+m] != pattern: break ...
// Time complexity: O(N) // Space complexity: O(1) class Solution { public boolean containsPattern(int[] arr, int m, int k) { int count = 0; for (int i = 0; i < arr.length - m; i++) { if (arr[i] == arr[i + m]) { count++; } else { count = 0; ...
class Solution { public: bool containsPattern(vector<int>& arr, int m, int k) { unordered_map<string, vector<int>> ump; string num = ""; for(int i = 0; i < arr.size(); ++i) num += to_string(arr[i]); for(int i = 0; i <= num.length() - m; ++i){ string str = num....
var containsPattern = function(arr, m, k) { const origin = arr.join(','); return arr.some((_, index, array) => { const check = arr.slice(index, m + index).join(',') + ','; index + k * m > arr.length && array.splice(index); const target = check.repeat(k).slice(0, -1); if (~origin.indexOf(target)) return true...
Detect Pattern of Length M Repeated K or More Times
Given an array of integers arr and an integer k. A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| &gt; |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] &gt; arr[j]. Return a list of the strongest k value...
class Solution: def getStrongest(self, arr: List[int], k: int) -> List[int]: n = len(arr) medInd = (n-1)//2 arr = sorted(arr) med = arr[medInd] start, end = 0, n-1 ans = [] while start <= end and len(ans) < k: if abs(med - arr[end]) < abs(...
class Solution { public int[] getStrongest(int[] arr, int k) { int[] result = new int[k]; int n = arr.length, left = 0, right = n - 1, idx = 0; Arrays.sort(arr); int median = arr[(n - 1) / 2]; while (left <= right) { int diff_l = Math.abs(arr[left] - median); ...
class Solution { public: vector<int> getStrongest(vector<int>& arr, int k) { int n=arr.size(); sort(arr.begin(),arr.end()); int m=arr[(n-1)/2]; priority_queue<pair<int,int>> pq; for(auto it: arr) { pq.push({abs(it-m),it}); } vector<in...
var getStrongest = function(arr, k) { // sort array so we can easily find median const sorted = arr.sort((a,b) => a-b) // get index of median const medianIndex = Math.floor(((sorted.length-1)/2)) // get median const median = sorted[medianIndex] // custom sort function following the paramete...
The k Strongest Values in an Array
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. &nbsp; Example 1: Input: nums = [2,3,-2,4] Outpu...
class Solution: def maxProduct(self, nums: List[int]) -> int: prod=1 maxprod=-100000000 for i in range(len(nums)): # traverse from L-R so that we get max prod*=nums[i] maxprod=max(maxprod,prod) if prod==0: prod=1 prod=1 fo...
class Solution { public int maxProduct(int[] nums) { int ans = Integer.MIN_VALUE; int m = 1; for(int i=0; i< nums.length; i++){ m*=nums[i]; ans = Math.max(m, ans); if(m == 0) m=1; } int n = 1; for(int i=nums.length-1; i>=0; i--){ ...
class Solution { public: int maxProduct(vector<int>& nums) { int n = nums.size(); int negPro = 1; int posPro = 1; int CHECK_ZERO = 0; int res = INT_MIN; for(int i = 0; i < n; i++) { if(nums[i] == 0) { posPro = 1; ...
/** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { const n = nums.length - 1; let ans = nums[0]; let l = 1, r = 1; for (let i = 0; i < nums.length; i++) { l = (l ? l : 1) * nums[i]; r = (r ? r : 1) * nums[n - i]; ans = Math.max(ans, Math.max(...
Maximum Product Subarray
Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. A subarray is a contiguous part of an array. &nbsp; Example 1: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], ...
class Solution: def subarraysDivByK(self, nums, k): n = len(nums) prefix_mod = 0 result = 0 # There are k mod groups 0...k-1. mod_groups = [0] * k mod_groups[0] = 1 for num in nums: # Take modulo twice to avoid negative remainders. pr...
class Solution { public int subarraysDivByK(int[] nums, int k) { HashMap<Integer,Integer> map = new HashMap<>(); int count = 0; int sum = 0; for(int i=0;i<nums.length;i++){ sum +=nums[i]; int rem =sum%k; if(rem <0){ rem = rem+k; // ...
class Solution { public: int subarraysDivByK(vector<int>& nums, int k) { // take an ans variable int ans = 0; // initialize a map of int, int and insert {0,1} as 0 occurs first time for sum unordered_map<int, int> mapp; mapp.insert({0,1}); // initialize presum = 0 and...
var subarraysDivByK = function(nums, k) { let count = 0; let map = new Map(); map.set(0, 1) let sum = 0; for(let i=0; i<nums.length; i++){ sum += nums[i]; let rem = sum%k; if(rem<0) rem += k; if(map.has(rem)){ count += map.get(rem) map.set(rem,...
Subarray Sums Divisible by K