algo_input
stringlengths 240
3.91k
| solution_py
stringlengths 10
6.72k
| solution_java
stringlengths 87
8.97k
| solution_c
stringlengths 10
7.38k
| solution_js
stringlengths 10
4.56k
| title
stringlengths 3
77
|
---|---|---|---|---|---|
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
| class Solution:
def partitionLabels(self, s: str) -> List[int]:
d = defaultdict(list)
for i, char in enumerate(s):
d[char].append(i)
nums = []
for v in d.values():
nums.append([v[0], v[-1]])
start = nums[0][0]
maxIndex = nums[0][1]
ans = []
for i in range(1, len(nums)):
if nums[i][0] <= maxIndex:
maxIndex = max(maxIndex, nums[i][1])
else:
ans.append(maxIndex - start + 1)
start = nums[i][0]
maxIndex = nums[i][1]
ans.append(maxIndex - start + 1)
# print(ans)
return ans | class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer>lr=new ArrayList<>();
HashMap<Character,Boolean>mp=new HashMap<>();
int count=0;
for(int i=0;i<s.length();i++){
if(!mp.containsKey(s.charAt(i))&&s.lastIndexOf(Character.toString(s.charAt(i)))!=i){
mp.put(s.charAt(i),true);
}
else if(mp.containsKey(s.charAt(i))&&s.lastIndexOf(Character.toString(s.charAt(i)))==i){
mp.remove(s.charAt(i));
}
if(mp.isEmpty()){
lr.add(count+1);
count=0;
}
else{
count++;
}
}
return lr;
}
} | class Solution {
public:
vector<int> partitionLabels(string s) {
unordered_map<char,int>mp;
// filling impact of character's
for(int i = 0; i < s.size(); i++){
char ch = s[i];
mp[ch] = i;
}
// making of result
vector<int> res;
int prev = -1;
int maxi = 0;
for(int i = 0; i < s.size(); i++){
maxi = max(maxi, mp[s[i]]);
if(maxi == i){
// partition time
res.push_back(maxi - prev);
prev = maxi;
}
}
return res;
}
}; | var partitionLabels = function(s) {
let last = 0, first = 0;
let arr = [...new Set(s)], ss = [];
let temp = '';
first = s.indexOf(arr[0]);
last = s.lastIndexOf(arr[0]);
for(let i = 1; i<arr.length; i++){
if(s.indexOf(arr[i]) < last){
if(last < s.lastIndexOf(arr[i])){
last = s.lastIndexOf(arr[i]);
}
}
else{
temp = s.slice(first,last+1);
ss.push(temp.length);
first = s.indexOf(arr[i]);
last = s.lastIndexOf(arr[i]);
}
}
temp = s.slice(first,last+1);
ss.push(temp.length);
return ss;
}; | Partition Labels |
Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 300
0 <= mat[i][j] <= 104
0 <= threshold <= 105
| class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
# prefix matrix
dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)]
for i in range(1, len(mat)+1):
for j in range(1, len(mat[0])+1):
dp[i][j] = dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1] + mat[i-1][j-1]
#bin search
max_side = 0
for i in range(1, len(mat) + 1):
for j in range(1, len(mat[0]) + 1):
if min(i, j) < max_side:
continue
left = 0
right = min(i,j)
while left <= right:
mid = (left+right)//2
pref_sum = dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid]
if pref_sum <= threshold:
max_side = max(max_side, mid)
left = mid + 1
else:
right = mid - 1
return max_side
| class Solution {
public int maxSideLength(int[][] mat, int threshold) {
int rows = mat.length;
int cols = mat[0].length;
int[][] preSum = new int[rows+1][cols+1];
for(int i=1;i<=rows;i++){
for(int j=1;j<=cols;j++){
preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + mat[i-1][j-1];
}
}
int lo=1,hi=Math.min(rows,cols);
while(lo<=hi){
int m = (lo+hi)>>1;
if(fun(preSum,threshold,rows,cols,m)) lo=m+1;
else hi=m-1;
}
return lo-1;
}
private boolean fun(int[][] preSum, int maxSum,int rows, int cols, int size){
for(int r=size;r<=rows;r++){
for(int c=size;c<=cols;c++){
int sum = preSum[r][c] - preSum[r-size][c] - preSum[r][c-size] + preSum[r-size][c-size];
if(sum <= maxSum) return true;
}
}
return false;
}
} | class Solution {
public:
int maxSideLength(vector<vector<int>>& mat, int threshold) {
int m = mat.size();
int n = mat[0].size();
int least = min (m,n);
vector<vector<int>> dp (m+1, vector<int> (n+1, 0));
/*
create dp matrix with sum of all squares
so for the following input matrix
1 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0
m = 4; n = 4; least = 4; threshold = 6
you get the dp matrix to be:
0 0 0 0 0
0 1 2 3 4
0 2 3 4 5
0 3 4 5 6
0 4 5 6 7
*/
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dp[i+1][j+1] = mat[i][j] + dp[i+1][j] + dp[i][j+1] - dp[i][j];
}
}
int sum = 0;
/*
from the previous example the once we start looking from least = 4 to see if the sum is less than threshold
for least = 4; sum = 7 - 0 - 0 + 0. (looking at the full 4 x 4 matrix) 7 is > threshold.. so keep looking..
for least = 3; sum = 5 - 0 - 0 + 0. (looking at the 3 x 3 matrix) .. 5 < threshold.. return 3.
say if the threshold was lower e.g. threshold = 2?
continuing...
for least = 3; sum = 6 - 3 - 0 + 0 = 3.
for least = 3; sum = 6 - 0 - 3 + 0 = 3;
for least = 3; sum = 7 - 4 - 4 + 1 = 0;
*/
for(int k = least; k > 0; k--) {
for(int i = k; i < m+1; i++) {
for(int j = k; j < n+1; j++) {
sum = dp[i][j] - dp[i-k][j] - dp[i][j-k] + dp[i-k][j-k];
if(sum <= threshold) {
return k;
}
}
}
}
return 0;
}
}; | /**
* @param {number[][]} mat
* @param {number} threshold
* @return {number}
*/
var maxSideLength = function(mat, threshold) {
const n = mat.length, m = mat[0].length;
// build sum matrix
let sum = [];
for(let i=0; i<=n; i++) {
sum.push(new Array(m+1).fill(0));
for(let j=0; j<=m; j++) {
if(i==0 || j==0) {
continue;
}
sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + mat[i-1][j-1];
}
}
// function to check square sum <= threshold
const underThreshold = function(len) {
for(let i=len; i<=n; i++) {
for(let j=len; j<=m; j++) {
if(sum[i][j] - sum[i-len][j] - sum[i][j-len] + sum[i-len][j-len] <= threshold) {
return true;
}
}
}
return false;
};
// binary search
let l=0, r=Math.min(n, m);
while(l<=r) {
const mid = Math.floor((l+r)/2);
if(underThreshold(mid)) {
l = mid+1;
} else {
r = mid-1;
}
}
return r;
}; | Maximum Side Length of a Square with Sum Less than or Equal to Threshold |
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Example 1:
Input: strs = ["aba","cdc","eae"]
Output: 3
Example 2:
Input: strs = ["aaa","aaa","aa"]
Output: -1
Constraints:
2 <= strs.length <= 50
1 <= strs[i].length <= 10
strs[i] consists of lowercase English letters.
| class Solution:
def findLUSlength(self, s: List[str]) -> int:
def lcs(X, Y):
m = len(X)
n = len(Y)
L = [[None]*(n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0 :
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1]+1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
return L[m][n]
k = 0
mp = {}
for i in s:
if len(i) not in mp:
mp[len(i)] = [i]
else:
mp[len(i)].append(i)
k = max(k , len(i))
t = k
while(k):
if k not in mp:
k -= 1
else:
curr = mp[k]
n = len(curr)
for i in range(n):
f = 0
for j in range(n):
if(i != j and curr[i] == curr[j]):
f = 1
break
if(not(f)):
ff = 0
for j in range(k+1 , t+1):
if(ff):break
if(j not in mp): continue
for jj in mp[j]:
if(lcs(curr[i] , jj) == len(curr[i])):
ff = 1
break
if(not(ff)):return len(curr[i])
k-=1
return -1
| class Solution {
public int findLUSlength(String[] strs) {
Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length
// store the frequency of all strings in array
Map<String,Integer> map = new HashMap<>();
for(String s : strs) map.put(s,map.getOrDefault(s,0)+1);
for(int i=0;i<strs.length;i++){
if(map.get(strs[i]) != 1) continue; // string is not unique
int j;
for(j=0;j<i;j++){
if(isSubsequence(strs[i],strs[j])) break;
}
// if it is not a subsequence of any other larger string
if(j == i) return strs[i].length();
}
return -1; // no string satisfies the criterion
}
public boolean isSubsequence(String a, String b){
int i=0,j=0;
while(i<a.length() && j<b.length())
if(a.charAt(i) == b.charAt(j++)) i++;
return i == a.length();
}
} | class Solution {
private:
bool isCommon(string &s,string &t){
int index=0;
for(int i=0;i<s.size();i++){
if(s[i]==t[index]){
if(++index==t.size()){
return true;
}
}
}
return false;
}
bool isUncommon(vector<string>&strs,int index){
for(int i=0;i<strs.size() and strs[index].size()<=strs[i].size();i++){
if(index!=i and isCommon(strs[i],strs[index])){
return false;
}
}
return true;
}
public:
int findLUSlength(vector<string>& strs) {
sort(strs.begin(),strs.end(),[](string &s,string &t){
return s.size()>t.size();
});
int ans=-1;
for(int i=0;i<strs.size();i++){
if(isUncommon(strs,i)){
ans=strs[i].size();
break;
}
}
return ans;
}
}; | var findLUSlength = function(strs) {
strs.sort((a, b) => b.length - a.length);
const isSubsequence = (a, b) => {
const A_LENGTH = a.length;
const B_LENGTH = b.length;
if (A_LENGTH > B_LENGTH) return false;
if (a === b) return true;
const matches = [...b].reduce((pos, str) => {
return a[pos] === str ? pos + 1 : pos;
}, 0);
return matches === A_LENGTH;
}
for (let a = 0; a < strs.length; a++) {
let isUncommon = true;
for (let b = 0; b < strs.length; b++) {
if (a === b) continue;
if (isSubsequence(strs[a], strs[b])) {
isUncommon = false;
break;
}
}
if (isUncommon) return strs[a].length;
}
return -1;
}; | Longest Uncommon Subsequence II |
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
Example 1:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
1 <= n <= 1690
| import heapq
class Solution:
def nthUglyNumber(self, n: int) -> int:
h1, h2, h3 = [], [], []
heapq.heappush(h1, 1)
heapq.heappush(h2, 1)
heapq.heappush(h3, 1)
ugly_number = 1
last_ugly_number = 1
count = 1
while count < n:
if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:
# pop from h1
x = heapq.heappop(h1)
ugly_number = 2 * x
if ugly_number == last_ugly_number:
# do nothing
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:
# pop from h2
x = heapq.heappop(h2)
ugly_number = 3 * x
if ugly_number == last_ugly_number:
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
else:
# pop from h3
x = heapq.heappop(h3)
ugly_number = 5 * x
if ugly_number == last_ugly_number:
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
return last_ugly_number | // Ugly number II
// https://leetcode.com/problems/ugly-number-ii/
class Solution {
public int nthUglyNumber(int n) {
int[] dp = new int[n];
dp[0] = 1;
int i2 = 0, i3 = 0, i5 = 0;
for (int i = 1; i < n; i++) {
dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5));
if (dp[i] == dp[i2] * 2) i2++;
if (dp[i] == dp[i3] * 3) i3++;
if (dp[i] == dp[i5] * 5) i5++;
}
return dp[n - 1];
}
} | class Solution {
public:
int nthUglyNumber(int n) {
int dp[n+1];
dp[1] = 1;
int p2 = 1, p3 = 1, p5 = 1;
int t;
for(int i = 2; i < n+1; i++){
t = min(dp[p2]*2, min(dp[p3]*3, dp[p5]*5));
dp[i] = t;
if(dp[i] == dp[p2]*2){
p2++;
}
if(dp[i] == dp[p3]*3){
p3++;
}
if(dp[i] == dp[p5]*5){
p5++;
}
}
return dp[n];
}
}; | var nthUglyNumber = function(n) {
let uglyNo = 1;
let uglySet = new Set(); // Set to keep track of all the ugly Numbers to stop repetition
uglySet.add(uglyNo);
let minHeap = new MinPriorityQueue(); // Javascript provides inbuilt min and max heaps, constructor does not require callback function for primitive types but a comparator callback for object data types, to know which key corresponds to the priority
//callback looks like this new MinPriorityQueue((bid) => bid.value)
// if this is confusing, check the documentation here
// https://github.com/datastructures-js/priority-queue/blob/master/README.md#constructor
while(n>1){
if(!uglySet.has(uglyNo*2)){// add only if the set does not have this ugly no.
minHeap.enqueue(uglyNo*2,uglyNo*2);// enqueue takes two inputs element and priority respectively, both are same here
uglySet.add(uglyNo*2);
}
if(!uglySet.has(uglyNo*3)){
minHeap.enqueue(uglyNo*3,uglyNo*3);
uglySet.add(uglyNo*3);
}
if(!uglySet.has(uglyNo*5)){
minHeap.enqueue(uglyNo*5,uglyNo*5);
uglySet.add(uglyNo*5);
}
uglyNo = minHeap.dequeue().element;//dequeue returns an object with two properties priority and element
n--;
}
return uglyNo;
}; | Ugly Number II |
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are unique.
nums is an ascending array that is possibly rotated.
-104 <= target <= 104
| class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l<=r:
mid = (l+r)//2
if target == nums[mid]:
return mid
if nums[l]<=nums[mid]:
if target > nums[mid] or target<nums[l]:
l = mid + 1
else:
r = mid - 1
else:
if target < nums[mid] or target > nums[r]:
r = mid - 1
else:
l = mid + 1
return -1 | class Solution {
public int search(int[] nums, int target) {
int pivot = findPivot(nums);
int ans = binarySearch(nums, target, 0, pivot);
if(ans!=-1){
return ans;
}
return binarySearch(nums, target, pivot+1, nums.length-1);
}
public int findPivot(int[] arr){
int start = 0, end = arr.length-1;
while(start<=end){
int mid = start + (end-start)/2;
if(mid<end && arr[mid]>arr[mid+1]){
return mid;
}
if(mid>start && arr[mid-1]>arr[mid]){
return mid-1;
}
if(arr[mid]<=arr[start]){
end = mid-1;
}else{
start = mid+1;
}
}
return -1;
}
public int binarySearch(int[] arr, int target, int start, int end){
while(start<=end){
int mid = start+ (end-start)/2;
if(target<arr[mid]){
end = mid-1;
}else if(target>arr[mid]){
start = mid+1;
}else{
return mid;
}
}
return -1;
}
} | class Solution
{
public:
int search(vector<int>& nums, int target)
{
int n=nums.size()-1;
if(nums[0]==target)
return 0;
if(nums.size()==1)
return -1;
// find the index of the minimum element ie pivot
int pivot=-1;
int low=0;
int high=n;
while(low<=high)
{
int mid=(low+high)/2;
if(mid==0)
{
if(nums[mid]< nums[mid+1] && nums[mid]< nums[n])
{
pivot=mid;
break;
}
else
{
low=mid+1;
}
}
else if(mid==n)
{
if(nums[mid] < nums[0] && nums[mid] < nums[mid-1])
{
pivot=mid;
break;
}
else
{
high=mid-1;
}
}
else if(nums[mid]<nums[mid+1] && nums[mid]<nums[mid-1])
{
pivot=mid;
break;
}
else if(nums[mid]>=nums[0] && nums[mid]<=nums[n])
high=mid-1;
else if(nums[mid] >= nums[0])
low=mid+1;
else if(nums[mid] < nums[0])
high=mid-1;
}
cout<<pivot<<endl;
if(target < nums[0])
{
int low1=pivot;
int high1=n;
while(low1<=high1)
{
int mid1=(low1+high1)/2;
if(nums[mid1]==target)
return mid1;
else if(nums[mid1] > target)
high1=mid1-1;
else if(nums[mid1]<target)
low1=mid1+1;
}
}
if(target > nums[0])
{
int low2=0;
int high2=pivot-1;
if(pivot==0)
{
low2=0;
high2=n;
}
while(low2<=high2)
{
int mid2=(low2+high2)/2;
if(nums[mid2]==target)
return mid2;
else if(nums[mid2] > target)
high2=mid2-1;
else if(nums[mid2]<target)
low2=mid2+1;
}
}
return -1;
}
}; | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
const len = nums.length;
if (len === 1 && nums[0] === target) return 0;
const h = nums.findIndex((val, i) => nums[i === 0 ? nums.length - 1 : i - 1] > val);
if (h !== 0) nums = nums.slice(h).concat(nums.slice(0, h));
// console.log(h, nums)
let lo = 0, hi = len - 1;
while (lo !== hi) {
if (lo + 1 === hi) {
if (nums[lo] === target) return (lo + h) % len;
if (nums[hi] === target) return (hi + h) % len;
break;
}
const i = Math.floor((lo + hi + 1) / 2);
// console.log(lo, hi, i)
const val = nums[i];
if (val === target) return (i + h) % len;
if (val > target) hi = i;
else lo = i;
}
return -1;
}; | Search in Rotated Sorted Array |
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:
Only the space character ' ' is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
Example 1:
Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:
Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" ('-' is read, so the result should be negative)
^
Step 3: " -42" ("42" is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:
Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
Constraints:
0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
| class Solution:
def assign_sign(self, sign):
# verify that we haven't already got a sign
# "+42-" -> we don't want to return -42; hence check
if not self.is_neg and not self.is_pos:
# no sign has been set yet
if sign=="+":
self.is_pos = True
elif sign=="-":
self.is_neg = True
return
def add_to_int(self, num):
if not self.num:
self.num = num
else:
self.num = (self.num*10) + num
def myAtoi(self, s: str) -> int:
# remove the leading and trailing spaces
self.is_neg = False
self.is_pos = False
self.num = None
s=s.strip()
for i in s:
# ignore the rest of the string if a non digit character is read
if i in ("+","-"):
# only read the first symbol; break if second symbol is read
if self.is_pos or self.is_neg or isinstance(self.num, int):
# one of the two symbols is read or a number is read
break
self.assign_sign(i)
continue
try:
i = int(i)
self.add_to_int(i)
except ValueError:
# it's neither a sign, nor a number; terminate
break
# outside the loop; compile the result
if not self.num:
return 0
upper_limit = 2**31 - 1
if self.is_pos or (not self.is_pos and not self.is_neg):
if self.num > upper_limit:
self.num = upper_limit
elif self.is_neg:
if self.num > upper_limit+1:
self.num = upper_limit+1
self.num = -1 * self.num
return self.num | class Solution {
public int myAtoi(String s) {
long n=0;
int i=0,a=0;
s=s.trim();
if(s.length()==0)
return 0;
if(s.charAt(i)=='+' || s.charAt(i)=='-')
a=1;
while(a<s.length())
if(s.charAt(a)=='0')
a++;
else
break;
for(i=a;i<a+11 && i<s.length();i++)
{
if(s.charAt(i)>='0' && s.charAt(i)<='9')
n=n*10+(int)(s.charAt(i)-'0');
else
break;
}
if(s.charAt(0)=='-')
n=-n;
if(n>2147483647)
n=2147483647;
if(n<-2147483648)
n=-2147483648;
return (int)n;
}
} | class Solution
{
public:
int myAtoi(string s)
{
long long ans = 0;
int neg = 1;
int i = 0;
while (i < s.length() and s[i] == ' ')
{
i++;
}
if (s[i] == '-' || s[i] == '+')
{
neg = s[i] == '-' ? -1 : 1;
i++;
}
while (i < s.length() && (s[i] >= '0' && s[i] <= '9'))
{
ans = ans *10 + (s[i] - '0');
// ans *= 10;
i++;
if (ans * neg >= INT_MAX) return INT_MAX;
if (ans * neg <= INT_MIN) return INT_MIN;
}
return ans * neg;
}
}; | const toNumber = (s) => {
let res = 0;
for (let i = 0; i < s.length; i++) {
res = res * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));
}
return res
}
var myAtoi = function(s) {
s = s.trim();
let r = s.match(/^(\d+|[+-]\d+)/);
if (r) {
let m = r[0], res;
switch (m[0]) {
case "-":
res = toNumber(m.slice(1)) * -1;
break;
case '+':
res = toNumber(m.slice(1));
break;
default:
res = toNumber(m);
break;
}
if (res < (1 << 31)) return (1 << 31);
if (res > -(1 << 31) - 1) return -(1 << 31) - 1;
return res;
}
return 0;
}; | String to Integer (atoi) |
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
| class Solution:
def canJump(self, nums: List[int]) -> bool:
"""
# Memoization + DFS Solution
# TLE as we have as much as n decisions depending on nums[i] which could be
# 10^5 as an uppercase according to problem constraints
# better off with a greedy approach
cache = {} # i : bool
def dfs(i):
if i == len(nums) -1:
return True
if nums[i] == 0:
return False
if i in cache:
return cache[i]
for j in range(1, nums[i] + 1):
res = dfs(i + j)
if res:
cache[i] = True
return cache[i]
cache[i] = False
return cache[i]
return dfs(0)
"""
# Greedy Solution
# Key with greedy is to find a local and gobal optimum
# here we find the furthest distance we can travel with each index
# futhest index reachable
reachable = 0
# iterate through all indexes and if the current index is futher than what we can travel return fasle
for i in range(len(nums)):
if i > reachable:
return False
reachable = max(reachable, nums[i] + i)
# if the futherest distance we can jump to is greater or equal than the last index break
if reachable >= len(nums) - 1:
break
return True | class Solution {
public boolean canJump(int[] nums)
{
int maxjump = 0;
for(int i=0;i<nums.length;i++)
{
// If the current index 'i' is less than current maximum jump 'curr'. It means there is no way to jump to current index...
// so we should return false
if(maxjump<i)
return false;
else
maxjump = Math.max(maxjump,nums[i]+i); // Update the current maximum jump...
}
return true;
}
}
//nums[i]+1 gives themax jump index possible from i | class Solution {
public:
bool canJump(vector<int>& nums) {
int ans = nums[0];
if(nums.size()>1&&ans==0) return false;
for(int i=1; i<nums.size(); i++){
ans = max(ans-1,nums[i]);
if(ans<=0&&i!=nums.size()-1) return false;
}
return true;
}
}; | var canJump = function(nums) {
let target = nums.length-1;
let max = 0,index = 0;
while(index <= target){
max = Math.max(max,index + nums[index]);
if(max >= target) return true;
if(index >= max && nums[index] === 0) return false;
index++;
}
return false;
}; | Jump Game |
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
| class Solution(object):
def combinationSum2(self, candidates, target):
res = []
def dfs(nums,summ,curr):
if summ>=target:
if summ == target:
res.append(curr)
return
for i in range(len(nums)):
if i !=0 and nums[i]==nums[i-1]:
continue
dfs(nums[i+1:],summ+nums[i],curr+[nums[i]])
dfs(sorted(candidates),0,[])
return res | class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
// O(nlogn)
Arrays.sort(candidates);
boolean[] visited = new boolean[candidates.length];
helper(res, path, candidates, visited, target, 0);
return res;
}
private void helper(List<List<Integer>> res,
List<Integer> path, int[] candidates,
boolean[] visited, int remain, int currIndex
){
if (remain == 0){
res.add(new ArrayList<>(path));
return;
}
if (remain < 0){
return;
}
for(int i = currIndex; i < candidates.length; i++){
if (visited[i]){
continue;
}
if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){
continue;
}
int curr = candidates[i];
path.add(curr);
visited[i] = true;
helper(res, path, candidates, visited, remain - curr, i + 1);
path.remove(path.size() - 1);
visited[i] = false;
}
}
} | class Solution {
public:
vector<vector<int>> ans;vector<int> temp;
void f(vector<int>& nums,int target,int i){
if(target==0){
ans.push_back(temp);
return;
}
if(i>=nums.size())
return;
if(nums[i]<=target){
temp.push_back(nums[i]);
f(nums,target-nums[i],i+1);
temp.pop_back();
while(i<nums.size()-1 && nums[i]==nums[i+1]) i++;
f(nums,target,i+1);
}
else
f(nums,target,i+1);
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
f(candidates,target,0);
return ans;
}
}; | /**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
candidates.sort((a, b) => a - b);
const ans = [];
function dfs(idx, t, st) {
if (t === 0) {
ans.push(Array.from(st));
return;
}
for (let i = idx; i < candidates.length; i++) {
if (i > idx && candidates[i - 1] === candidates[i]) continue;
if (candidates[i] > t) break;
st.push(candidates[i]);
dfs(i + 1, t - candidates[i], st);
st.pop();
}
}
dfs(0, target, []);
return ans;
}; | Combination Sum II |
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104
| class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
deque = []
for i, num in enumerate(nums):
while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i]
deque.pop(0)
if deque: # compute the max sum we can get at index i
nums[i] = nums[deque[0]] + num
while(deque and nums[deque[-1]] < nums[i]):
# delet all the sequence that smaller than current sum, becaus there will never be
# considers ==> smaller than current sequence, and end before current sequence
deque.pop()
if nums[i] > 0: # if nums[i] < 0, it can't be a useful prefix sum
deque.append(i)
return max(nums) | class Solution {
public int constrainedSubsetSum(int[] nums, int k) {
int n=nums.length;
int[] dp=new int[n];
int res=nums[0];
Queue<Integer> queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap
Arrays.fill(dp,Integer.MIN_VALUE);
dp[0]=nums[0];
queue.offer(0);
for(int j=1;j<n;j++){
int i=Math.max(j-k,0); // get the furthest index possible
while(!queue.isEmpty() && queue.peek()<i) queue.poll(); // find the global max in the specified range for that particular j index
int idx=queue.peek();
dp[j]=Math.max(dp[idx]+nums[j],nums[j]);
res=Math.max(res,dp[j]);
queue.offer(j);
}
return res;
}
} | class Solution {
public:
int constrainedSubsetSum(vector<int>& nums, int k) {
priority_queue<array<int, 2>> que;
int ret = nums[0], curr;
que.push({nums[0], 0});
for (int i = 1; i < nums.size(); i++) {
while (!que.empty() && que.top()[1] < i - k) {
que.pop();
}
curr = max(0, que.top()[0]) + nums[i];
ret = max(ret, curr);
que.push({curr, i});
}
return ret;
}
}; | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var constrainedSubsetSum = function(nums, k) {
const queue = [[0, nums[0]]];
let max = nums[0];
for (let i = 1; i < nums.length; i++) {
const cur = queue.length ? nums[i] + Math.max(0, queue[0][1]) : nums[i];
max = Math.max(max, cur);
while(queue.length && queue[queue.length-1][1] < cur) queue.pop();
queue.push([i, cur]);
while(queue.length && queue[0][0] <= i-k) queue.shift();
}
return max;
}; | Constrained Subsequence Sum |
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.
Return abs(i - start).
It is guaranteed that target exists in nums.
Example 1:
Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
Example 2:
Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
Example 3:
Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 104
0 <= start < nums.length
target is in nums.
| class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
if nums[start] == target: return 0
left, right = start-1, start+1
N = len(nums)
while True:
if left >=0 and nums[left] == target:
return start - left
if right < N and nums[right] == target:
return right - start
left -= 1
right += 1 | class Solution {
public int getMinDistance(int[] nums, int target, int start) {
int ans = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
ans = Math.min(ans, Math.abs(i - start));
}
}
return ans;
}
} | class Solution{
public:
int getMinDistance(vector<int>& nums, int target, int start){
int ans = INT_MAX;
for(int i = 0; i < nums.size(); i++){
int temp = 0;
if (nums[i] == target){
temp = abs(i - start);
if (temp < ans){
ans = temp;
}
}
}
return ans;
}
}; | var getMinDistance = function(nums, target, start) {
let min = Infinity;
for(let i=nums.indexOf(target);i<nums.length;i++){
if(nums[i]===target){
if(Math.abs(i-start)<min) min = Math.abs(i-start);
}
}
return min;
}; | Minimum Distance to the Target Element |
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Return the number of boomerangs.
Example 1:
Input: points = [[0,0],[1,0],[2,0]]
Output: 2
Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
Example 2:
Input: points = [[1,1],[2,2],[3,3]]
Output: 2
Example 3:
Input: points = [[1,1]]
Output: 0
Constraints:
n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
All the points are unique.
| class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
def sq(a):
return a * a
def euclid(a, b, c, d):
dist = sq(a - c) + sq(b - d)
return sq(dist)
n = len(points)
res = 0
for i in range(n):
count = defaultdict(lambda : 0)
for j in range(n):
d = euclid(points[i][0], points[i][1], points[j][0], points[j][1])
res += count[d] * 2
count[d] += 1
return res | class Solution {
public int numberOfBoomerangs(int[][] points) {
int answer = 0;
for (int p=0; p<points.length;p++) {
int[] i = points[p];
HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
for (int q=0;q<points.length;q++) {
if (q==p) {
continue;
}
int[] j = points[q];
double distance = Math.sqrt(Math.pow(j[0]-i[0], 2) + Math.pow(j[1]-i[1], 2));
if (distance > 0) {
if (hm.containsKey(distance)) {
hm.put(distance, hm.get(distance) + 1);
} else {
hm.put(distance, 1);
}
}
}
for (Double dist : hm.keySet()) {
int occ = hm.get(dist);
if (occ > 1) {
answer = answer + ((occ) * (occ - 1));
}
}
}
return answer;
}
} | class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
int cnt = 0, n = points.size();
for(int i = 0; i < n; i++)
{
map<int, int> mp;
for(int j = 0; j < n; j++)
{
if(i == j)
continue;
int tmp = findDistance(points[i], points[j]);
if(mp.find(tmp) != mp.end())
cnt += mp[tmp] * 2; // 2 is multiplied bcoz the order of j & k can be k & j also
mp[tmp]++;
}
}
return cnt;
}
int findDistance(vector<int> &p1, vector<int> &p2)
{
return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
}
}; | var numberOfBoomerangs = function(points) {
const POINTS_LEN = points.length;
let result = 0;
for (let i = 0; i < POINTS_LEN; i++) {
const hash = new Map();
for (let j = 0; j < POINTS_LEN; j++) {
if (i === j) continue;
const [x1, y1] = points[i];
const [x2, y2] = points[j];
const dis = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
const value = hash.get(dis) ?? 0;
if (value > 0) result += value * 2;
hash.set(dis, value + 1);
}
}
return result;
}; | Number of Boomerangs |
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:
Input: n = 1, edges = []
Output: [0]
Example 3:
Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints:
1 <= n <= 3 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
The given input represents a valid tree.
| from typing import List
ROOT_PARENT = -1
class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
"""
@see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N)
:param n:
:param edges:
:return:
"""
g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree
root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)
# considering "root" as starting node, we create a tree.
# Now defining,
# tree_nodes[i] = number of nodes in the tree rooted at node i
# distances[i] = sum of distances of all nodes from ith node to all the
# other nodes of the tree
tree_nodes, distances = [0] * n, [0] * n
def postorder(rt: int, parent: int):
"""
updating tree_nodes and distances from children of rt. To update them, we must know their
values at children. And that is why post order traversal is used
After the traversal is done,
tree_nodes[rt] = all the nodes in tree rooted at rt
distances[rt] = sum of distances from rt to all the nodes of tree rooted at rt
:param rt:
:param parent:
"""
tree_nodes[rt] = 1
for c in g[rt]:
if c != parent:
postorder(c, rt)
# adding number of nodes in subtree rooted at c to tree rooted at rt
tree_nodes[rt] += tree_nodes[c]
# moving to rt from c will increase distances by nodes in tree rooted at c
distances[rt] += distances[c] + tree_nodes[c]
def preorder(rt: int, parent: int):
"""
we start with "root" and update its children.
distances[root] = sum of distances between root and all the other nodes in tree.
In this function, we calculate distances[c] with the help of distances[root] and
that is why preorder traversal is required.
:param rt:
:param parent:
:return:
"""
for c in g[rt]:
if c != parent:
distances[c] = (
(n - tree_nodes[c]) # rt -> c increase this much distance
+
(distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance
)
preorder(c, rt)
postorder(root, ROOT_PARENT)
preorder(root, ROOT_PARENT)
return distances
@staticmethod
def create_undirected_graph(edges: List[List[int]], n: int):
"""
:param edges:
:param n:
:return: graph from edges. Note that this undirect graph is a tree. (Any node can be
picked as root node)
"""
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
return g | class Solution {
private Map<Integer, List<Integer>> getGraph(int[][] edges) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for(int[] edge: edges) {
graph.putIfAbsent(edge[0], new LinkedList<>());
graph.putIfAbsent(edge[1], new LinkedList<>());
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
return graph;
}
public int[] sumOfDistancesInTree(int n, int[][] edges) {
if(n < 2 || edges == null) {
return new int[]{0};
}
int[] countSubNodes = new int[n];
Arrays.fill(countSubNodes, 1);
int[] distances = new int[n];
Map<Integer, List<Integer>> graph = getGraph(edges);
postOrderTraversal(0, -1, countSubNodes, distances, graph);
preOrderTraversal(0, -1, countSubNodes, distances, graph, n);
return distances;
}
private void postOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map<Integer, List<Integer>> graph) {
List<Integer> children = graph.get(node);
for(int child: children) {
if(child != parent) {
postOrderTraversal(child, node, countSubNodes, distances, graph);
countSubNodes[node] += countSubNodes[child];
distances[node] += distances[child] + countSubNodes[child];
}
}
}
private void preOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map<Integer, List<Integer>> graph, int n) {
List<Integer> children = graph.get(node);
for(int child: children) {
if(child != parent) {
distances[child] = distances[node] + (n - countSubNodes[child]) - countSubNodes[child];
preOrderTraversal(child, node, countSubNodes, distances, graph, n);
}
}
}
}`` | /*
Finding sum of distance from ith node to all other nodes takes O(n), so it will take O(n^2)
if done naively to find distance for all.
x---------------------y
/ \ \
o o o
/ / \
o o o
Above is a graph where x and y are subtrees with them as the root. They both are neighbors
and are connected by an edge.
From x's POV
x
/ | \
o o y
/ \
o o
/ \
o o
From y's POV
y
/ \
x o
/ | / \
o o o o
/
o
As evident froma above, the tree structure looks different when we change the root of tree.
So even if we find the sum of distance for node 0 as root, the subanswers are actually not correct
for other nodes when they are the root of tree. The subanswers are only correct when node 0 is root,
since that is how it was computed.
We use something called re-rooting, this allows us to find a relation so that we can change the root of the tree
and use the answer from its neighbor to compute answer for it.
So if we compute the answer for node 0 as root, we can find the answers for its children, then those children can
be used to compute for their neighbors and so on.
For the 1st diagram:
distance[x] = sum(x) + sum(y) + count(y)
distance[x] is the overall sum of distance with root as x
sum(i) is the sum of distance of all the descendents for a subtree rooted at i
count(i) is the no. of descendent nodes in the subtree rooted at i
Now why count(y) ?
Consider a node z in subtree y, dist(x, z) = dist(y, z) + 1
So sum(y) already accounts for dist(y, z) and we just need to add 1
So if there are n_y nodes in the subtree, we need to add +1 that many times.
distance[x] = sum(x) + sum(y) + count(y) -----------------1
distance[y] = sum(y) + sum(x) + count(x) -----------------2
From (1) - (2)
distance[x] - distance[y] = count(y) - count(x) ----------3
distance[x] = distance[y] - count(x) + count(y)
Above relation can be used to find the answer for a neighbor, when the answer for
the other neighbor is known.
In our case, we can compute the answer for node 0 as root in one traversal of post order.
Then in another traversal with again root as 0, compute the answer for its children and from
them to their children nodes and so on.
distance[child] = distance[parent] - count(child) + (N - count(child))
Since we also know the no. of nodes in subtree with child as root, the remaining nodes = (N - count(child))
Re-rooting Ref: https://leetcode.com/problems/sum-of-distances-in-tree/solution/
TC: O(N)
SC: O(N)
*/
class Solution {
private:
int n = 0;
// subtree_distance[i] = Sum of distance to other nodes when the ith-node is root
vector<int> subtree_distance;
// subtree_count[i] = no. of nodes in the subtree with ith-node as root
vector<int> subtree_count;
public:
void postorder(int root, int parent, vector<vector<int>>& graph) {
// Perform DFS for the child nodes
for(auto child: graph[root]) {
// Avoid iterating to the parent, it will create a loop otherwise
if(child != parent) {
postorder(child, root, graph);
// Update the subtree count and sum of distance
subtree_count[root] += subtree_count[child];
// distance[X] = distance[X] + distance[Y] + n_Y
subtree_distance[root] += subtree_distance[child] + subtree_count[child];
}
}
}
void preorder(int root, int parent, vector<vector<int>>& graph) {
for(auto child: graph[root]) {
if(child != parent) {
// distance[child] = distance[parent] - count[child] + count(parent)
subtree_distance[child] = subtree_distance[root] - subtree_count[child] + (n - subtree_count[child]);
preorder(child, root, graph);
}
}
}
vector<int> reRootingSol(int n, vector<vector<int>>& edges) {
// create an undirected graph
vector<vector<int> > graph(n);
for(auto edge: edges) {
int src = edge[0], dst = edge[1];
graph[src].emplace_back(dst);
graph[dst].emplace_back(src);
}
this->n = n;
this->subtree_count.resize(n, 1);
this->subtree_distance.resize(n, 0);
// This computes the subtree sum and subtree node count when 0 is the root of graph
// Imagine looking at the graph from node 0's POV
postorder(0, -1, graph);
// Since we have computed the sum distance from node's POV, we can use that information
// to find the sum of distance from each node's POV i.e imagine looking at the graph from
// POV of each node
preorder(0, -1, graph);
return this->subtree_distance;
}
vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
return reRootingSol(n, edges);
}
}; | var sumOfDistancesInTree = function(n, edges) {
let graph = {};
for (let [start, end] of edges) {
if (!graph[start]) graph[start] = [];
if (!graph[end]) graph[end] = [];
graph[start].push(end);
graph[end].push(start);
}
let visited = new Set(), distanceFromZero = 0, totalChildren = {};
// Find the sum distance from node O to all other nodes and the total children of each node
function dfs(node, sum = 0) {
visited.add(node);
distanceFromZero += sum;
if (!graph[node]) return;
let child = 0;
for (let nextNode of graph[node]) {
if (visited.has(nextNode)) continue;
child += dfs(nextNode, sum + 1);
}
totalChildren[node] = child;
return child + 1;
}
dfs(0);
let dp = [distanceFromZero];
visited = new Set();
function findDistance(node) {
visited.add(node);
if (!graph[node]) return;
for (let nextNode of graph[node]) {
if (visited.has(nextNode)) {
dp[node] = dp[nextNode] + (n - 2);
break;
}
}
if (node !== 0 && totalChildren[node]) dp[node] -= totalChildren[node] * 2;
for (let nextNode of graph[node]) {
if (visited.has(nextNode)) continue;
else findDistance(nextNode);
}
}
findDistance(0);
return dp;
}; | Sum of Distances in Tree |
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:
0 if it is a batch of buy orders, or
1 if it is a batch of sell orders.
Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.
Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.
Example 1:
Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
Output: 6
Explanation: Here is what happens with the orders:
- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.
- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.
- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.
- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.
Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
Example 2:
Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
Output: 999999984
Explanation: Here is what happens with the orders:
- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.
- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.
- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.
- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.
Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).
Constraints:
1 <= orders.length <= 105
orders[i].length == 3
1 <= pricei, amounti <= 109
orderTypei is either 0 or 1.
| class Solution:
def getNumberOfBacklogOrders(self, orders):
b, s = [], []
heapq.heapify(b)
heapq.heapify(s)
for p,a,o in orders:
if o == 0:
heapq.heappush(b, [-p, a])
elif o == 1:
heapq.heappush(s, [p, a])
# Check "good" condition
while s and b and s[0][0] <= -b[0][0]:
a1, a2 = b[0][1], s[0][1]
if a1 > a2:
b[0][1] -= a2
heapq.heappop(s)
elif a1 < a2:
s[0][1] -= a1
heapq.heappop(b)
else:
heapq.heappop(b)
heapq.heappop(s)
count = sum([a for p,a in b]) + sum([a for p,a in s])
return count % (10**9 + 7) | class Solution {
PriorityQueue<Order> buyBackLog;
PriorityQueue<Order> sellBackLog;
static int MOD = 1_000_000_007;
public int getNumberOfBacklogOrders(int[][] orders) {
//max heap, heapify on price
buyBackLog = new PriorityQueue<Order>((a, b) -> (b.price - a.price));
//min heap, heapify on price
sellBackLog = new PriorityQueue<Order>((a, b) -> (a.price - b.price));
//handle all order
for(int[] order : orders){
int price = order[0];
int quantity = order[1];
int orderType = order[2];
if(orderType == 0){
//buy order
handleBuyOrder(new Order(price, quantity));
}else if(orderType == 1){
//sell order
handleSellOrder(new Order(price, quantity));
}
}
long counts = 0L;
//count buy backlog
while(!buyBackLog.isEmpty()){
counts += buyBackLog.remove().quantity;
counts %= MOD;
}
//count sell backlog
while(!sellBackLog.isEmpty()){
counts += sellBackLog.remove().quantity;
counts %= MOD;
}
return (int) (counts % MOD);
}
private void handleBuyOrder(Order buyOrder){
//just add buyorder, if there is no sell back log
if(sellBackLog.isEmpty()){
buyBackLog.add(buyOrder);
return;
}
while(!sellBackLog.isEmpty() && buyOrder.price >= sellBackLog.peek().price && buyOrder.quantity > 0){
//selloder with minumum price
Order sellOrder = sellBackLog.remove();
if(buyOrder.quantity >= sellOrder.quantity){
buyOrder.quantity -= sellOrder.quantity;
sellOrder.quantity = 0;
} else {
//decrement sell order, add remaining sellorder
sellOrder.quantity -= buyOrder.quantity;
sellBackLog.add(sellOrder);
buyOrder.quantity = 0;
}
}
//add reaming buyorder
if(buyOrder.quantity > 0){
buyBackLog.add(buyOrder);
}
}
private void handleSellOrder(Order sellOrder){
//just add sell order, if there is no buy backlog
if(buyBackLog.isEmpty()){
sellBackLog.add(sellOrder);
return;
}
while(!buyBackLog.isEmpty() && buyBackLog.peek().price >= sellOrder.price && sellOrder.quantity > 0){
//buy order with maximum price
Order buyOrder = buyBackLog.remove();
if(sellOrder.quantity >= buyOrder.quantity){
sellOrder.quantity -= buyOrder.quantity;
buyOrder.quantity = 0;
}else{
//decrement buy order quantity, add remaining buyorder
buyOrder.quantity -= sellOrder.quantity;
buyBackLog.add(buyOrder);
sellOrder.quantity = 0;
}
}
//add remaining sell order
if(sellOrder.quantity > 0){
sellBackLog.add(sellOrder);
}
}
}
class Order{
int price;
int quantity;
public Order(int price, int quantity){
this.price = price;
this.quantity = quantity;
}
} | class Solution {
public:
int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
int n = orders.size();
//0 - buy , 1 - sell;
priority_queue<vector<int>> buyBacklog;
priority_queue<vector<int> , vector<vector<int>> , greater<vector<int>>> sellBacklog;
for(auto order : orders) {
if(order[2] == 0)
buyBacklog.push(order);
else
sellBacklog.push(order);
while(!buyBacklog.empty() && !sellBacklog.empty() && sellBacklog.top()[0] <= buyBacklog.top()[0]) {
auto btop = buyBacklog.top();
buyBacklog.pop();
auto stop = sellBacklog.top();
sellBacklog.pop();
int diff = btop[1] - stop[1];
if(diff > 0) {
btop[1] = diff;
buyBacklog.push(btop);
}
else if(diff<0) {
stop[1] = abs(diff);
sellBacklog.push(stop);
}
}
}
int ans = 0 , mod = 1e9+7;
while(!buyBacklog.empty()){
ans = (ans +buyBacklog.top()[1])%mod;
buyBacklog.pop();
}
while(!sellBacklog.empty()){
ans = (ans+ sellBacklog.top()[1])%mod;
sellBacklog.pop();
}
return ans;
}
}; | var getNumberOfBacklogOrders = function(orders) {
const buyHeap = new Heap((child, parent) => child.price > parent.price)
const sellHeap = new Heap((child, parent) => child.price < parent.price)
for (let [price, amount, orderType] of orders) {
// sell
if (orderType) {
// while there are amount to be decremented from the sell,
// orders to in the buy backlog, and the price of the largest
// price is greater than the sell price decrement the
// amount of the order with the largest price by the amount
while (amount > 0 && buyHeap.peak() && buyHeap.peak().price >= price) {
if (buyHeap.peak().amount > amount) {
buyHeap.peak().amount -= amount
amount = 0
} else {
amount -= buyHeap.pop().amount
}
}
// if there is any amount left, add it to the sale backlog
if (amount) {
sellHeap.push({ price, amount })
}
// buy
} else {
// while there are amount to be decremented from the buy,
// orders to in the sell backlog, and the price of the smallest
// price is less than the buy price decrement the
// amount of the order with the smallest price by the amount
while (amount > 0 && sellHeap.peak() && sellHeap.peak().price <= price) {
if (sellHeap.peak().amount > amount) {
sellHeap.peak().amount -= amount
amount = 0
} else {
amount -= sellHeap.pop().amount;
}
}
// if there is any amount left, add it to the buy backlog
if (amount) {
buyHeap.push({ price, amount })
}
}
}
// total all of the amounts in both backlogs and return the result
let accumultiveAmount = 0;
for (const { amount } of buyHeap.store) {
accumultiveAmount += amount;
}
for (const { amount } of sellHeap.store) {
accumultiveAmount += amount;
}
return accumultiveAmount % 1000000007
};
class Heap {
constructor(fn) {
this.store = [];
this.fn = fn;
}
peak() {
return this.store[0];
}
size() {
return this.store.length;
}
pop() {
if (this.store.length < 2) {
return this.store.pop();
}
const result = this.store[0];
this.store[0] = this.store.pop();
this.heapifyDown(0);
return result;
}
push(val) {
this.store.push(val);
this.heapifyUp(this.store.length - 1);
}
heapifyUp(child) {
while (child) {
const parent = Math.floor((child - 1) / 2);
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
child = parent;
} else {
return child;
}
}
}
heapifyDown(parent) {
while (true) {
let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());
if (this.shouldSwap(child2, child)) {
child = child2
}
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
parent = child;
} else {
return parent;
}
}
}
shouldSwap(child, parent) {
return child && this.fn(this.store[child], this.store[parent]);
}
} | Number of Orders in the Backlog |
A string s is called good if there are no two different characters in s that have the same frequency.
Given a string s, return the minimum number of characters you need to delete to make s good.
The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.
Example 1:
Input: s = "aab"
Output: 0
Explanation: s is already good.
Example 2:
Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
Example 3:
Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters.
| class Solution:
def minDeletions(self, s: str) -> int:
# Get the frequency of each character sorted in reverse order
frequencies = sorted(Counter(s).values(), reverse=True)
total_deletions = 0
next_unused_freq = len(s)
for freq in frequencies:
# It is impossible for the frequency to be higher
next_unused_freq = min(next_unused_freq, freq)
total_deletions += freq - next_unused_freq
# We cannot have another character with this frequency,
# so decrement next_unused_freq
if next_unused_freq > 0:
next_unused_freq -= 1
return total_deletions | class Solution {
private int N = 26;
public int minDeletions(String s) {
int[] array = new int[N];
for (char ch : s.toCharArray()) {
array[ch - 'a']++;
}
int ans = 0;
Set<Integer> set = new HashSet<>();
for (int i : array) {
if (i == 0) continue;
while (set.contains(i)) {
i--;
ans++;
}
if (i != 0) {
set.add(i);
}
}
return ans;
}
} | class Solution {
public:
int minDeletions(string s) {
//Array to store the count of each character.
vector<int> freq (26, 0);
//Calculatimg frequency of all characters.
for (char c : s){
freq[c - 'a']++;
}
//sorting the frequencies. So the greatest frequencies are in right side.
sort(freq.begin(), freq.end());
int del = 0; //to store the deletions.
//Checking if 2 frequencies are same, if same then decrease the frequency so that it becomes less than the next greater one.So Start from the 2nd greatest frequency that is at freq[24].
for (int i = 24; i >= 0; i--) {
if(freq[i] == 0) break; // if frequency is 0 that means no more character is left.
if(freq[i] >= freq[i+1]){
int prev = freq[i]; //To store the frequency before deletion.
freq[i] = max(0, freq[i+1] -1); //New frequency should be 1 less than the previous frequency in the array.
del += prev - freq[i]; //Calculating deleted characters
}
}
return del;
}
}; | var minDeletions = function(s) {
let freq = new Array(26).fill(0); // Create an array to store character frequencies
for (let i = 0; i < s.length; i++) {
freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; // Count the frequency of each character
}
freq.sort((a, b) => a - b); // Sort frequencies in ascending order
let del = 0; // Initialize the deletion count
for (let i = 24; i >= 0; i--) {
if (freq[i] === 0) {
break; // No more characters with this frequency
}
if (freq[i] >= freq[i + 1]) {
let prev = freq[i];
freq[i] = Math.max(0, freq[i + 1] - 1);
del += prev - freq[i]; // Update the deletion count
}
}
return del; // Return the minimum deletions required
}; | Minimum Deletions to Make Character Frequencies Unique |
There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.
Note that multiple kids can have the greatest number of candies.
Example 1:
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
Example 2:
Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
Example 3:
Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
Constraints:
n == candies.length
2 <= n <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50
| class Solution:
def kidsWithCandies(self, candy, extra):
#create an array(res) with all values as True and it's lenght is same as candies
res = [True]*len(candy)
#iterate over the elements in the array candy
for i in range(len(candy)):
#if the no. of canides at curr position + extra is greater than or equal to the maximum of candies then continue
if (candy[i] + extra) >= max(candy):
continue
#if not
else:
#change the value of that position in res as false
res[i] = False
#return the res list
return res | class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
List<Boolean>result = new ArrayList<>(candies.length); // better practice since the length is known
int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1
for (int i = 1; i<candies.length; i++) {
theHighest = Math.max(theHighest,candies[i]); //returns the greatest value for us to compare later
}
//Since we are comparing with greatest value, we can use math logic to subtract extraCandies the other side
//(candies[i]+extraCandies >= theHighest) or (candies[i] >= theHighest-extraCandies)
int mathLogic = theHighest - extraCandies;
for (int i = 0; i<candies.length; i++) {
//logic: 6+5>=10 or 6 >=10-5
if (candies[i] >= mathLogic) {
result.add(true);
} else {
result.add(false);
}
}
return result;
}
} | class Solution {
public:
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
vector<bool> ans;
int i = 0, size, max = 0;
size = candies.size();
for(i = 0; i<size; i++){
if(candies[i]>max) max = candies[i];
}
for(i = 0; i<size;i++){
if(candies[i]+extraCandies >= max){
ans.push_back(true);
}
else ans.push_back(false);
}
return ans;
}
}; | var kidsWithCandies = function(candies, extraCandies) {
//First find out maximum number in array:->
let max=0, res=[];
for(let i=0; i<candies.length; i++){
if(candies[i]>max) max=candies[i];
}
console.log(max)
/*Now add extraCandies with every element in array and checks if
that sum is equals to or greater than max and return true and false otherwise; */
for(let i=0; i<candies.length; i++){
let temp=candies[i]+extraCandies;
if(temp>=max) res.push(true);
else res.push(false);
}
return res;
}; | Kids With the Greatest Number of Candies |
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
Each group has exactly X cards.
All the cards in each group have the same integer.
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
Constraints:
1 <= deck.length <= 104
0 <= deck[i] < 104
| class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
f=defaultdict(int)
for j in deck:
f[j]+=1
import math
u=list(f.values())
g=u[0]
for j in range(1,len(u)):
g=math.gcd(g,u[j])
return g!=1
| // X of a Kind in a Deck of Cards
// Leetcode problem : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
int[] count = new int[10000];
for(int i : deck)
count[i]++;
int gcd = 0;
for(int i : count)
if(i != 0)
gcd = gcd == 0 ? i : gcd(gcd, i);
return gcd >= 2;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
} | class Solution {
public:
int gcd(int a,int b)
{
while(a>0 && b>0)
{
if(a>b) a=a%b;
else b=b%a;
}
return (a==0? b:a);
}
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int,int> mp;
vector<int> v;
for(auto i:deck)
{
mp[i]++;
}
for(auto it:mp)
{
v.push_back(it.second);
}
int g=-1;
for(int i=0;i<v.size();i++)
{
if(g==-1)
g=v[i];
else
g=gcd(g,v[i]);
}
return g>1;
}
}; | var hasGroupsSizeX = function(deck) {
let unique = [...new Set(deck)], three = 0, two = 0, five = 0, size = 0, same = 0, s = 0;
for(let i = 0; i<unique.length; i++){
for(let y=0; y<deck.length; y++){
if(unique[i] === deck[y]){
size++;
}
}
if(size<2) return false;
if(size%2===0) two++;
if(size%3===0) three++;
if(size%5===0) five++;
if(s === size) same++;
s = size;
size = 0;
}
if(Math.max(two,three,five) !== unique.length && same !== unique.length-1) return false;
return true;
}; | X of a Kind in a Deck of Cards |
Given an integer array nums, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
Example 1:
Input: nums = [1,3,2,3,1]
Output: 2
Example 2:
Input: nums = [2,4,3,5,1]
Output: 3
Constraints:
1 <= nums.length <= 5 * 104
-231 <= nums[i] <= 231 - 1
| from sortedcontainers import SortedList
class Solution:
"""
For each sub array nums[0, i]
We sum the reverse pairs count
of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1
Using a BST(sortedList) to get logN insert and lookup time.
Time: O(NlogN)
Space: O(N)
"""
def reversePairs(self, nums: List[int]) -> int:
res = 0
bst = SortedList()
for e in nums:
res += len(bst) - bst.bisect_left(2 * e + 1) # the count is the N - index
bst.add(e) # add the the bst
return res | class Solution {
int cnt;
public int reversePairs(int[] nums) {
int n = nums.length;
cnt = 0;
sort(0 , n - 1 , nums);
return cnt;
}
void sort(int l , int r , int nums[]){
if(l == r){
return;
}
int mid = l + (r - l) / 2;
sort(l , mid , nums);
sort(mid + 1 , r , nums);
merge(l , mid , r , nums);
}
void merge(int l , int mid , int r , int nums[]){
int n1 = mid - l + 1;
int n2 = r - mid;
int a[] = new int[n1];
int b[] = new int[n2];
for(int i = 0; i < n1; i++){
a[i] = nums[l + i];
}
for(int j = 0; j < n2; j++){
b[j] = nums[mid + 1 + j];
int idx = upperBound(a , 0 , n1 - 1 , 2L * (long)b[j]);
if(idx <= n1) {
cnt += n1 - idx;
}
}
int i = 0;
int j = 0;
int k = l;
while(i < n1 && j < n2){
if(b[j] <= a[i]){
nums[k++] = b[j++];
}
else{
nums[k++] = a[i++];
}
}
while(i < n1){
nums[k++] = a[i++];
}
while(j < n2){
nums[k++] = b[j++];
}
}
int upperBound(int a[] , int l , int r , long x){
int ans = r + 1;
while(l <= r){
int mid = l + (r - l) / 2;
if((long)a[mid] > x){
ans = mid;
r = mid - 1;
}
else{
l = mid + 1;
}
}
return ans;
}
} | class Solution {
public:
int merge_count(vector<int> &nums,int s,int e){
int i;
int mid = (s+e)/2;
int j=mid+1;
long long int count=0;
for(i=s;i<=mid;i++){
while((j<=e)&&((double)nums[i]/2.0)>nums[j]){
j++;
}
count += j-(mid+1);
}
i=s;j=mid+1;
vector<int> ans;
while((i<=mid)&&(j<=e)){
if(nums[i]<=nums[j]){
ans.push_back(nums[i]);
i++;
}
else{
ans.push_back(nums[j]);
j++;
}
}
while(i<=mid){
ans.push_back(nums[i]);
i++;
}
while(j<=e){
ans.push_back(nums[j]);
j++;
}
for(int k=s;k<=e;k++){
nums[k]=ans[k-s];
}
return count;
}
int reverse_count(vector<int> &nums,int s,int e){
if(s>=e){
return 0;
}
int mid = (s+e)/2;
int l_count = reverse_count(nums,s,mid);
int r_count = reverse_count(nums,mid+1,e);
int s_count = merge_count(nums,s,e);
return (l_count+r_count+s_count);
}
int reversePairs(vector<int>& nums) {
int res = reverse_count(nums,0,nums.size()-1);
return res;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var reversePairs = function(nums) {
let ans = mergeSort(nums,0,nums.length-1);
return ans;
};
var mergeSort = function(nums,l,h){
if(l>=h){
return 0;
}
let m = Math.floor((l+h)/2);
let inv = mergeSort(nums,l,m);
inv = inv + mergeSort(nums,m+1,h);
inv = inv + merge(nums,l,m,h);
return inv;
}
var merge = function (nums,l,m,h){
let cnt = 0;
let j=m+1;
for(let i=l;i<=m;i++){
while(j<=h && nums[i]> 2*nums[j]){
j++;
}
cnt = cnt+(j-(m+1));
}
let left = l, right=m+1,temp=[];
while(left<=m && right<=h){
if(nums[left]<=nums[right]){
temp.push(nums[left]);
left++;
}
else{
temp.push(nums[right]);
right++;
}
}
while(left<=m){
temp.push(nums[left]);
left++;
}
while(right<=h){
temp.push(nums[right]);
right++;
}
for(let i=l;i<=h;i++){
nums[i]=temp[i-l];
}
return cnt;
} | Reverse Pairs |
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
Example 1:
Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
Example 2:
Input: root = [2,1,3]
Output: [2,1,3]
Constraints:
The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 105
| # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def balanceBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
arr = []
self.flatTree(root, arr)
return self.createTree(arr, 0, len(arr))
def flatTree(self, root, arr):
if not root:
return
self.flatTree(root.left, arr)
arr.append(root)
self.flatTree(root.right, arr)
def createTree(self, arr, start, length):
if length == 0:
return None
root = arr[start + length / 2]
root.left = self.createTree(arr, start, length / 2)
root.right = self.createTree(arr, start + length / 2 + 1, length - length / 2 - 1)
return root | class Solution {
public TreeNode balanceBST(TreeNode root) {
List<Integer> arr = new ArrayList();
InOrder( root, arr);
return sortedArrayToBST( arr, 0, arr.size()-1);
}
public void InOrder(TreeNode node, List<Integer> arr){
if(node != null){
InOrder( node.left, arr);
arr.add(node.val);
InOrder( node.right, arr);
}
}
public TreeNode sortedArrayToBST(List<Integer> arr, int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode node = new TreeNode(arr.get(mid));
node.left = sortedArrayToBST(arr, start, mid - 1);
node.right = sortedArrayToBST(arr, mid + 1, end);
return node;
}
} | class Solution {
public:
vector<int> nums ;
void traverse(TreeNode * root){
if(!root) return ;
traverse(root->left) ;
nums.push_back(root->val) ;
traverse(root->right) ;
return ;
}
TreeNode * makeTree(int s , int e){
if(s > e) return nullptr ;
int m = (s + e) / 2 ;
TreeNode * root = new TreeNode(nums[m]) ;
root->left = makeTree(s,m - 1) ;
root->right = makeTree(m + 1,e) ;
return root ;
}
TreeNode* balanceBST(TreeNode* root) {
traverse(root) ;
return makeTree(0,size(nums) - 1) ;
}
}; | var balanceBST = function(root) {
let arr = [];//store sorted value in array
let InOrder = (node) => {//inorder helper to traverse and store sorted values in array
if(!node)
return;
InOrder(node.left);
arr.push(node.val);
InOrder(node.right);
}
InOrder(root);
let BalancedFromSortedArray = (arr, start, end) => {//create Balanced tree from sorted array
if(start>end)
return null;
let mid = Math.floor((start+end)/2);
let newNode = new TreeNode(arr[mid]);
newNode.left = BalancedFromSortedArray(arr,start,mid-1);
newNode.right = BalancedFromSortedArray(arr,mid+1,end);
return newNode;
}
let Balanced = BalancedFromSortedArray(arr,0,arr.length-1);
return Balanced;
}; | Balance a Binary Search Tree |
We have an array arr of non-negative integers.
For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j].
Return the number of possible results. Results that occur more than once are only counted once in the final answer
Example 1:
Input: arr = [0]
Output: 1
Explanation: There is only one possible result: 0.
Example 2:
Input: arr = [1,1,2]
Output: 3
Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Example 3:
Input: arr = [1,2,4]
Output: 6
Explanation: The possible results are 1, 2, 3, 4, 6, and 7.
Constraints:
1 <= nums.length <= 5 * 104
0 <= nums[i] <= 109
| class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
ans=set(arr)
# each element is a subarry
one = set()
# to get the ans for the subarray of size >1
# starting from 0th element to the ending element
one.add(arr[0])
for i in range(1,len(arr)):
two=set()
for j in one:
two.add(j | arr[i])
# subarray from the element in one set to the current ele(i th one)
ans.add(j| arr[i])
two.add(arr[i])
# adding curr element to set two so that from next iteration we can take sub array starting from curr element
one = two
return len(ans)
| class Solution {
public int subarrayBitwiseORs(int[] arr) {
int n = arr.length;
Set<Integer> s = new HashSet();
LinkedList<Integer> queue = new LinkedList();
for(int i = 0; i< n; i++){
int size = queue.size();
if(!queue.contains(arr[i])){
queue.offer(arr[i]);
s.add(arr[i]);
}
int j = 0;
while(j<size){
int tmp = queue.poll()|arr[i];
if(!queue.contains(tmp)){
queue.offer(tmp);
s.add(tmp);
}
j++;
}
}
return s.size();
}
} | class Solution {
public:
int subarrayBitwiseORs(vector<int>& arr) {
vector<int>s;
int l=0;
for(int a:arr) {
int r=s.size();
s.push_back(a);
for(int i=l;i<r;i++)
if(s.back()!=(s[i]|a))
s.push_back(s[i] | a);
l=r;
}
return unordered_set<int>(begin(s), end(s)).size();
}
}; | /** https://leetcode.com/problems/bitwise-ors-of-subarrays/
* @param {number[]} arr
* @return {number}
*/
var subarrayBitwiseORs = function(arr) {
// Hashset to store the unique bitwise
this.uniqueBw = new Set();
// Dynamic programming
dp(arr, arr.length - 1);
return this.uniqueBw.size;
};
var dp = function(arr, currIdx) {
// Base, reach beginning of the array
if (currIdx === 0) {
// Store the value to unique bitwise, since it's only single number, we store the actual value
this.uniqueBw.add(arr[0]);
// Return array
return [arr[0]];
}
// DP to previous index
let prev = dp(arr, currIdx - 1);
// Number at current index
let firstBw = arr[currIdx];
// Add number at current index to hashset, since it's only single number, we store the actual value
this.uniqueBw.add(firstBw);
// Another hashset to store the result of bitwise operation between number at current index with result from previous index
let currRes = new Set();
currRes.add(firstBw);
// Loop through result form previous index
for (let i = 0; i < prev.length; i++) {
// Perform bitwise operation OR
let curr = arr[currIdx] | prev[i];
// Add to unique bitwise collection
this.uniqueBw.add(curr);
// Add to current result
currRes.add(curr);
}
// Return current result as an array
return [...currRes];
}; | Bitwise ORs of Subarrays |
You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.
In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.
Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".
Example 1:
Input: words = ["abba","baba","bbaa","cd","cd"]
Output: ["abba","cd"]
Explanation:
One of the ways we can obtain the resultant array is by using the following operations:
- Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2].
Now words = ["abba","baba","cd","cd"].
- Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1].
Now words = ["abba","cd","cd"].
- Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2].
Now words = ["abba","cd"].
We can no longer perform any operations, so ["abba","cd"] is the final answer.
Example 2:
Input: words = ["a","b","c","d","e"]
Output: ["a","b","c","d","e"]
Explanation:
No two adjacent strings in words are anagrams of each other, so no operations are performed.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
| class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
i = 0
while i < len(words) - 1:
if sorted(words[i]) == sorted(words[i + 1]):
words.remove(words[i + 1])
continue
i += 1
return words | class Solution {
public List<String> removeAnagrams(String[] words) {
String prev ="";
List<String> li=new ArrayList<>();
for(int i=0;i<words.length;i++){
char[] ch=words[i].toCharArray();
Arrays.sort(ch);
String curr=String.valueOf(ch);
if(!curr.equals(prev)){
li.add(words[i]);
prev=curr;
}
}
return li;
}
} | class Solution {
public:
vector<string> removeAnagrams(vector<string>& words) {
for(int i = 1;i<words.size();i++){
string x = words[i];
sort(x.begin(),x.end());
string y = words[i-1];
sort(y.begin(),y.end());
if(x == y){
words.erase(words.begin() + i);
i--;
}
}
return words;
}
}; | var removeAnagrams = function(words) {
let n = words.length;
for(let i=0; i<n-1; i++){
if(isAnagram(words[i], words[i+1])){
words.splice(i+1, 1);
i--
n--
}
}
return words
};
function isAnagram(a, b){
let freqArr = new Array(26).fill(0);
if(a.length != b.length) return false
for(let i=0; i<a.length; i++){
let idx1 = a[i].charCodeAt(0) - "a".charCodeAt(0);
freqArr[idx1]++;
let idx2 = b[i].charCodeAt(0) - "a".charCodeAt(0);
freqArr[idx2]--
}
for(let i=0; i<26; i++){
if(freqArr[i] > 0){
return false
}
}
return true
} | Find Resultant Array After Removing Anagrams |
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Constraints:
1 <= num <= 108
| class Solution:
def maxDiff(self, num: int) -> int:
i=0
while i<len(str(num)):
change = (str(num)[i])
if change!='9':
break
i+=1
i=0
flag = False
while i<len(str(num)):
sc = (str(num)[i])
if sc!='1' and sc!='0':
if i>0:
flag =True
break
i+=1
small = str(num)
num = str(num)
m=''
for i in range(len(str(num))):
if num[i]==change:
m+='9'
else:
m+=num[i]
m = int(m)
s =''
for i in range(len(num)):
if small[i]==sc:
if flag:
s+='0'
else:
if small[i]=="0":
s+='0'
else:
s+='1'
else:
s+=small[i]
small = int(s)
return m - small | class Solution {
public int maxDiff(int num) {
int[] arr = new int[String.valueOf(num).length()];
for (int i = arr.length - 1; i >= 0; i--){
arr[i] = num % 10;
num /= 10;
}
return max(arr.clone()) - min(arr);
}
private int max(int[] arr){ // find max
for (int i = 0, t = -1; i < arr.length; i++){
if (t == -1 && arr[i] != 9){
t = arr[i];
}
if (t == arr[i]){
arr[i] = 9;
}
}
return parse(arr);
}
private int min(int[] arr){ // find min
int re = arr[0] == 1? 0 : 1;
int t = arr[0] == 1? -1 : arr[0];
for (int i = 0; i < arr.length; i++){
if (t == -1 && arr[i] != 0 && arr[i] != arr[0]){
t = arr[i];
}
if (t == arr[i]){
arr[i] = re;
}
}
return parse(arr);
}
private int parse(int[] arr){
int ans = 0;
for (int i = 0; i < arr.length; i++){
ans = 10 * ans + arr[i];
}
return ans;
}
} | class Solution {
public:
int power10(int n)
{
int total=1;
for(int i=0;i<n;i++)
{
total*=10;
}
return total;
}
int maxDiff(int num) {
vector<int> v;
vector<int> w;
int n = num;
while (n > 0)
{
v.push_back(n % 10);
w.push_back(n % 10);
n /= 10;
}
//Finding maximum number
int d = v.size();
int j = d - 1;
for (int i = d - 1; i >= 0; i--)
{
if (v[i] != 9)
{
j = i;
break;
}
}
for (int i = 0; i <= j; i++)
{
if (v[i] == v[j])
{
v[i] = 9;
}
}
long long int res = 0;
for (int i = d - 1; i >= 0; i--)
{
res += (v[i] * power10(i));
}
//Finding minimum number
int t = w.size();
if (w[t - 1] == 1)
{
int l = -1;
for (int i = t - 2; i >= 0; i--)
{
if (w[i] != 0 && w[i]!=1)
{
l = i;
break;
}
}
for (int i = 0; i <= l; i++)
{
if (w[i] == w[l])
{
w[i] = 0;
}
}
}
else
{
for (int i = 0; i < t; i++)
{
if (w[i] == w[t - 1])
{
w[i] = 1;
}
}
}
long long int res2 = 0;
for (int i = t - 1; i >= 0; i--)
{
res2 += (power10(i) * w[i]);
}
return res-res2;
}
}; | var maxDiff = function(num) {
let occur = undefined;
let max = num.toString().split("");
let min = num.toString().split("");
for(i=0;i<max.length;i++){
if(max[i]<9&&!occur){
occur = max[i];
max[i] = 9;
}
if(max[i]===occur) max[i] = 9;
}
occur = undefined;
let zerone;
for(i=0;i<min.length;i++){
if(!occur&&min[i]>1){
occur = min[i];
if(i===0) zerone = 1;
else zerone = 0;
min[i] = zerone;
}
if(min[i]===occur) min[i] = zerone;
}
return +max.join("")-+min.join("");
}; | Max Difference You Can Get From Changing an Integer |
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
Example 1:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Example 2:
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
Constraints:
n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
All the values of rooms[i] are unique.
| class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
# Create a set of for rooms visited
visited_rooms = set()
# Create a queue to do a breadth first search visiting rooms
# Append the first room, 0, to the queue to begin the search
queue = collections.deque()
queue.append(0)
# Perform the breadth first search with the queue
while queue:
for _ in range(0, len(queue)):
# Search the room
room_number = queue.popleft()
# If we haven't visited the room, get the keys from the room
if room_number not in visited_rooms:
# Collect the keys from the room
found_keys = rooms[room_number]
# Add the keys to the queue so they can be tested
for key in found_keys:
queue.append(key)
# Add the current room to the visited set
visited_rooms.add(room_number)
# If we visited all of the rooms, then the number of visited rooms should be
# equal to the number of total rooms
if len(visited_rooms) == len(rooms):
return True
return False | class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] visited = new boolean[rooms.size()];
visited[0]= true;
for(int a:rooms.get(0))
{
if(!visited[a])
{
bfs(a, visited, rooms.size()-1, rooms);
}
}
//System.out.println("arr -->>"+Arrays.toString(visited));
for(boolean a:visited)
{
if(!a)
return false;
}
return true;
}
public void bfs(int key, boolean[] vivsted, int target,List<List<Integer>> rooms)
{
vivsted[key] = true;
for(int a:rooms.get(key))
{
if(!vivsted[a])
{
bfs(a, vivsted, target, rooms);
}
}
}
} | class Solution {
public:
void dfs(int node, vector<vector<int>>& rooms,vector<int> &visited){
visited[node]=1;
for(auto it: rooms[node]){
if(visited[it]==0)
dfs(it, rooms, visited);
else continue;
}
return;
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n=rooms.size();
vector<int> visited(n,0);
dfs(0,rooms,visited);
for(int i=0;i<n;i++){
if(visited[i]==0) return false;
}
return true;
}
}; | function dfs(current,all,visited){
if(visited.size==all.length){
return true;
}
for(let i=0;i<all[current].length;i++){
if(!visited.has(all[current][i])){
visited.add(all[current][i]);
if(dfs(all[current][i],all,visited))
return true;
}
}
return false;
}
var canVisitAllRooms = function(rooms) {
let visited=new Set();
visited.add(0);
if (dfs(0,rooms,visited)) return true;
return false;
}; | Keys and Rooms |
You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:
You want to use the modify function to covert arr to nums using the minimum number of calls.
Return the minimum number of function calls to make nums from arr.
The test cases are generated so that the answer fits in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.
Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.
Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
| # Observe that:
# +1 places a 1 to the end of the int's binary representation
# (assuming a 0 there previously)
# x2 is a bitshift left
# So you basically just need to count all the ones in the binary representations
# and find how many shifts are required (largest bit length minus one).
class Solution:
def minOperations(self, nums: List[int]) -> int:
if max(nums) == 0:
return 0
return sum([x.bit_count() for x in nums]) + max([x.bit_length() for x in nums]) - 1 | class Solution {
public int minOperations(int[] nums) {
int odd = 0, even = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums){
int res = dfs(n, map);
odd += res >> 5;
even = Math.max(res & 0b11111, even);
}
return odd + even;
}
private int dfs(int n, Map<Integer, Integer> map){
if (n == 0) return 0;
if (map.containsKey(n)) return map.get(n);
int res = n % 2 << 5;
res += dfs(n / 2, map) + (n > 1? 1 : 0);
map.put(n, res);
return res;
}
} | class Solution {
public:
int minOperations(vector<int>& nums) {
int ans = 0;
int t = 33;
while(t--){
int flag = false;
for(int i = 0; i<nums.size(); i++){
if(nums[i]%2) ans++;
nums[i]/=2;
if(nums[i]!=0) flag = true;
}
if(!flag) break;
ans++;
}
return ans;
}
}; | var minOperations = function(nums) {
let maxpow = 0, ans = 0, pow, val
for (let i = 0; i < nums.length; i++) {
for (val = nums[i], pow = 0; val > 0; ans++)
if (val % 2) val--
else pow++, val /= 2
ans -= pow
if (pow > maxpow) maxpow = pow
}
return ans + maxpow
}; | Minimum Numbers of Function Calls to Make Target Array |
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.
The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
Example 1:
Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
Example 2:
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
Constraints:
1 <= logs.length <= 100
1950 <= birthi < deathi <= 2050
| class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
logs.sort(key=lambda x: x[0])
print(logs)
living = 0
max_living = 0
year = 0
for ind, (start, stop) in enumerate(logs):
born = ind+1
dead = 0
for i in range(ind):
if logs[i][1] <= start:
dead += 1
living = born - dead
# print(born, dead, living, max_living)
if living > max_living:
max_living = living
year = start
return year | class Solution {
public int maximumPopulation(int[][] logs) {
int[] year = new int[2051];
// O(n) -> n is log.length
for(int[] log : logs){
year[log[0]] += 1;
year[log[1]] -= 1;
}
int maxNum = year[1950], maxYear = 1950;
// O(100) -> 2050 - 1950 = 100
for(int i = 1951; i < year.length; i++){
year[i] += year[i - 1]; // Generating Prefix Sum
if(year[i] > maxNum){
maxNum = year[i];
maxYear = i;
}
}
return maxYear;
}
} | class Solution {
public:
int maximumPopulation(vector<vector<int>>& logs) {
int arr[101]={0};
for(vector<int> log : logs){
arr[log[0]-1950]++;
arr[log[1]-1950]--;
}
int max=0,year,cnt=0;
for(int i=0;i<101;i++){
cnt+=arr[i];
if(cnt>max)
max=cnt,year=i;
}
return year+1950;
}
}; | var maximumPopulation = function(logs) {
const count = new Array(101).fill(0);
for (const [birth, death] of logs) {
count[birth - 1950]++;
count[death - 1950]--;
}
let max = 0;
for (let i = 1; i < 101; i++) {
count[i] += count[i - 1];
if (count[i] > count[max]) max = i;
}
return 1950 + max;
}; | Maximum Population Year |
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
| class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
step = 0
while step < len(nums):
if nums[step] == val:
nums.pop(step)
continue
step+=1
return len(nums) | class Solution {
public int removeElement(int[] nums, int val) {
int ind = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] != val){
nums[ind++] = nums[i];
}
}
return ind;
}
} | // two pointer
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
if (nums[left] != val) {
++left;
}
else if (nums[right] == val) {
--right;
}
else if (left < right) {
nums[left++] = nums[right--];
}
}
return left;
}
}; | var removeElement = function(nums, val) {
for(let i = 0; i < nums.length; i++){
if(nums[i] === val){
nums.splice(i, 1);
i--;
}
}
return nums.length;
}; | Remove Element |
Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"
Example 2:
Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"
Constraints:
1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s and dictionary[i] consist of lowercase English letters.
| class Solution:
def findLongestWord(self, s: str, dictionary: list[str]) -> str:
solution = ""
for word in dictionary:
j = 0
for i in range(len(s)):
if s[i] == word[j]:
j+=1
if j == len(word):
solution = word if len(word) > len(solution) or len(word) == len(solution) and word < solution else solution
break
return solution | class Solution {
public String findLongestWord(String s, List<String> dictionary) {
int[] fre=new int[26];
String ans="";
int flag=0;
int[] fff=new int[26];
char[] ch = s.toCharArray();
for(char c : ch)
fre[c-'a']+=1;
for(String s1 : dictionary)
{
fff=fre.clone();
int[] fre1=new int[26];
char[] ch1 = s1.toCharArray();
for(char c : ch1)
{
fre1[c-'a']+=1;
}
for(char c : ch1)
{
if(fre1[c-'a'] <= fff[c-'a'])
{ flag=0;
fff[c-'a']-=1;
fre1[c-'a']-=1;
}
else
{flag=1;
break;}
}
if(flag==0)
{
if(ans != "")
{
if(ans.length() <s1.length())
{
ans=s1;
}else
{
if(ans.length() ==s1.length())
{
int f=0;
for(int m=0;m<ans.length();m++)
{
if(ans.charAt(m)>s1.charAt(m))
{
f=1;
break;
}
}
if(f==1)
ans=s1;
}
}
}
else
ans =s1;
}
else
{
flag=0;
}
}
return ans;
}
} | class Solution {
private:
//checks whether the string word is a subsequence of s
bool isSubSeq(string &s,string &word){
int start=0;
for(int i=0;i<s.size();i++){
if(s[i]==word[start]){
//every character of word occurs in s, therefore we return true
if(++start==word.size()){
return true;
}
}
}
return false;
}
public:
string findLongestWord(string s, vector<string>& dictionary) {
string ans="";
for(string word:dictionary){
if(word.size()>=ans.size() and isSubSeq(s,word)){
if(word.size()>ans.size()){
ans=word;
} else if(word.size()==ans.size() and word<ans){
ans=word;
}
}
}
return ans;
}
}; | /**
* @param {string} s
* @param {string[]} dictionary
* @return {string}
*/
var findLongestWord = function(s, dictionary) {
const getLen = (s1, s2) => {
let i = 0, j = 0;
while(i < s1.length && j < s2.length) {
if(s1[i] == s2[j]) { i++, j++; }
else i++;
}
if(j != s2.length) return 0;
return s2.length;
}
let ans = '', ml = 0;
for(let word of dictionary) {
const len = getLen(s, word);
if(len > ml) {
ans = word;
ml = len;
}
else if(len == ml && ans > word) {
ans = word;
}
}
return ans;
}; | Longest Word in Dictionary through Deleting |
Given the head of a linked list, return the list after sorting it in ascending order.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is in the range [0, 5 * 104].
-105 <= Node.val <= 105
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
| class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
store = []
curr = head
while curr:
store.append(curr.val)
curr = curr.next
store.sort()
dummyNode = ListNode(0)
temp = dummyNode
for i in store:
x = ListNode(val = i)
temp.next = x
temp = x
return dummyNode.next | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = middle(head);
ListNode left = sortList(head);
ListNode right = sortList(mid);
return mergeTwoLists(left, right);
}
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode tail = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
tail.next = list1;
list1 = list1.next;
tail = tail.next;
} else {
tail.next = list2;
list2 = list2.next;
tail = tail.next;
}
}
tail.next = (list1 != null) ? list1 : list2;
return head.next;
}
public ListNode middle(ListNode head) {
ListNode midprev = null;
while (head != null && head.next != null) {
midprev = (midprev == null) ? head : midprev.next;
head = head.next.next;
}
ListNode mid = midprev.next;
midprev.next = null;
return mid;
}
} | // Please upvote if it helps
class Solution {
public:
ListNode* sortList(ListNode* head) {
//If List Contain a Single or 0 Node
if(head == NULL || head ->next == NULL)
return head;
ListNode *temp = NULL;
ListNode *slow = head;
ListNode *fast = head;
// 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)
while(fast != NULL && fast -> next != NULL)
{
temp = slow;
slow = slow->next; //slow increment by 1
fast = fast ->next ->next; //fast incremented by 2
}
temp -> next = NULL; //end of first left half
ListNode* l1 = sortList(head); //left half recursive call
ListNode* l2 = sortList(slow); //right half recursive call
return mergelist(l1, l2); //mergelist Function call
}
//MergeSort Function O(n*logn)
ListNode* mergelist(ListNode *l1, ListNode *l2)
{
ListNode *ptr = new ListNode(0);
ListNode *curr = ptr;
while(l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{
curr -> next = l1;
l1 = l1 -> next;
}
else
{
curr -> next = l2;
l2 = l2 -> next;
}
curr = curr ->next;
}
//for unqual length linked list
if(l1 != NULL)
{
curr -> next = l1;
l1 = l1->next;
}
if(l2 != NULL)
{
curr -> next = l2;
l2 = l2 ->next;
}
return ptr->next;
}
}; | function getListSize(head) {
let curr = head;
let size = 0;
while(curr !== null) {
size += 1;
curr = curr.next;
}
return size;
}
function splitInHalf(head, n) {
let node1 = head;
let curr = head;
for (let i = 0; i < Math.floor(n / 2) - 1; i++) {
curr = curr.next;
}
const node2 = curr.next;
curr.next = null;
return [
node1,
Math.floor(n / 2),
node2,
n - Math.floor(n / 2),
]
}
function merge(head1, head2) {
if (head1.val > head2.val) {
return merge(head2, head1)
}
const head = head1;
let curr = head1;
let runner1 = curr.next;
let runner2 = head2;
while (runner1 !== null || runner2 !== null) {
const runner1Value = runner1 ? runner1.val : Infinity;
const runner2Value = runner2 ? runner2.val : Infinity;
if (runner1Value < runner2Value) {
curr.next = runner1;
runner1 = runner1.next;
} else {
curr.next = runner2;
runner2 = runner2.next;
}
curr = curr.next;
}
curr.next = null;
return head;
}
var sortList = function(head) {
const size = getListSize(head);
function mergeSort(node, n) {
if (n <= 1) {
return node;
}
const [node1, n1, node2, n2] = splitInHalf(node, n);
const [merged1, merged2] = [mergeSort(node1, n1), mergeSort(node2, n2)];
return merge(merged1, merged2);
}
return mergeSort(head, size);
}; | Sort List |
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.
You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.
Return the maximum number of candies each child can get.
Example 1:
Input: candies = [5,8,6], k = 3
Output: 5
Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.
Example 2:
Input: candies = [2,5], k = 11
Output: 0
Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.
Constraints:
1 <= candies.length <= 105
1 <= candies[i] <= 107
1 <= k <= 1012
| def canSplit(candies, mid, k):
split = 0
for i in candies:
split += i//mid
if split >= k:
return True
else:
return False
class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
end = sum(candies)//k
start = 1
ans = 0
while start <= end:
mid = (start + end)//2
if canSplit(candies, mid, k):
start = mid + 1
ans = mid
else:
end = mid - 1
return ans | class Solution {
public boolean canSplit(int[] candies, long k, long mid) {
long split = 0;
for(int i = 0; i < candies.length; ++i) {
split += candies[i]/mid;
}
if(split >= k)
return true;
else
return false;
}
public int maximumCandies(int[] candies, long k) {
long sum = 0;
for(int i = 0; i < candies.length; ++i) {
sum += candies[i];
}
long start = 1, end = sum;
long ans = 0;
while(start <= end) {
long mid = (start + end)/2;
if(canSplit(candies, k, mid)) {
ans = mid;
start = mid + 1;
} else {
end = mid-1;
}
}
return (int)ans;
}
} | class Solution {
public:
bool canSplit(vector<int>& candies, long long k, long long mid) {
long long split = 0;
for(int i = 0; i < candies.size(); ++i) {
split += candies[i]/mid;
}
if(split >= k)
return true;
else
return false;
}
int maximumCandies(vector<int>& candies, long long k) {
long long sum = 0;
for(int i = 0; i < candies.size(); ++i) {
sum += candies[i];
}
long long start = 1, end = sum/k;
long long ans = 0;
while(start <= end) {
long long mid = (start + end)/2;
if(canSplit(candies, k, mid)) {
ans = mid;
start = mid + 1;
} else {
end = mid-1;
}
}
return ans;
}
}; | var maximumCandies = function(candies, k) {
const n = candies.length;
let left = 1;
let right = 1e7 + 1;
while (left < right) {
const mid = (left + right) >> 1;
const pilesAvail = divideIntoPiles(mid);
if (pilesAvail < k) right = mid;
else left = mid + 1;
}
return right - 1;
function divideIntoPiles(pileSize) {
let piles = 0;
for (let i = 0; i < n; ++i) {
const count = candies[i];
piles += Math.floor(count / pileSize);
}
return piles;
}
}; | Maximum Candies Allocated to K Children |
Given an integer num, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 106
| class Solution:
def numberOfSteps(self, num: int) -> int:
count=0
while num:
if num%2:
num=num-1
else:
num=num//2
count+=1
return count | class Solution {
public int numberOfSteps(int num) {
return helper(num,0);
}
public int helper(int n,int c){
if(n==0) return c;
if(n%2==0){ //check for even no.
return helper(n/2,c+1);
}
return helper(n-1,c+1);
}
} | class Solution {
public:
int numberOfSteps(int num) {
int count = 0;
while (num > 0)
{
if (num % 2==0)
{
num = num/2;
count++;
}
else
{
if(num > 1)
{
num -= 1;
count++;
}
else
{
count++;
break;
}
}
}
return count;
}
}; | var numberOfSteps = function(num) {
let steps = 0
while (num > 0) {
if (num % 2 === 0) {
num = num/2
steps++
}
if (num % 2 === 1) {
num--
steps++
}
}
return steps
}; | Number of Steps to Reduce a Number to Zero |
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.
Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.
Example 1:
Input: flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]
Output: [1,2,2,2]
Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
Example 2:
Input: flowers = [[1,10],[3,3]], persons = [3,3,2]
Output: [2,2,1]
Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
Constraints:
1 <= flowers.length <= 5 * 104
flowers[i].length == 2
1 <= starti <= endi <= 109
1 <= persons.length <= 5 * 104
1 <= persons[i] <= 109
| class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
#we ADD flowers in the order in which they start, but we remove them in the order they
#end. For this reason, we sort the flowers by starting time but put them in a heap,
#in which we remove them by ending time
starts = sorted(flowers) #keep flowers untouched in case array should be constant
blooming = [] #heap of active flowers
answer = [-1] * len(people) #output array
hours = [(people[i], i) for i in range(len(people))] #the people, ordered and indexed by their time
hours.sort()
i = 0 #going through starts
for hour, person in hours:
#add all flowers that have started
while i < len(starts) and starts[i][0] <= hour:
heappush(blooming, (starts[i][1], starts[i][0]))
i += 1
#now remove all flowers that have ended. Note that we only care about the absolute smallest,
#and in python minheaps, that is always the first element - even if no other element's order
#is guaranteed
while blooming and blooming[0][0] < hour: #as long as the soonest to end blooming flower hasn't already stopped
heappop(blooming)
answer[person] = len(blooming)
return answer | class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] persons) {
int n = persons.length;
int[] result = new int[n];
TreeMap<Integer, Integer> treeMap = new TreeMap<>();
// See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clean-Code
for (int[] flower : flowers) {
treeMap.put(flower[0], treeMap.getOrDefault(flower[0], 0) + 1);
// use end + 1 instead of end
treeMap.put(flower[1] + 1, treeMap.getOrDefault(flower[1] + 1, 0) - 1);
}
TreeMap<Integer, Integer> sum = new TreeMap<>();
int prev = 0;
for (Map.Entry<Integer, Integer> entry : treeMap.entrySet()) {
prev += entry.getValue();
sum.put(entry.getKey(), prev);
}
for (int i = 0; i < n; i++) {
Map.Entry<Integer, Integer> entry = sum.floorEntry(persons[i]);
// if entry is null then result[i] = 0
if (entry != null) result[i] = entry.getValue();
}
return result;
}
} | class Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& flowers, vector<int>& persons) {
vector<vector<int>> line;
for (auto& f : flowers) {
line.push_back({f[0], +1});
line.push_back({f[1]+1, -1});
}
sort(line.begin(), line.end());
int prefix = 0;
vector<int> time, vals;
for (auto& l : line) {
time.push_back(l[0]);
vals.push_back(prefix += l[1]);
}
vector<int> ans;
for (auto& p : persons) {
auto it = upper_bound(time.begin(), time.end(), p);
if (it == time.begin()) ans.push_back(0);
else ans.push_back(vals[it - time.begin() - 1]);
}
return ans;
}
}; | /**
* @param {number[][]} flowers
* @param {number[]} persons
* @return {number[]}
*/
var fullBloomFlowers = function(flowers, persons) {
// *** IDEATION *** //
// key observation:
// total number of flowers see on day i =
// number of flowers has already bloomed so far on day i - number of flowers already ended ("died") prior to day i
// find number of flowers already bloomed on day i
// each flower has a start day
// start array = [1, 3, 9, 4] for example
// on day 8, there are 3 flowers bloomed:
// equivalent to find the number of elements in the "start" array which is less than or equal to 8
// find number of flowers already ended on day i
// each flower has an end day
// end array = [6, 7, 12, 13] for example
// on day 8, there are 2 flowers already ended:
// equivalent to find the number of elements in the "end" array which is less than 8
// equivalent to find the number of elements in the "end" array which is less than or equal to 7
// both process above can be solved efficiently with binary search on a sorted array
// hence we need to first build 2 array "start" and "end" and sorted it
// then apply the formula at the beginning to return the required answer
// *** IMPLEMENTATION *** //
// step 1: build the "start" and "end" array
let start = [];
let end = [];
for (let i = 0; i < flowers.length; i++) {
start[i] = flowers[i][0];
end[i] = flowers[i][1];
}
// step 2: sort the "start" and "end" array
start.sort((a, b) => a - b);
end.sort((a, b) => a - b);
// step 3: apply the observation formula using a binarySearch function
let res = [];
for (let j = 0; j < persons.length; j++) {
res[j] = binarySearch(start, persons[j]) - binarySearch(end, persons[j] - 1);
}
return res;
// step 4: implement the binarySearch function (variant from standard binarySearch)
function binarySearch(array, k) {
// array is sorted;
// obj is to find the number of elements in array which is less than or equal to "k"
let left = 0;
let right = array.length - 1;
let index = -1;
while (left <= right) {
let mid = left + Math.floor((right - left) / 2);
if (k < array[mid]) {
right = mid - 1;
} else {
index = Math.max(index, mid); // record the index whenever k >= array[mid]
left = mid + 1;
}
}
// all elements with in array from position '0' to position 'index' will be less than or equal to k
return index + 1;
}
}; | Number of Flowers in Full Bloom |
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.
If there are several possible values for h, the maximum one is taken as the h-index.
Example 1:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
Example 2:
Input: citations = [1,3,1]
Output: 1
Constraints:
n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
| class Solution:
def hIndex(self, citations: List[int]) -> int:
num = sorted(citations)
h = 0
j = len(num)-1
for i in range(len(num)):
if i+1 <=num[i] and j-i+1>=num[i]:
h =max(num[i],h)
elif i+1 <= num[i] and j-i+1<num[i]:
h = max(h,j-i+1)
elif i+1 > num[i] and j-i+1 >=num[i]:
h = max(h, num[i])
return h | class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
Arrays.sort(citations);
for(int i = 0; i < n; i++) {
int hlen = (n-1) - i + 1;
if(citations[i] >= hlen) {
return hlen;
}
}
return 0;
}
} | class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(),citations.end(),greater<int>());
int ans=0;
for(int i=0;i<citations.size();i++){
if(citations[i]>=i+1) ans=i+1;
}
return ans;
}
}; | var hIndex = function(citations) {
citations.sort((a,b)=>b-a)
let i=0
while(citations[i]>i) i++
return i
}; | H-Index |
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
| class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
def dfs(node, level, result):
if not node:
return
if level >= len(result):
result.append([])
result[level].append(node.val)
dfs(node.left, level+1, result)
dfs(node.right, level+1, result)
result = []
dfs(root, 0, result)
return result[::-1] | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
Queue<TreeNode> al=new LinkedList<>();
List<List<Integer>> fal=new LinkedList<>();
if(root==null) return fal;
al.offer(root);
while(!al.isEmpty()){
List<Integer> aal=new LinkedList<>();
int num=al.size();
for(int i=0;i<num;i++){
if(al.peek().left != null){
al.offer(al.peek().left);
}
if( al.peek().right != null){
al.offer(al.peek().right);
}
aal.add(al.poll().val);
}
fal.add(0,aal);
}
return fal;
}
} | class Solution {
void dft(TreeNode* root, int level, map<int,vector<int>,std::greater<int>>& levelVals)
{
if (root == nullptr)
return;
if (levelVals.find(level) == levelVals.end())
levelVals[level] = {root->val};
else
levelVals[level].push_back(root->val);
dft(root->left,level+1,levelVals);
dft(root->right,level+1,levelVals);
}
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
map<int,vector<int>,std::greater<int>> levelVals;
dft(root,0,levelVals);
vector<vector<int>> res;
for (const auto& [level,vals] : levelVals)
res.push_back(vals);
return res;
}
}; | var levelOrderBottom = function(root) {
let solution = []
function dfs(node, level) {
if(!node) return null
if(!solution[level]) solution[level] = []
solution[level].push(node.val)
dfs(node.left, level + 1)
dfs(node.right, level + 1)
}
dfs(root, 0)
return solution.reverse()
}; | Binary Tree Level Order Traversal II |
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node,maxVal):
if not node:
return 0
res=1 if node.val>=maxVal else 0
maxVal=max(maxVal,node.val)
res+=dfs(node.left,maxVal)
res+=dfs(node.right,maxVal)
return res
return dfs(root,root.val) | class Solution {
int ans = 0;
public int goodNodes(TreeNode root) {
if (root == null) return 0;
dfs(root, root.val);
return ans;
}
void dfs(TreeNode root, int mx) {
if (root == null) return;
mx = Math.max(mx, root.val);
if(mx <= root.val) ans++;
dfs(root.left, mx);
dfs(root.right, mx);
}
} | class Solution {
public:
int count=0;
void sol(TreeNode* root,int gr){
if(!root)return; // base condition
if(gr<=root->val){ //check point max element increase count
gr=max(gr,root->val);
count++;
}
if(root->left) sol(root->left,gr);
if(root->right) sol(root->right,gr);
}
int goodNodes(TreeNode* root) {
if(!root->left && !root->right) return 1; //check for if there is one node
int gr=root->val;
sol(root,gr);
return count;
}
}; | var goodNodes = function(root) {
let ans = 0;
const traverse = (r = root, mx = root.val) => {
if(!r) return;
if(r.val >= mx) {
ans++;
}
let childMax = Math.max(mx, r.val);
traverse(r.left, childMax);
traverse(r.right, childMax);
}
traverse();
return ans;
}; | Count Good Nodes in Binary Tree |
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
1 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= fromi, toi < n
fromi != toi
1 <= pricei <= 104
There will not be any multiple flights between two cities.
0 <= src, dst, k < n
src != dst
| class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
graph = defaultdict(list)
for u,v,w in flights: graph[u].append((v,w))
pq = [(0,src,0)]
dis = [float('inf')]*n
while pq:
c,n,l = heappop(pq)
if n==dst: return c
if l > k or l>= dis[n]: continue
dis[n] = l
for v,w in graph[n]:
heappush(pq,(c+w,v,l+1))
return -1 | class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
// Initialize Prices arr with infinity & src 0
int[] prices = new int[n];
for(int i = 0; i < n; i++)
prices[i] = Integer.MAX_VALUE;
prices[src] = 0;
// Build Adj list {key: src | val: dst+price}
Map<Integer, List<int[]>> flightsMap = new HashMap<>();
for(int[] flight : flights){
int flightSrc = flight[0];
int flightDst = flight[1];
int flightPrice = flight[2];
List<int[]> flightsList = flightsMap.getOrDefault(flightSrc, new ArrayList<>());
flightsList.add(new int[]{flightDst, flightPrice});
flightsMap.put(flightSrc, flightsList);
}
// Start Bellman ford Algo
Queue<Integer> q = new LinkedList<>();
q.offer(src);
while(k >= 0 && !q.isEmpty()){
int[] tempPrices = new int[n]; // Temporary Prices Arr
for(int i = 0; i < n; i++)
tempPrices[i] = prices[i];
int size = q.size();
for(int i = 0; i < size; i++){
int curSrc = q.poll();
int curPrice = prices[curSrc];
List<int[]> curFlightsList = flightsMap.getOrDefault(curSrc, new ArrayList<>());
for(int[] flight : curFlightsList){
int flightDst = flight[0];
int flightPrice = flight[1];
int newPrice = curPrice + flightPrice;
if(newPrice < tempPrices[flightDst]){
tempPrices[flightDst] = newPrice;
q.offer(flightDst);
}
}
}
for(int i = 0; i < n; i++) // Copy Temp Prices to Original Price Arr
prices[i] = tempPrices[i];
k--;
}
int totalPrice = prices[dst];
return totalPrice == Integer.MAX_VALUE? -1 : totalPrice;
}
} | class Solution {
public:
#define f first
#define s second
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k){
priority_queue< array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
unordered_map<int, vector<pair<int,int>>> g;
for(auto& f : flights){
g[f[0]].push_back({f[1],f[2]});
}
vector<int> dis(n,INT_MAX);
pq.push({0,src,0});
while(!pq.empty()){
int c = pq.top()[0];
int cur = pq.top()[1];
int lvl = pq.top()[2];
pq.pop();
if(cur==dst) return c;
if(lvl > k || lvl >= dis[cur]) continue;
dis[cur] = lvl;
for(auto& nei : g[cur]){
pq.push({c+nei.s, nei.f, lvl+1});
}
}
return -1;
}
}; | /**
* @param {number} n
* @param {number[][]} flights
* @param {number} src
* @param {number} dst
* @param {number} k
* @return {number}
*/
const MAX_PRICE=Math.pow(10,8);
var findCheapestPrice = function(n, flights, src, dst, k) {
let prev=[];
let step=0;
let curr=[];
for(let i=0;i<n;i++){
prev[i]=MAX_PRICE;
}
prev[src]=0;
while(step-1<k){
curr=[...prev];
let isAnyChange=false;
for(let i=0;i<flights.length;i++){
let [src,dst,p]=flights[i];
if(prev[src]>=MAX_PRICE)continue;
let totalCostToReachDst=prev[src]+p;
curr[dst]=Math.min(curr[dst],totalCostToReachDst);
}
step++;
prev=curr;
}
return prev[dst]>=MAX_PRICE?-1:prev[dst];
}; | Cheapest Flights Within K Stops |
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.
For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses.
Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000"
Output: ["0.0.0.0"]
Example 3:
Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
1 <= s.length <= 20
s consists of digits only.
| class Solution:
def restoreIpAddresses(self, s: str):
def isValid(st):
if(len(st)!=len(str(int(st)))):
return False
st = int(st)
if(st>255 or st<0):
return False
return True
validIps = []
for i in range(1,4):
s1 = s[:i]
if(not isValid(s1)):
continue
for j in range(i+1, min(len(s), i+4)):
s2 = s[i:j]
if(not isValid(s2)):
continue
for k in range(j+1,min(len(s), j+4)):
s3 = s[j:k]
if(not isValid(s3)):
continue
s4 = s[k:]
if(not isValid(s4)):
continue
currentIp = s1+"."+s2+"."+s3+"."+s4
validIps.append(currentIp)
return validIps | class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> ans = new ArrayList<>();
int len = s.length();
for(int i = 1; i < 4 && i < len-2 ; i++ ){
for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){
for(int k = j+1 ; k < j + 4 && k < len ; k++){
String s1 = s.substring(0,i);
String s2 = s.substring(i,j);
String s3 = s.substring(j,k);
String s4 = s.substring(k,len);
if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))
ans.add(s1+"."+s2+"."+s3+"."+s4);
}
}
}
return ans;
}
boolean isValid(String s){
if(s.length() > 3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s) > 255)
return false;
return true;
}
} | class Solution {
public:
vector<string> res;
void dfs(string s,int idx,string curr_ip,int cnt)
{
if(cnt>4)
return;
if(cnt==4&&idx==s.size())
{
res.push_back(curr_ip);
// return;
}
for(int i=1;i<4;i++)
{
if(idx+i>s.size())
break;
string str=s.substr(idx,i);
if((str[0]=='0'&&str.size()>1)||(i==3&&stoi(str)>=256))
continue;
dfs(s,idx+i,curr_ip+str+(cnt==3?"":"."),cnt+1);
}
}
vector<string> restoreIpAddresses(string s)
{
dfs(s,0,"",0);
return res;
}
}; | var restoreIpAddresses = function(s) {
const results = [];
const go = (str, arr) => {
// if we used every character and have 4 sections, it's a good IP!
if (str.length === 0 && arr.length === 4) {
results.push(arr.join('.'));
return;
}
// we already have too many in the array, let's just stop
if (arr.length >= 4) {
return;
}
// chop off next 3 characters and continue recursing
if (str.length > 2 && +str.substring(0, 3) < 256 && +str.substring(0, 3) > 0 && str[0] !== '0') {
go(str.slice(3), [...arr, str.substring(0, 3)]);
}
// chop off next 2 characters and continue recursing
if (str.length > 1 && +str.substring(0, 2) > 0 && str[0] !== '0') {
go(str.slice(2), [...arr, str.substring(0, 2)]);
}
// chop off next 1 character and continue recursing, in this case, starting with 0 is OK
if (str.length > 0 && +str.substring(0, 1) >= 0) {
go(str.slice(1), [...arr, str.substring(0, 1)]);
}
return;
}
go(s, []);
return results;
}; | Restore IP Addresses |
You are given an integer array nums that is sorted in non-decreasing order.
Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:
Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
All subsequences have a length of 3 or more.
Return true if you can split nums according to the above conditions, or false otherwise.
A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).
Example 1:
Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5
Example 2:
Input: nums = [1,2,3,3,4,4,5,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5
Example 3:
Input: nums = [1,2,3,4,4,5]
Output: false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
nums is sorted in non-decreasing order.
| class Solution:
from collections import defaultdict
def isPossible(self, nums):
# If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.
if len(nums) < 3:
return False
# 'count' dictionary stores the frequency of each number in the input array.
count = defaultdict(int)
# 'tails' dictionary stores the number of subsequences that end at a certain number.
tails = defaultdict(int)
# Populate the 'count' dictionary with the frequency of each number.
for num in nums:
count[num] += 1
# Iterate through the input array.
for num in nums:
# If the count of the current number is 0, it means this number has already been used in a subsequence.
if count[num] == 0:
continue
# If there is a subsequence that ends with the current number minus 1,
# it means we can extend that subsequence by adding the current number.
elif tails[num - 1] > 0:
tails[num - 1] -= 1 # Decrease the count of the tails that end with the current number minus 1.
tails[num] += 1 # Increase the count of the tails that end with the current number.
# If there are enough numbers after the current number to form a subsequence,
# create a new subsequence starting with the current number.
elif count[num + 1] > 0 and count[num + 2] > 0:
count[num + 1] -= 1 # Decrease the count of the next number.
count[num + 2] -= 1 # Decrease the count of the number after the next number.
tails[num + 2] += 1 # Increase the count of the tails that end with the number after the next number.
else:
# If we can't extend an existing subsequence or start a new one, return False.
return False
# Decrease the count of the current number since it's used in a subsequence.
count[num] -= 1
# If the function successfully iterates through the entire array, return True.
return True | class Solution {
public boolean isPossible(int[] nums) {
int[] freq = new int[2002], subEnd = new int[2002];
for (int i : nums) {
int num = i + 1001;
freq[num]++;
}
for (int i : nums) {
int num = i + 1001;
if (freq[num] == 0) continue; // Num already in use
freq[num]--;
if (subEnd[num - 1] > 0) { // Put into existing subsequence
subEnd[num - 1]--;
subEnd[num]++;
}
// New subsequence of size 3 is possible
else if (freq[num + 1] > 0 && freq[num + 2] > 0) {
freq[num + 1]--;
freq[num + 2]--;
subEnd[num + 2]++; // New subsequence
} else return false;
}
return true;
}
} | class Solution {
public:
bool isPossible(vector<int>& nums) {
priority_queue<int, vector<int>, greater<int>> pq;
unordered_map<int, int> um;
for(int &num : nums)
{
pq.push(num);
um[num]++;
}
queue<int> q;
int count = 0, prev;
while(!pq.empty())
{
if(count == 0)
{
prev = pq.top();
pq.pop();
count++;
}
else if(pq.top() == prev+1)
{
if(um[pq.top()] >= um[prev])
{
um[prev]--;
pq.pop();
prev += 1;
count++;
}
else if(um[pq.top()] < um[prev])
{
um[prev]--;
if(count <= 2) return false;
while(!q.empty())
{
pq.push(q.front());
q.pop();
}
count = 0;
}
}
else if(pq.top() == prev)
{
q.push(pq.top());
pq.pop();
if(pq.empty())
{
if(count <= 2) return false;
while(!q.empty())
{
pq.push(q.front());
q.pop();
}
count = 0;
}
}
else if(pq.top() > prev+1)
{
if(count <= 2) return false;
while(!q.empty())
{
pq.push(q.front());
q.pop();
}
count = 0;
}
}
if(count > 0 && count <= 2) return false;
return true;
}
}; | var isPossible = function(nums) {
const need = new Map();
const hash = nums.reduce((map, num) => {
const count = map.get(num) ?? 0;
map.set(num, count + 1);
return map;
}, new Map());
for (const num of nums) {
const current = hash.get(num);
if (current === 0) continue;
const currentNeed = need.get(num);
const next1 = hash.get(num + 1);
const next2 = hash.get(num + 2);
if (currentNeed > 0) {
const need1 = need.get(num + 1) ?? 0;
need.set(num, currentNeed - 1);
need.set(num + 1, need1 + 1);
} else if (next1 > 0 && next2 > 0) {
const need3 = need.get(num + 3) ?? 0;
hash.set(num + 1, next1 - 1);
hash.set(num + 2, next2 - 1);
need.set(num + 3, need3 + 1);
} else {
return false;
}
hash.set(num, current - 1);
}
return true;
}; | Split Array into Consecutive Subsequences |
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
| class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
# step1. determine the larger array and the smaller array, and get the difference on sum
sum1 = sum(nums1)
sum2 = sum(nums2)
if sum1==sum2:
return 0
elif sum1>sum2:
larger_sum_nums = nums1
smaller_sum_nums = nums2
else:
larger_sum_nums = nums2
smaller_sum_nums = nums1
sum_diff = abs(sum1-sum2)
# step2. calculate the max "gain" at each position (how much difference we can reduce if operating on that position)
gains_in_larger_array = [num-1 for num in larger_sum_nums]
gains_in_smaller_array = [6-num for num in smaller_sum_nums]
# step3. sort the "gain" and check the least number of steps to reduce the difference to 0
gains = gains_in_larger_array + gains_in_smaller_array
gains.sort(reverse = True)
count = 0
target_diff = sum_diff
for i in range(len(gains)):
target_diff -= gains[i]
count += 1
if target_diff <= 0:
return count
# return -1 if the difference still cannot be reduced to 0 even after operating on all positions
return -1 | class Solution {
public int minOperations(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
if (m > 6 * n || n > 6 * m) return -1;
int sum1 = 0, sum2 = 0;
for (int i : nums1) sum1 += i;
for (int i : nums2) sum2 += i;
int diff = sum1 - sum2;
if (diff == 0) return 0;
return (diff > 0 ? helper(nums1, nums2, diff)
: helper(nums2, nums1, -diff));
}
private int helper(int[] nums1, int[] nums2, int diff) {
// count[i] : frequency of numbers that can reduce the diff by i
int[] count = new int[6];
for (int num : nums1) count[num - 1]++;
for (int num : nums2) count[6 - num]++;
int res = 0;
for (int i = 5; i > 0; i--) {
int c = Math.min(count[i], diff / i + (diff % i == 0 ? 0 : 1));
res += c;
diff -= c * i;
if (diff <= 0) break;
}
return res;
}
} | /**
* @brief
* Given two array, return the minimum numbers we have to change the values to make two arrays sum equal
*
* [Observation]
* Since the value is from 1 ~ 6
*
* Min sum of the array = len(arr)
* Max sum of the array = 6 len(arr)
*
* When to arrays range cannot overlap -> no answer
*
* If there is a answer -> sum s, value will be between s1 and s2
* So, let's say if s1 is smaller, we would like to increase s1's element and decrease s2's element
* -> We only have to design for s1 is smaller than s2.
*
* [Key] Which element's should we increase and decrease?
* To minimize the changing elements, we change the number who can mostly decrease the differences.
* So, we compare the smallest element in num1 and largest in num2.
* -> sorting
*
* @algo sorting + greedy
* Time O(NlogN) for sorting
* Space O(1)
*/
class Solution {
public:
int minOperations(vector<int>& nums1, vector<int>& nums2) {
int l1 = nums1.size(); // l1 ~ 6l1
int l2 = nums2.size(); // l2 ~ 6l2
if(6*l1 < l2 || 6*l2 < l1) {
return -1;
}
int sum1 = accumulate(nums1.begin(), nums1.end(), 0);
int sum2 = accumulate(nums2.begin(), nums2.end(), 0);
if(sum1 > sum2) return minOperations(nums2, nums1);
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end(), greater<int>());
// let us design the way where sum1 <= sum2
int ans = 0, ptr1 = 0, ptr2 = 0;
int diff = sum2 - sum1;
while(diff > 0) {
if(ptr2 == l2 || ptr1 < l1 && (6 - nums1[ptr1]) >= (nums2[ptr2] - 1)) {
diff -= (6 - nums1[ptr1]);
ans++;
ptr1++;
}
else {
diff -= (nums2[ptr2] - 1);
ans++;
ptr2++;
}
}
return ans;
}
}; | var minOperations = function(nums1, nums2) {
/*
Two impossible cases:
min1...max1 ... min2...max2 -> we can't make them equal
min2...max2 ... min1...max1 -> we can't make them equal
*/
let min1 = nums1.length * 1;
let max1 = nums1.length * 6;
let min2 = nums2.length * 1;
let max2 = nums2.length * 6;
if (min2 > max1 || min1 > max2) {
return -1;
}
let sum1 = nums1.reduce((acc,cur) => acc + cur);
let sum2 = nums2.reduce((acc,cur) => acc + cur);
if (sum1 === sum2) return 0;
if (sum1 < sum2) {
return helper(nums1, nums2, sum1, sum2);
} else {
return helper(nums2, nums1, sum2, sum1);
}
// T.C: O(M + N), M = # of nums1, N = # of nums2
// S.C: O(1)
};
// Condition: sum of A < sum of B
// the idea is to add the maximum possible value to sumA and
// subtract the maximum possible value from sumB so that
// we make sumA >= sumB as soon as possible
function helper(A, B, sumA, sumB) {
let freqA = new Array(7).fill(0);
let freqB = new Array(7).fill(0);
for (let i = 0; i < A.length; i++) {
freqA[A[i]]++;
}
for (let i = 0; i < B.length; i++) {
freqB[B[i]]++;
}
let count = 0;
for (let i = 1; i <= 6; i++) {
// increase sumA
while (freqA[i] > 0 && sumA < sumB) {
sumA += 6-i;
freqA[i]--;
count++;
}
let j = 7-i;
// decrease sumB
while (freqB[j] > 0 && sumA < sumB) {
sumB -= j-1;
freqB[j]--;
count++;
}
if (sumA >= sumB) break;
}
return count;
} | Equal Sum Arrays With Minimum Number of Operations |
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
1 <= arr.length <= 105
-104 <= arr[i], difference <= 104
| class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
d = defaultdict(int)
for num in arr:
if num - difference in d:
d[num] = d[num - difference] + 1
else:
d[num] = 1
return max((d[x] for x in d)) | class Solution {
public int longestSubsequence(int[] arr, int difference) {
int max = 1;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
// find the target element using the current element and the given difference
int target = arr[i] - difference;
// find if an AP for the target element exists in map and its length (else default to 1 - each element is an AP)
int currAns = map.getOrDefault(target, 0) + 1;
// add the current answer to the map
// the amswer will override any previous answers with the same key (with an equal or greater answer)
// for eg, in this case: .......X.....X
// here X is the same number but the 2nd X will have an equal or larger AP sequence (logically)
map.put(arr[i], currAns);
// get max answer
max = Math.max(max, currAns);
}
return max;
}
} | class Solution {
public:
int longestSubsequence(vector<int>& arr, int difference) {
int n = arr.size();
unordered_map<int,int>mp;
multiset<int>s;
int ans = 1;
for(int i=0;i<n;i++)
{
int req = arr[i] - difference;
auto it = s.find(req);
s.insert(arr[i]);
if(it == s.end())
{
continue;
}
else
{
mp[arr[i]] = mp[req] + 1;
ans = max(ans,mp[arr[i]] + 1);
}
}
return ans;
}
}; | var longestSubsequence = function(arr, difference) {
const map = new Map()
let max = 0
for(let num of arr) {
const prev = map.has(num - difference) ? map.get(num -difference) : 0
const val = prev + 1
map.set(num, val)
max = Math.max(max, val)
}
return max
}; | Longest Arithmetic Subsequence of Given Difference |
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Constraints:
arr.length == n
1 <= n <= 105
n is even.
-109 <= arr[i] <= 109
1 <= k <= 105
| class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
#The idea is to count the residues
#If every residue has the counter residue
#such that x+y == k,then we found a pair
count = [0]*k
for num in arr:
count[num%k] +=1
#Now since we have 0,1,2,.....k-1 as residues
#If count[1] == count[k-1],pairs+=count[1]
#since we have odd number of complimenting residues,
#we should also care about residue=0 and residue=k//2
i,j =1,k-1
pairs = 0
while i<j :
if count[i]!=count[j]:
return False
pairs += count[i]
i+=1
j-=1
if pairs>0 and i==j:
pairs+=count[i]/2
pairs+= count[0]/2
n = len(arr)
return pairs == n//2 | class Solution {
public boolean canArrange(int[] arr, int k) {
int[] frequency = new int[k];
for(int num : arr){
num %= k;
if(num < 0) num += k;
frequency[num]++;
}
if(frequency[0]%2 != 0) return false;
for(int i = 1; i <= k/2; i++)
if(frequency[i] != frequency[k-i]) return false;
return true;
}
} | //ask the interviewer
//can we have negative values?
class Solution {
public:
bool canArrange(vector<int>& arr, int k)
{
unordered_map<int,int>memo;//remainder : occurence
//we are storing the frequency of curr%k
//i.e. the frequency of the remainder
for(auto curr : arr)
{
int remainder = ((curr%k)+k)%k;
memo[remainder]++;
}
for(int i =1; i<=k/2; i++)
{
if(memo[i] != memo[k-i])
return false;
}
if(memo[0]%2 != 0)
return false;
return true;
}
}; | var canArrange = function(arr, k) {
let map = new Map();
let index = 0;
for(let i = 0; i < arr.length; i++){
let val = arr[i] % k;
if(val<0) val+=k;
if(map.get(k-val)) map.set(k-val, map.get(k-val) - 1), index--;
else if(map.get(-val)) map.set(-val, map.get(-val) - 1), index--;
else map.set(val, map.get(val) + 1 || 1), index++;
}
return !index;
}; | Check If Array Pairs Are Divisible by k |
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4x.
Example 1:
Input: n = 16
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion? | import math
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
return math.log(n, 4).is_integer() | class Solution {
public boolean isPowerOfFour(int n) {
return (Math.log10(n)/Math.log10(4))%1==0;
}
} | class Solution {
public:
bool isPowerOfFour(int n) {
if(n==1)
return true;
long long p=1;
for(int i=1;i<n;i++)
{
p=p*4;
if(p==n)
return true;
if(p>n)
return false;
}
return false;
}
}; | var isPowerOfFour = function(n) {
if(n==1){
return true
}
let a=1;
for(let i=2;i<=30;i++){
a=a*4
if(a===n){
return true
}
}
return false
}; | Power of Four |
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Example 1:
Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]
Example 2:
Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
Constraints:
1 <= nums.length <= 105
1 <= nums[i].length <= 105
1 <= sum(nums[i].length) <= 105
1 <= nums[i][j] <= 105
| class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
# sort the index of element
heap = list()
n = len(nums)
for i in range(n):
m = len(nums[i])
for j in range(m):
heapq.heappush(heap,[i+j,j,i])
# append the element one by one
ans = []
while heap:
temp = heapq.heappop(heap)
ans.append(nums[temp[2]][temp[1]])
return ans | class Solution {
public int[] findDiagonalOrder(List<List<Integer>> nums) {
HashMap<Integer , Stack<Integer>> map = new HashMap();
for(int i = 0 ; i < nums.size() ; i++){
for(int j = 0 ; j < nums.get(i).size() ; j++){
int z = i + j;
if(map.containsKey(z)){
map.get(z).add(nums.get(i).get(j));
}else{
Stack<Integer> stk = new Stack<>();
stk.push(nums.get(i).get(j));
map.put(z , stk);
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
int k = 0;
while(true){
if(map.containsKey(k)){
int size = map.get(k).size();
while(size-- > 0){
arr.add(map.get(k).pop());
}
k++;
}else{
break;
}
}
int[] res = new int[arr.size()];
for(int i = 0 ; i < res.length ; i++){
res[i] = arr.get(i);
}
return res;
}} | class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
int n = nums.size();
int m = 0;
for(vector<int> &v : nums)
{
int y = v.size();
m = max(m, y);
}
vector<int> D2[n+m-1];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < nums[i].size(); j++)
{
D2[i+j].push_back(nums[i][j]);
}
}
vector<int> ans;
for(int i = 0; i < n+m-1; i++)
{
int x = D2[i].size();
while(x--)
{
ans.push_back(D2[i][x]);
D2[i].pop_back();
}
}
return ans;
}
}; | var findDiagonalOrder = function(nums) {
let vals = []; // [row, diagonal value, actual value]
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums[i].length; j++) {
vals.push([i, i + j, nums[i][j]]);
}
}
vals.sort((a, b) => {
if (a[1] === b[1]) return b[0] - a[0];
return a[1] - b[1];
})
return vals.map(val => val[2]);
}; | Diagonal Traverse II |
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
| class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a, base = 2)+int(b, base = 2)))[2:] | class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int carry = 0;
int i= a.length() -1;
int j= b.length() -1;
while(i>=0 || j>=0){
int sum = carry;
if(i>=0)
sum+=a.charAt(i--)-'0'; // -'0' is just to convert char in integer
if(j>=0)
sum+=b.charAt(j--)-'0';
sb.append(sum%2); // If we have sum = 1 1 then = 2 % 2 = 0 and 0 1 = 1 % 2 = 1
carry = sum /2;
}
if(carry>0)
sb.append(carry);
return sb.reverse().toString();
}
} | class Solution {
public:
string addBinary(string a, string b) {
string ans;
int i=a.length()-1,j=b.length()-1;
int carry=0;
while(carry||i>=0||j>=0){
if(i>=0){
carry+=a[i]-'0';
i--;
}
if(j>=0){
carry+=b[j]-'0';
j--;
}
ans+=carry%2+'0';
carry=carry/2;
}
reverse(ans.begin(),ans.end());
return ans;
}
}; | var addBinary = function(a, b) {
let i = a.length-1, j = b.length-1, carry = 0
let s =[]
while(i >= 0 || j >= 0){
let sum = carry
if(i >= 0) sum += a[i--].charCodeAt() - 48
if(j >= 0) sum += b[j--].charCodeAt() - 48
s.unshift(sum % 2)
carry = ~~(sum/2)
}
return carry > 0 ? "1" + s.join("") : s.join("")
}; | Add Binary |
Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Example 1:
Input: a = "aba", b = "cdc"
Output: 3
Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.
Example 2:
Input: a = "aaa", b = "bbb"
Output: 3
Explanation: The longest uncommon subsequences are "aaa" and "bbb".
Example 3:
Input: a = "aaa", b = "aaa"
Output: -1
Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
Constraints:
1 <= a.length, b.length <= 100
a and b consist of lower-case English letters.
| class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a == b:
return -1
else:
return max(len(a), len(b)) | class Solution {
public int findLUSlength(String a, String b) {
if(a.equals(b)) return -1;
return Math.max(a.length(),b.length());
}
} | class Solution {
public:
int findLUSlength(string a, string b) {
if(a==b){
return -1;
}
if(a.size()>=b.size()){
return a.size();
}
return b.size();
}
}; | var findLUSlength = function(a, b) {
if (a===b) return -1
return Math.max(a.length,b.length)
}; | Longest Uncommon Subsequence I |
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.
Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).
Example 1:
Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Explanation:
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
Example 2:
Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]
Constraints:
1 <= people.length <= 2000
0 <= hi <= 106
0 <= ki < people.length
It is guaranteed that the queue can be reconstructed.
| class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
n = len(people)
people.sort()
ans = [[]]*n
i = 0
while people:
h,p = people.pop(0)
count= p
for i in range(n):
if count== 0 and ans[i] == []:
ans[i] = [h,p]
break
elif not ans[i] or (ans[i] and ans[i][0] >= h ):
count -= 1
return ans | class Solution {
public int[][] reconstructQueue(int[][] people) {
List<int[]> result = new ArrayList<>(); //return value
Arrays.sort(people, (a, b) -> {
int x = Integer.compare(b[0], a[0]);
if(x == 0) return Integer.compare(a[1], b[1]);
else return x; });
for(int[] p: people)
result.add(p[1], p);
return result.toArray(new int[people.length][2]);
}
} | #include <bits/stdc++.h>
using namespace std;
struct node {
int h, k;
node *next;
node(int h, int k) : h(h), k(k), next(nullptr){}
};
bool cmp(vector<int>& p1, vector<int>& p2) {
return (p1[0] != p2[0]) ? (p1[0] > p2[0]) : (p1[1] < p2[1]);
}
void insert(vector<int>& p, node **target) {
node *new_p = new node(p[0], p[1]);
new_p->next = (*target)->next;
(*target)->next = new_p;
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), cmp);
vector<int>& first = people[0];
node *head = new node(0, 0);//pseu
node **target;
int step;
for (int i = 0; i < people.size(); i++) {
vector<int>& p = people[i];
for (target = &head, step=p[1]; step > 0; target=&((*target)->next), step--);
insert(p, target);
}
vector<vector<int>> ans;
ans.resize(people.size());
int i = 0;
for(node *cur = head->next; cur != nullptr; cur = cur->next)
ans[i++] = vector<int>({cur->h, cur->k});
//formally, we should free the list later.
return ans;
}
}; | var reconstructQueue = function(people) {
var queue = new Array(people.length);
people = people.sort((a,b) => (a[0]-b[0]));
for(let i =0;i<people.length;i++){
let count = 0;
for(let j= 0;j<queue.length;j++){
if(!queue[j]){
if(count == people[i][1]){
queue[j] = people[i];
break;
}
count++;
}
else if( queue[j][0] >= people[i][0]){
count++;
}
}
}
return queue;
}; | Queue Reconstruction by Height |
Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Example 2:
Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000.
| class Solution:
max_path=0
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
self.dfs(root);
return self.max_path
def dfs(self,root):
if root is None:return 0
left=self.dfs(root.left)
right=self.dfs(root.right)
if root.left and root.left.val == root.val:
leftPath=left+1
else:
leftPath=0
if root.right and root.right.val == root.val:
rightPath=right+1
else:
rightPath=0
self.max_path = max(self.max_path, leftPath + rightPath)
return max(leftPath, rightPath) | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxLen = 0;
public int longestUnivaluePath(TreeNode root) {
lup(root);
return maxLen;
}
public int lup(TreeNode root) {
if (root == null) {
return 0;
}
int left = lup(root.left);
int right = lup(root.right);
int leftMax = 0;
int rightMax = 0;
if (root.left != null && root.val == root.left.val) {
leftMax = left + 1;
}
if (root.right != null && root.val == root.right.val) {
rightMax = right + 1;
}
maxLen = Math.max(maxLen, leftMax + rightMax);
return Math.max(leftMax, rightMax);
}
} | class Solution {
public:
int maxlen=0;
pair<int,int> util(TreeNode* root,int val ){
if(!root)
return {0,-1001};
// in pair we will the first part will return the no nodes ,
//and in the second part we will return the value associated with it
pair<int,int> l=util(root->left,root->val);
pair<int,int> r=util(root->right,root->val);
/* now we will check whether the value coming from
the left subtree or(&) right subtree is equal to the
value of the current node
if equal to both the left && right subtree, then the length returned
will be max of the left & right subtree , becuase ATQ, we have to
return the longest path where each node in the path has the same
value , therefore from the current node we can travel to either the
left or right subtree , but the maxlength can be l.first+r.first+1 ,
because we can travel from the leftmost node through the current
node to the rightmost node , which will be a valid path , therefore
we will compare this with the maxlength
*/
if(l.second==root->val && r.second==root->val){
maxlen=max(maxlen,l.first+r.first+1);
return {max(l.first,r.first)+1,root->val};
}
// now similary checking for all the other nodes:
else if(l.second==root->val){
maxlen=max(maxlen,l.first+1);
return {l.first+1,root->val};
}
else if(r.second==root->val){
maxlen=max(maxlen,r.first+1);
return {r.first+1,root->val};
}
else{
return {1,root->val};
}
}
int longestUnivaluePath(TreeNode* root) {
if(!root)
return 0;
util(root,root->val);
return max(maxlen-1,0);
}
}; | var longestUnivaluePath = function(root) {
let max = 0;
const dfs = (node = root, parentVal) => {
if (!node) return 0;
const { val, left, right } = node;
const leftPath = dfs(left, val);
const rightPath = dfs(right, val);
max = Math.max(max, leftPath + rightPath);
return val === parentVal
? Math.max(leftPath, rightPath) + 1
: 0;
};
dfs();
return max;
}; | Longest Univalue Path |
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".
Example 1:
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit cost
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
Example 2:
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
Example 3:
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It is impossible to paint any integer with total cost equal to target.
Constraints:
cost.length == 9
1 <= cost[i], target <= 5000
| from functools import lru_cache
class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
@lru_cache(None)
def dfs(t):
if t == 0: return 0
res = float('-inf')
for digit in range(1,10):
if t - cost[digit-1] >= 0:
res = max(res, dfs(t - cost[digit-1])*10+digit)
return res
res = dfs(target)
return "0" if res == float('-inf') else str(res) | // Space Complexity = O(N*M) (N == length of cost array and M == target )
// Time Complexity = O(N*M)
class Solution {
Map<String,String> map = new HashMap<>();
String[][] memo;
public String largestNumber(int[] cost, int target) {
memo = new String[cost.length+1][target+1];
for( int i = 0;i<=cost.length;i++ ){
for(int j = 0;j<=target;j++) memo[i][j] = "0";
}
String res = helper(cost,cost.length-1,target);
return res == "-1" ? "0" : res;
}
public String helper( int[] cost , int index , int target){
if(target == 0) {
return "";
}
if(target < 0) return "-1";
if(index < 0) return "-1";
if( memo[index][target] != "0") return memo[index][target];
String str1 = (index+1) + helper(cost,cost.length-1,target-cost[index]) ;
String str2 = helper(cost,index-1,target);
String res = getBigger(str1,str2);
memo[index][target] = res;
return res;
}
public String getBigger(String num1 , String num2){
if( num1.contains("-1") ) return num2;
if( num2.contains("-1") ) return num1;
if( num1.length() > num2.length() ) return num1;
if( num2.length() > num1.length() ) return num2;
return Double.parseDouble( num1 ) < Double.parseDouble( num2 ) ? num2 : num1;
}
} | class Solution {
public:
vector<vector<string>> dp ;
string largestNumber(vector<int>& cost, int target) {
dp.resize(10,vector<string>(target+1,"-1"));
return solve(cost,0,target) ;
}
string solve(vector<int>& cost,int idx,int target){
if(!target) return "";
if(target < 0 || idx >= size(cost)) return "0";
if(dp[idx][target]!="-1") return dp[idx][target];
string a = to_string(idx+1) + solve(cost,0,target-cost[idx]);
string b = solve(cost,idx+1,target);
return dp[idx][target] = a.back() == '0' ? b : b.back() == '0' ? a : size(a) == size(b) ? max(a,b) : size(a) > size(b) ? a : b ;
}
}; | var largestNumber = function(cost, target) {
const arr = new Array(target+1).fill('#');
arr[0] = '';
for (let i = 0; i < 9; i++) {
for (let j = cost[i]; j <= target; j++) {
if (arr[j-cost[i]] !== '#' && arr[j-cost[i]].length + 1 >= arr[j].length) {
arr[j] = (i+1).toString().concat(arr[j-cost[i]]);
}
}
}
return arr[target] == '#' ? '0' : arr[target];
}; | Form Largest Integer With Digits That Add up to Target |
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.
For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].
Return the minimum number of operations needed to make nums strictly increasing.
An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.
Example 1:
Input: nums = [1,1,1]
Output: 3
Explanation: You can do the following operations:
1) Increment nums[2], so nums becomes [1,1,2].
2) Increment nums[1], so nums becomes [1,2,2].
3) Increment nums[2], so nums becomes [1,2,3].
Example 2:
Input: nums = [1,5,2,4,1]
Output: 14
Example 3:
Input: nums = [8]
Output: 0
Constraints:
1 <= nums.length <= 5000
1 <= nums[i] <= 104
| class Solution:
def minOperations(self, nums: List[int]) -> int:
sol = 0
last = nums[0]
for i in range(len(nums) - 1):
if last >= nums[i + 1]:
sol += last - nums[i + 1] + 1
last = last + 1
else:
last = nums[i + 1]
return sol | class Solution {
public int minOperations(int[] nums) {
if (nums.length <= 1) {
return 0;
}
int count = 0;
int num = nums[0];
for (int i = 1; i < nums.length; i++) {
if (num == nums[i]) {
count++;
num++;
} else if (num > nums[i]) {
num++;
count += num - nums[i];
} else {
num = nums[i];
}
}
return count;
}
} | class Solution {
public:
int minOperations(vector<int>& nums) {
int output=0;
for(int i=0;i<nums.size()-1;i++){
if(nums[i]<nums[i+1])
continue;
else{
output=output+(nums[i]+1-nums[i+1]);
nums[i+1]=nums[i]+1;
}
}
return output;
}
}; | var minOperations = function(nums) {
if(nums.length < 2) return 0;
let count = 0;
for(let i = 1; i<nums.length; i++) {
if(nums[i] <= nums[i-1]) {
let change = nums[i-1] - nums[i] + 1;
count += change;
nums[i] += change;
}
}
return count;
}; | Minimum Operations to Make the Array Increasing |
You are given an m x n integer matrix mat and an integer target.
Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
The absolute difference between two numbers a and b is the absolute value of a - b.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
Output: 0
Explanation: One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
Example 2:
Input: mat = [[1],[2],[3]], target = 100
Output: 94
Explanation: The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
Example 3:
Input: mat = [[1,2,9,8,7]], target = 6
Output: 1
Explanation: The best choice is to choose 7 from the first row.
The absolute difference is 1.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 70
1 <= mat[i][j] <= 70
1 <= target <= 800
| class Solution:
def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:
min_possible = sum(min(row) for row in mat)
if min_possible >= target: return min_possible - target
curs = {0}
for row in mat:
curs = {x + y for x in row for y in curs if x + y <= 2*target}
return min(abs(target - x) for x in curs) | class Solution {
public int minimizeTheDifference(int[][] mat, int target) {
Integer[][] dp = new Integer[mat.length][5001];
return minDiff(mat, 0, target,0, dp);
}
public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){
if(index == mat.length){
return Math.abs(val - target);
}
if(dp[index][val] != null){
return dp[index][val];
}
int res = Integer.MAX_VALUE;
for(int i = 0; i < mat[0].length; i++){
res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));
}
return dp[index][val] = res;
}
} | class Solution
{
public:
int dp[8000][71];
int n,m;
int find(vector<vector<int>>&mat,int r,int sum,int &target)
{
if(r>=n)
{
return abs(sum-target);
}
if(dp[sum][r]!=-1)
{
return dp[sum][r];
}
int ans=INT_MAX;
for(int i=0;i<m;i++)
{
ans=min(ans,find(mat,r+1,sum+mat[r][i],target));
if(ans==0)
{
break;
}
}
return dp[sum][r]=ans;
}
int minimizeTheDifference(vector<vector<int>>& mat, int target)
{
memset(dp,-1,sizeof(dp));
n=mat.size();
m=mat[0].size();
return find(mat,0,0,target);
}
}; | var minimizeTheDifference = function(mat, target) {
const MAX = Number.MAX_SAFE_INTEGER;
const m = mat.length;
const n = mat[0].length;
const memo = [];
for (let i = 0; i < m; ++i) {
memo[i] = new Array(4901).fill(MAX);
}
return topDown(0, 0);
function topDown(row, sum) {
if (row === m) return Math.abs(target - sum);
if (memo[row][sum] != MAX) return memo[row][sum];
let min = MAX;
mat[row].sort((a, b) => a - b);
const set = new Set(mat[row]);
for (const num of set) {
const res = topDown(row + 1, sum + num);
if (res > min) break;
min = res;
}
memo[row][sum] = min;
return min;
}
}; | Minimize the Difference Between Target and Chosen Elements |
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
Return the number of strings in words that are a prefix of s.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
Example 1:
Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.
Example 2:
Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s.
Note that the same string can occur multiple times in words, and it should be counted each time.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length, s.length <= 10
words[i] and s consist of lowercase English letters only.
| class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return len([i for i in words if s.startswith(i)]) | class Solution {
public int countPrefixes(String[] words, String s) {
int i = 0;
int j = 0;
int count = 0;
for(int k = 0; k < words.length; k++){
if(words[k].length() > s.length()){
continue;
}
while(i < words[k].length() && words[k].charAt(i) == s.charAt(j)){
i++;
j++;
}
if(i == words[k].length()){
count++;
}
i = 0;
j = 0;
}
return count;
}
} | class Solution {
public:
int countPrefixes(vector<string>& words, string s) {
int res = words.size();
for (auto && word : words) {
for (int i = 0; i < word.size(); i++) {
if (s[i] != word[i]) {
res--;
break;
}
}
}
return res;
}
}; | var countPrefixes = function(words, s) {
let cont = 0;
for(i = 0; i < words.length; i++){
for(j = 1; j <= s.length; j++){
if(words[i] == s.slice(0, j)){
cont++;
}
}
}
return cont;
}; | Count Prefixes of a Given String |
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.
Example 2:
Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.
Example 3:
Input: patterns = ["a","a","a"], word = "ab"
Output: 3
Explanation: Each of the patterns appears as a substring in word "ab".
Constraints:
1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i] and word consist of lowercase English letters.
| class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return sum([pattern in word for pattern in patterns])
| class Solution {
public int numOfStrings(String[] patterns, String word) {
int count = 0;
for(int i=0;i<patterns.length;i++){
if(word.contains(patterns[i])){
count++;
}
}
return count;
}
} | class Solution {
public:
int numOfStrings(vector<string>& patterns, string word) {
int count=0;
for(int i=0;i<patterns.size();i++)
{
if(word.find(patterns[i])!=string::npos)
count++;
}
return count;
}
}; | /**
* @param {string[]} patterns
* @param {string} word
* @return {number}
*/
var numOfStrings = function(patterns, word) {
let result = 0;
for(let char of patterns){
if(word.includes(char)){
result++;
} else{
result += 0;
}
}
return result;
}; | Number of Strings That Appear as Substrings in Word |
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
Example 1:
Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
Explanation: The recursive calls are as follow:
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
- The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
- Empty array, so no child.
- The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
Example 2:
Input: nums = [3,2,1]
Output: [3,null,2,null,1]
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
All integers in nums are unique.
| class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
m = max(nums)
idx = nums.index(m)
root = TreeNode(m)
root.left = self.constructMaximumBinaryTree(nums[:idx])
root.right = self.constructMaximumBinaryTree(nums[idx+1:])
return root | class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
TreeNode root = construct(nums,0,nums.length-1);
return root;
}
private TreeNode construct(int []nums, int start, int end) {
if(start > end)
return null;
if(start == end)
return new TreeNode(nums[start]);
int maxIdx = findMax(nums,start,end);
TreeNode root = new TreeNode(nums[maxIdx]);
root.left = construct(nums,start,maxIdx-1);
root.right = construct(nums,maxIdx+1,end);
return root;
}
private int findMax(int []arr, int low, int high) {
int idx = -1, max = Integer.MIN_VALUE;
for(int i=low;i<=high;++i)
if(arr[i]>max) {
max = arr[i];
idx = i;
}
return idx;
}
} | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums)
{
return recur(0, nums.size() - 1, nums);
}
TreeNode* recur(int st, int en, vector<int> &ar)
{
if(st > en)
{
return NULL;
}
TreeNode* cur = new TreeNode();
int maxm = -1, ind;
for(int i = st; i <= en; i++)
{
if(maxm < ar[i])
{
maxm = ar[i];
ind = i;
}
}
cur->val = ar[ind];
cur->left = recur(st, ind-1, ar);
cur->right = recur(ind+1, en, ar);
return cur;
}
}; | var constructMaximumBinaryTree = function(nums) {
if (nums.length === 0) return null;
let max = Math.max(...nums);
let index = nums.indexOf(max);
let left = nums.slice(0, index);
let right = nums.slice(index + 1);
let root = new TreeNode(max);
root.left = constructMaximumBinaryTree(left);
root.right = constructMaximumBinaryTree(right);
return root;
}; | Maximum Binary Tree |
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the Solution class:
Solution() Initializes the object of the system.
String encode(String longUrl) Returns a tiny URL for the given longUrl.
String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.
Example 1:
Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "https://leetcode.com/problems/design-tinyurl"
Explanation:
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after deconding it.
Constraints:
1 <= url.length <= 104
url is guranteed to be a valid URL.
| class Codec:
def encode(self, longUrl):
return longUrl
def decode(self, shortUrl):
return shortUrl | public class Codec {
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
return longUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortUrl;
}
} | class Solution {
private:
unordered_map<string, string> hash;
string server = "http://tinyurl.com/";
string all = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
srand(time(NULL));
string add = "";
int ran = rand() % 10;
int strsize = all.size();
while(ran){
int index = rand() % strsize;
add += all[index];
ran--;
}
hash[(server+add)] = longUrl;
return (server + add);
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return hash[shortUrl];
}
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url)); | let arr = new Array();
let size = 0;
var encode = function(longUrl) {
arr.push(longUrl)
let i = longUrl.indexOf('/',11);
longUrl.slice(i);
longUrl += this.size;
arr.push(longUrl);
size += 2;
return longUrl;
};
var decode = function(shortUrl) {
let i = 0;
while(arr[i] !== shortUrl && i<size){
i++;
}
return arr[i-1];
}; | Encode and Decode TinyURL |
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively? | class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
return root is None or self.findSymmetric(root.left, root.right)
def findSymmetric(self, left, right):
if (left is None or right is None):
return left == right
if (left.val != right.val):
return False
return self.findSymmetric(left.left, right.right) and self.findSymmetric(left.right, right.left) | class Solution {
public boolean isSymmetric(TreeNode root) {
return isSymmetric(root.left,root.right);
}
public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) {
if(rootLeft == null && rootRight == null) {return true;}
if(rootLeft == null || rootRight == null) {return false;}
if (rootLeft.val != rootRight.val) {return false;}
else
return isSymmetric(rootLeft.right, rootRight.left) && isSymmetric(rootLeft.left, rootRight.right);
}
} | class Solution {
public:
bool mirror(TreeNode* root1, TreeNode* root2){
if(root1==NULL and root2==NULL) return true;
if(root1==NULL or root2==NULL) return false;
if(root1->val!=root2->val) return false;
return mirror(root1->left, root2->right) and mirror(root1->right,root2->left);
}
bool isSymmetric(TreeNode* root) {
if(root==NULL) return true;
return mirror(root->left,root->right);
}
}; | var isSymmetric = function(root) {
return helper(root.left, root.right);
function helper(left, right){
if(!left && !right) return true;
if((!left && right) || (left && !right) || (left.val !== right.val)) return false;
return helper(left.left, right.right) && helper(left.right, right.left)
}
}; | Symmetric Tree |
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Example 1:
Input: nums = [2,3,-1,8,4]
Output: 3
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
Example 2:
Input: nums = [1,-1,4]
Output: 2
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
Example 3:
Input: nums = [2,5]
Output: -1
Explanation: There is no valid middleIndex.
Constraints:
1 <= nums.length <= 100
-1000 <= nums[i] <= 1000
Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/
| class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
A = [0] + list(accumulate(nums)) + [0]
total, n = sum(nums), len(nums)
for i in range(n):
if A[i] == total - A[i] - nums[i]:
return i
return -1 | class Solution {
public int findMiddleIndex(int[] nums) {
for(int i=0;i<nums.length;i++)
{
int rsum=0;
int lsum=0;
for(int k=0;k<i;k++) lsum+=nums[k];
for(int k=i+1;k<nums.length;k++) rsum+=nums[k];
if(lsum==rsum){
return i;
}
}
return -1;
}
} | class Solution {
public:
int findMiddleIndex(vector<int>& nums)
{
int n=nums.size();
int left_sum=0;
int right_sum=0;
for(int i=0;i<n;i++)
{
right_sum+=nums[i];
}
for(int i=0;i<n;i++)
{
right_sum-=nums[i];
if(left_sum==right_sum)
{
return i;
}
left_sum+=nums[i];
}
return -1;
}
}; | var findMiddleIndex = function(nums) {
for (let i = 0; i < nums.length; i++) {
let leftNums = nums.slice(0, i).reduce((a, b) => a + b, 0);
let rightNums = nums.slice(i + 1).reduce((a, b) => a + b, 0);
if (leftNums === rightNums) {
return i;
}
}
return -1;
}; | Find the Middle Index in Array |
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord, endWord, and wordList[i] consist of lowercase English letters.
beginWord != endWord
All the words in wordList are unique.
| class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
e = defaultdict(list)
m = len(beginWord)
for word in wordList + [beginWord]:
for i in range(m):
w = word[:i] + "*" + word[i + 1:]
e[w].append(word)
q = deque([beginWord])
used = set([beginWord])
d = 0
while q:
d += 1
for _ in range(len(q)):
word = q.popleft()
for i in range(m):
w = word[:i] + "*" + word[i + 1:]
if w in e:
for v in e[w]:
if v == endWord:
return d + 1
if v not in used:
q.append(v)
used.add(v)
e.pop(w)
return 0 | class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int count = 1;
Set<String> words = new HashSet<>(wordList);
Queue<String> q = new LinkedList<String>();
q.add(beginWord);
while(!q.isEmpty()) {
int size = q.size();
while(size-- > 0) {
String word = q.poll();
char[] chList = word.toCharArray();
for(int i=0; i<word.length(); i++) {
char tmp = chList[i];
for(char c='a'; c<='z'; c++) {
chList[i] = c;
String newWord = new String(chList);
if(words.contains(newWord)) {
if(newWord.equals(endWord)) {
return count + 1;
}
q.add(newWord);
words.remove(newWord);
}
}
chList[i] = tmp;
}
}
count++;
}
return 0;
}
} | // For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
// 1. Create a set and insert all wordList to the set to have
// easy search of O(1)
unordered_set<string> wordSet;
bool isEndWordPresent = false;
for (string s:wordList)
{
// Check if the destination string even present in the wordList
// If not then there is no point in even trying to find the
// route from source string to destination string
if (!isEndWordPresent && s.compare(endWord) == 0)
{
isEndWordPresent = true;
}
wordSet.insert(s);
}
// 2. If endWord is not present in the wordList return
if (!isEndWordPresent)
{
return 0;
}
// 3. Create a queue for BST insert the elements of currentlevel to the queue
// currentLevel is defined as all the strings that can be reached from
// all the strings of the previous string by just replacing one character
// and the one-char-replaced-string is present in the wordSet / wordList
queue<string> q;
q.push(beginWord);
int level = 0; // every time all the strings at this level are processed increment it
// 4. Loop through all the elements in the queue
while (!q.empty())
{
level++;
int numStringsInCurLevel = q.size();
// loop through all the strings in this current level
// and find out if destination can be reached before
// jumping to the next level of strings added to the queue
while (numStringsInCurLevel--)
{
string curStr = q.front();
q.pop();
for (int i=0; i<curStr.length(); i++)
{
string tempStr = curStr;
// Now check if swappin one char in the curStr will
// lead to any string in the wordSet
for (char c='a'; c<='z'; c++)
{
tempStr[i] = c;
if (tempStr.compare(curStr) == 0)
{
// Ignore the same string
continue;
}
// Check if we reached the destination
if (tempStr.compare(endWord) == 0)
{
return level+1;
}
if (wordSet.find(tempStr) != wordSet.end())
{
// this string is in the set so add it to the queue
// and remove it from the set
q.push(tempStr);
wordSet.erase(tempStr);
}
}
}
}
}
// If we are here then we couldn't reach destination
// even though the destination string is present in the wordList
// there is no path from source to destination for the given rules
return 0;
}
}; | /**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
// Logic is same as One direction, just from both side tword mid, much faster.
// One Direction solution is here ->
// https://leetcode.com/problems/word-ladder/discuss/2372376/Easy-Fast-Simple-83.95-235-ms-50.4-MB-One-Direction
var ladderLength = function(beginWord, endWord, wordList) {
const charMap = buildCharMap()
const wordSet = new Set(wordList)
if (!wordSet.has(endWord)) return 0
let leftSet = new Set([beginWord]), rightSet = new Set([endWord]), level = 1
const helper = (set1, set2) => {
const setArr = Array.from(set1)
for (let i = 0; i < setArr.length; i++) {
const word = setArr[i]
for (let i = 0; i < word.length; i++) {
for (const c of charMap) {
const newWord = word.slice(0, i) + c + word.slice(i + 1)
if (set2.has(newWord)) return true
if (wordSet.has(newWord)) {
set1.add(newWord)
wordSet.delete(newWord)
}
}
}
set1.delete(word)
}
}
while (leftSet.size && rightSet.size) {
level++
if (helper(leftSet, rightSet)) return level
level++
if (helper(rightSet, leftSet)) return level
}
return 0
};
const buildCharMap = () => {
const map = []
for (let i = 0; i < 26; i++) {
map.push(String.fromCharCode(i + 97))
}
return map
} | Word Ladder |
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
| class Solution:
def totalSteps(self, nums: List[int]) -> int:
st = []
ans = 0
for i in nums:
t = 0
while st and st[-1][0] <= i:
t = max(t, st.pop()[1])
x = 0
if st:
x = t+1
st.append([i, x])
ans = max(ans, x)
return ans | class Solution {
public int totalSteps(int[] nums) {
int n = nums.length;
int ans = 0;
Stack<Pair<Integer,Integer>> st = new Stack();
st.push(new Pair(nums[n-1],0));
for(int i=n-2;i>=0;i--)
{
int count = 0;
while(!st.isEmpty() && nums[i] > st.peek().getKey())
{
count = Math.max(count+1 , st.peek().getValue() );
st.pop();
}
ans = Math.max(ans , count);
st.push(new Pair(nums[i],count));
}
return ans;
}
} | class Solution {
public:
using pi = pair<int, int>;
int totalSteps(vector<int>& nums) {
int N = nums.size();
map<int, int> mp;
vector<pi> del; // stores pairs of (previous id, toDelete id)
for (int i = 0; i < N; ++i) {
mp[i] = nums[i];
if (i+1 < N && nums[i] > nums[i+1])
del.emplace_back(i, i+1);
}
int ans = 0; // number of rounds
while (!del.empty()) {
++ans;
vector<pi> nxt; // pairs to delete in the next round
for (auto [i,j] : del) mp.erase(j); // first, get rid of the required deletions
for (auto [i,j] : del) {
auto it = mp.find(i);
if ( it == end(mp) || next(it) == end(mp) ) // if it's not in the map anymore,
continue; // OR if it's the last element, skip it
auto itn = next(it); // now compare against next element in the ordering
if (it->second > itn->second)
nxt.emplace_back(it->first, itn->first); // add the (current id, toDelete id)
}
swap(nxt, del); // nxt is the new del
}
return ans;
}
}; | var totalSteps = function(nums) {
let stack = [],
dp = new Array(nums.length).fill(0),
max = 0
for (let i = nums.length - 1; i >= 0; i--) {
while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {
dp[i] = Math.max(++dp[i], dp[stack.pop()])
max = Math.max(dp[i], max)
}
stack.push(i)
}
return max
}; | Steps to Make Array Non-decreasing |
Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
Example 1:
Input: seats = [["#",".","#","#",".","#"],
[".","#","#","#","#","."],
["#",".","#","#",".","#"]]
Output: 4
Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam.
Example 2:
Input: seats = [[".","#"],
["#","#"],
["#","."],
["#","#"],
[".","#"]]
Output: 3
Explanation: Place all students in available seats.
Example 3:
Input: seats = [["#",".",".",".","#"],
[".","#",".","#","."],
[".",".","#",".","."],
[".","#",".","#","."],
["#",".",".",".","#"]]
Output: 10
Explanation: Place students in available seats in column 1, 3 and 5.
Constraints:
seats contains only characters '.' and'#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8
| class Solution:
def maxStudents(self, seats: List[List[str]]) -> int:
m, n = len(seats), len(seats[0])
match = [[-1]*n for _ in range(m)]
def dfs(i, j, visited):
for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]:
if 0 <= x < m and 0 <= y < n and seats[x][y] == "." and (x, y) not in visited:
visited.add((x, y))
if match[x][y] == -1 or dfs(*match[x][y], visited):
match[x][y] = (i, j)
match[i][j] = (x, y)
return True
return False
def max_matching():
cnt = 0
for i in range(m):
for j in range(0,n,2):
if seats[i][j] == '.' and match[i][j] == -1:
visited = set()
cnt += dfs(i, j, visited)
return cnt
#returns the number of elements of the maximum independent set in the bipartite set
return sum(seats[i][j]=='.' for i in range(m) for j in range(n)) - max_matching() | class Solution {
private Integer[][] f;
private int n;
private int[] ss;
public int maxStudents(char[][] seats) {
int m = seats.length;
n = seats[0].length;
ss = new int[m];
f = new Integer[1 << n][m];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (seats[i][j] == '.') {
ss[i] |= 1 << j;
}
}
}
return dfs(ss[0], 0);
}
private int dfs(int seat, int i) {
if (f[seat][i] != null) {
return f[seat][i];
}
int ans = 0;
for (int mask = 0; mask < 1 << n; ++mask) {
if ((seat | mask) != seat || (mask & (mask << 1)) != 0) {
continue;
}
int cnt = Integer.bitCount(mask);
if (i == ss.length - 1) {
ans = Math.max(ans, cnt);
} else {
int nxt = ss[i + 1];
nxt &= ~(mask << 1);
nxt &= ~(mask >> 1);
ans = Math.max(ans, cnt + dfs(nxt, i + 1));
}
}
return f[seat][i] = ans;
}
} | class Solution {
public:
int dp[8][(1 << 8) - 1];
int maxStudents(vector<vector<char>>& seats) {
memset(dp, -1, sizeof(dp));
return helper(seats, 0, 0);
}
int helper(vector<vector<char>>& seats, int prevAllocation, int idx) {
if (idx == seats.size()) return 0;
int sz = seats[0].size(), masks = ((1 << sz) - 1), maxi = 0;
// masks is for iterating over all subsets
if (dp[idx][prevAllocation] != -1) return dp[idx][prevAllocation];
while (masks >= 0) {
int curAllocation = 0, cnt = 0;
for (int i = 0; i < sz; i++) {
if (seats[idx][i] != '#' && masks >> i & 1) {
int ul = i - 1, ur = i + 1;
bool canPlace = true;
if (ul >= 0)
if (prevAllocation >> ul & 1 || curAllocation >> ul & 1)
canPlace = false;
if (ur < sz)
if (prevAllocation >> ur & 1 || curAllocation >> ur & 1)
canPlace = false;
if (canPlace) {
curAllocation |= 1 << i;
cnt++;
}
}
}
maxi = max(maxi, cnt + helper(seats, curAllocation, idx + 1));
masks--;
}
dp[idx][prevAllocation] = maxi;
return maxi;
}
}; | var maxStudents = function(seats) {
if (!seats.length) return 0;
// precalculate the seat that will be off the matrix
const lastPos = 1 << seats[0].length;
// encode the classroom into binary where 1 will be an available seat and 0 will be a broken seat
const classroom = seats.map((row) => (
row.reduce((a,c,i) => c === '#' ? a : (a | (1 << i)), 0))
);
// create a store to store the max seating for each row arrangment
// each row will be off +1 of seats rows
const dp = new Array(seats.length + 1).fill(null).map(() => new Map());
// since no one can sit at row=-1 set the max number of no one sitting on that row as 0
dp[0].set(0,0);
// iterate through every row in seats matrix
// remember that dp's rows are +1 of seats rows
for (let row = 0; row < seats.length; row++) {
// start with no one sitting on the row
let queue = [0];
// this will count the number of students sitting on this row
// we will increment this up as we add students to the row
let numStudents = 0;
while (queue.length > 0) {
// this will store all the different arrangments possible when we add 1 more student from the previous
const next = [];
// iterate through all the previous arrangements
// calculate the maximum number of students that can sit on current and all previous rows
// try adding a student to all possible available seats meeting the rules of the game
for (let arrangement of queue) {
// this calculates the maximum number of students that can sit with this row arrangment
// if the arrangement doesn't allow any students to sit in the previous row this will be handled
// by the 0 case in the previous row
// *see helper function that checks to see if the arrangement conflicts with the previous arrangment
let max = 0;
for (let [prevArrang, count] of dp[row]) {
if (conflicts(prevArrang, arrangement)) continue;
max = Math.max(max, count + numStudents);
}
dp[row + 1].set(arrangement, max);
// try adding an additional student to all elements in the row checking if it conflicts
// arrangement | i => adds the student to the arrangement
for (let i = 1; i < lastPos; i <<= 1) {
if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i);
}
}
queue = next;
numStudents++;
}
}
// return the maximum value from the last row
// the last row holds the maximum number of students for each arrangment
return Math.max(...dp[seats.length].values());
};
// this checks if the there are any students to the left or right of current arrangment
// curr << 1 => checks if there are any students to the left
// curr >> 1 => check if there are any students to the right
function conflicts(prev, curr) {
return (prev & (curr << 1)) || (prev & (curr >> 1));
}
// this checks if we can place the new student in this spot
// row & newStudent => checks if the classroom's row's seat is not broken
// arrangment & newStudent => will return truthy if there is a student sitting in that position (so we ! it because we don't want anyone sitting there)
// arrangement & (newStudent << 1) => will return truthy if there is a student sitting to the left of that position (so we ! it because we don't want anyone sitting there)
// arrangement & (newStudent >> 1) => will return truthy if there is a student sitting to the right of that position (so we ! it because we don't want anyone sitting there)
function canSit(row, arrangement, newStudent) {
return row & newStudent && !(arrangement & newStudent) && !(arrangement & (newStudent << 1)) && !(arrangement & (newStudent >> 1));
} | Maximum Students Taking Exam |
Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].
Example 1:
Input: n = 3
Output: 3
Example 2:
Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
Constraints:
1 <= n <= 231 - 1
| class Solution:
def findNthDigit(self, n: int) -> int:
low, high = 1, 0
place = 1
sum_ = 0
while True:
high = 10**place -1
digits_sum = (high - low +1 ) * place
if sum_<= n <= digits_sum + sum_:
break
else:
low = high+1
sum_+= digits_sum
place += 1
remaining_digits = n - sum_
position = (remaining_digits-1)//place
index_ = remaining_digits - position*place -1
number = low + position
# return str(number)[index_]
count = 0
index_ = place - 1 - index_
l = []
#
while number:
if count == index_:
return number%10
number = number//10
count+=1 | class Solution {
public int findNthDigit(int n) {
if(n < 10)
return n;
long currDigitIndex = 10;
int tillNextIncrease = 90;
int currNumberSize = 2;
int currNumber = 10;
int next = tillNextIncrease;
while(currDigitIndex < n) {
currNumber++;
currDigitIndex += currNumberSize;
next--;
if(next == 0) {
currNumberSize++;
tillNextIncrease *= 10;
next = tillNextIncrease;
}
}
int nthDigit = currNumber % 10;
if(currDigitIndex == n) {
while(currNumber != 0) {
nthDigit = currNumber % 10;
currNumber /= 10;
}
} else if(currDigitIndex > n) {
currNumber--;
while(currDigitIndex > n) {
currDigitIndex--;
nthDigit = currNumber % 10;
currNumber /= 10;
}
}
return nthDigit;
}
} | class Solution {
public:
#define ll long long
int findNthDigit(int n) {
if(n<=9) return n;
ll i=1;
ll sum=0;
while(true){
ll a=(9*pow(10,i-1))*i;
if(n-a<0){
break;
}
else{
sum+=9*pow(10,i-1);
n-=a;
}
i++;
}
ll x=0;
ll mod=n%i;
n=(n/i);
n+=sum;
if(mod==0) return n%10;
else{
n++;
ll x=i-mod;
while(x--){
n/=10;
}
}
return n%10;
}
}; | var findNthDigit = function(n) {
var len = 1;
var range = 9;
var base = 1;
while(n>len*range)
{
n -= len *range;
range *= 10;
base *= 10;
len++;
}
// [100, 101, 102,...]
// 100 should have offset 0, use (n-1) to make the counting index from 0-based.
var num = base + Math.floor((n-1)/len);
var s = num.toString();
return parseInt(s[(n-1)%len]);
}; | Nth Digit |
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Example 1:
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
Example 2:
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
Example 3:
Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.
Constraints:
maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j] is either '.' or '+'.
entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance will always be an empty cell.
| class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
x, y = entrance
m, n, infi = len(maze), len(maze[0]), int(1e5)
reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)
@lru_cache(None)
def dfs(i, j):
if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':
return infi
if reached(i, j):
return 0
maze[i][j] = '+'
ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))
maze[i][j] = '.'
return ans
ans = dfs(x, y)
return -1 if ans>=infi else ans | class Solution {
public int nearestExit(char[][] maze, int[] entrance) {
int rows = maze.length, cols = maze[0].length, queueSize;
Queue<int[]> queue = new LinkedList<>();
boolean[][] visited = new boolean[rows][cols];
int[] curr;
int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};
int x, y, steps = 0;
queue.offer(entrance);
visited[entrance[0]][entrance[1]] = true;
while (!queue.isEmpty()) {
queueSize = queue.size();
steps++;
for (int i=0;i<queueSize;i++) {
curr = queue.poll();
for (int[] dir: dirs) {
x = dir[0]+curr[0];
y = dir[1]+curr[1];
if (x<0||x>=rows||y<0||y>=cols) continue;
if (visited[x][y] || maze[x][y] == '+') continue;
// check if we have reached boundary
if (x==0||x==rows-1||y==0||y==cols-1) return steps;
queue.offer(new int[]{x, y});
visited[x][y] = true;
}
}
}
return -1;
}
} | class Solution {
public:
//checks if the coordinates of the cell are that of an unvisited valid empty cell
bool isValid(int x,int y,int n,int m, vector<vector<char>>& maze,vector<vector<int>>& visited){
if(x>=0 && x<n && y>=0 && y< m && maze[x][y]!='+' && visited[x][y]!=1){
return true;
}
return false;
}
//checks if the cell is a valid exit point
bool isExit(int x,int y,int startX,int startY, vector<vector<char>>& maze,vector<vector<int>>& visited){
if(x==startX && y==startY) return false;
if( (x==0 || x==maze.size()-1 || y==0 || y==maze[0].size()-1)
&& maze[x][y]!='+')
{
return true;
}
return false;
}
//main BFS function
int bfsHelper(vector<vector<char>>& maze,vector<vector<int>>& visited,int startX,int startY){
queue<vector<int>>Queue;
Queue.push({startX,startY,0});
while(!Queue.empty()){
int x = Queue.front()[0];
int y = Queue.front()[1];
int steps = Queue.front()[2];
Queue.pop();
//if you reach a valid exit, return the number of steps
if(isExit(x,y,startX,startY,maze,visited)) return steps;
int dx[4] = {0,-1,0,1};
int dy[4] = {-1,0,1,0};
//check in the 4 directions that you can travel
for(int i=0;i<4;i++){
int newX = x+dx[i] , newY = y+dy[i];
//if the coordinates of the cell are that of
//an unvisited valid empty cell, add it to the queue
//and mark it as visited.
if(isValid(newX,newY,maze.size(),maze[0].size(),maze,visited)){
Queue.push({newX,newY,steps+1});
visited[newX][newY] = 1;
}
}
}
//if you could not find a valid exit point, return -1
return -1;
}
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int n = maze.size();
int m = maze[0].size();
//create a 2d matrix and mark all the cells as -1,
//denoting that they have not been visited yet.
vector<vector<int>>visited(n,vector<int>(m,-1));
return bfsHelper(maze,visited,entrance[0],entrance[1]);
}
}; | function nearestExit(maze, entrance) {
const queue = []; // queue for bfs
const empty = ".";
const [height, width] = [maze.length, maze[0].length];
const tried = [...Array(height)].map(() => Array(width).fill(false));
const tryStep = (steps, row, col) => {
// don't reuse once it's already been tried
if (tried[row][col]) return;
tried[row][col] = true;
if (maze[row][col] !== empty) return; // blocked? i.e. can't step
queue.push([steps, row, col]);
};
const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };
const trySteppableDirs = (steps, row, col) => {
// try steppable directions
if (col < edges.right) tryStep(steps, row, col + 1);
if (row < edges.bottom) tryStep(steps, row + 1, col);
if (col > edges.left) tryStep(steps, row, col - 1);
if (row > edges.top) tryStep(steps, row - 1, col);
};
let steps = 1, [row, col] = entrance;
tried[row][col] = true; // don't reuse the entrance
trySteppableDirs(steps, row, col);
while (queue.length > 0) { // bfs
[steps, row, col] = queue.shift();
// path to the edge found?
if (col === edges.left || col === edges.right) return steps;
if (row === edges.top || row === edges.bottom) return steps;
trySteppableDirs(steps + 1, row, col);
}
// NO path to the edge found
return -1;
} | Nearest Exit from Entrance in Maze |
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution class:
Solution(int[] nums) Initializes the object with the integer array nums.
int[] reset() Resets the array to its original configuration and returns it.
int[] shuffle() Returns a random shuffling of the array.
Example 1:
Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
// Any permutation of [1,2,3] must be equally likely to be returned.
// Example: return [3, 1, 2]
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
Constraints:
1 <= nums.length <= 50
-106 <= nums[i] <= 106
All the elements of nums are unique.
At most 104 calls in total will be made to reset and shuffle.
| import random
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def reset(self) -> List[int]:
return self.nums
def shuffle(self) -> List[int]:
shuffled_array = self.nums.copy()
# randomly generates the idx of the element that'll be the ith element of the array
for i in range(len(self.nums) - 1, 0, -1):
idx = random.randint(0, i)
shuffled_array[i], shuffled_array[idx] = shuffled_array[idx], shuffled_array[i]
return shuffled_array | class Solution {
int a[];
int b[];
public Solution(int[] nums) {
a=nums.clone();
b=nums.clone();
}
public int[] reset() {
a=b.clone();
return a;
}
public int[] shuffle() {
for(int i=0;i<a.length;i++){
int ren=(int)(Math.random()*a.length);
int temp= a[ren];
a[ren]=a[i];
a[i]=temp;
}
return a;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/ | class Solution {
public:
vector<int> ans;
vector<int> res;
Solution(vector<int>& nums) {
ans=nums;
res=nums;
}
vector<int> reset() {
return res;
}
vector<int> shuffle() {
next_permutation(ans.begin(),ans.end());
return ans;
}
}; | var Solution = function(nums) {
this.nums = nums;
this.resetArray = [...nums];
};
Solution.prototype.reset = function() {
return this.resetArray;
};
Solution.prototype.shuffle = function() {
const n = this.nums.length;
const numsArray = this.nums;
for (let i = 0; i < n; i++) {
const j = Math.floor(Math.random() * (n - i)) + i;
const tmp = numsArray[i];
numsArray[i] = numsArray[j];
numsArray[j] = tmp;
}
return numsArray;
}; | Shuffle an Array |
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]]
Output: 0
Example 3:
Input: matrix = [["1"]]
Output: 1
Constraints:
rows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j] is '0' or '1'.
| class Solution:
def maxArea(self,arr: List[List[int]]) -> int:
maxA = 0 #local max variable to return max area of a 1D array
stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing
arr.append(-1) # value for stack index -1 and one extra iteration to empty the stack
for i in range(len(arr)): # traversing for stack from left to right
arr[i] = int(arr[i]) # we are getting str value from matrix
while stack and arr[stack[-1]] >= int(arr[i]): #stack is non empty and stack top is greater or equal to current element
index = stack.pop() #pop greater element from stack and finds its area
width = i - stack[-1] - 1 if stack else i # for empty stack width is len of 1D arr, and after poping if we have element in stack then it becomes left boundary and current index as right boundary
maxA = max(maxA, width * arr[index]) # geting max area (L * B)
stack.append(int(i)) # inserting each element in stack
return maxA # return the max area
"""Below is the code for adding each row one by one and passing it to above function to get the max area for each row"""
# r1 - 1 0 1 0 0
# r2 - 1 0 1 1 1
# r = 2 0 2 1 1 This is for else condition
# r1 - 1 1 1 0 1
# r2 - 1 0 1 1 0
# r = 2 0 2 1 0 This is for if condition
def maximalRectangle(self, matrix: List[List[str]]) -> int:
result = [0] * len(matrix[0])
maxReact = 0
maxReact = self.maxArea(result)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if matrix[i][j] == 0:
result[j] = 0
else:
result[j] = result[j] + matrix[i][j]
maxReact = max(maxReact,self.maxArea(result)) #after getting max area for 1D arr we are getting max value from those 1D arr for the 2D arr
return maxReact | class Solution {
public int maximalRectangle(char[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int n = matrix[0].length;
for(int i=0; i<n; i++){
list.add(Character.getNumericValue(matrix[0][i]));
}
int maxArea = maximumArea(list);
int m = matrix.length;
for(int i=1; i<m; i++){
for(int j=0; j<n; j++){
if(matrix[i][j] == '1'){
list.set(j, Character.getNumericValue(matrix[i][j]) + list.get(j));
}else
list.set(j, 0);
}
maxArea = Math.max(maxArea, maximumArea(list));
}
return maxArea;
}
public int maximumArea(ArrayList<Integer> heights) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
int n = heights.size();
int[] left = new int[n];
int[] right = new int[n];
int[] width = new int[n];
for(int i=0; i<n; i++){
while(!stack1.isEmpty() && heights.get(stack1.peek()) >= heights.get(i))
stack1.pop();
if(!stack1.isEmpty())
left[i] = stack1.peek();
else
left[i] = -1;
stack1.push(i);
}
for(int i=n-1; i>=0; i--){
while(!stack2.isEmpty() && heights.get(stack2.peek()) >= heights.get(i))
stack2.pop();
if(!stack2.isEmpty())
right[i] = stack2.peek();
else
right[i] = n;
stack2.push(i);
}
for(int i=0; i<n; i++){
width[i] = right[i] - left[i] - 1;
}
int mxArea = 0;
for(int i=0; i<n; i++){
mxArea = Math.max(mxArea, width[i] * heights.get(i));
}
return mxArea;
}
} | class Solution {
private:
vector<int> nextSmallerElement(int *arr , int n){
stack<int> st;
st.push(-1);
vector<int> ans(n);
for(int i = n - 1 ; i >= 0 ; i--){
int curr = arr[i];
while(st.top() != -1 && arr[st.top()] >= curr){
st.pop();
}
ans[i] = st.top();
st.push(i);
}
return ans;
}
vector<int> prevSmallerElement(int *arr , int n){
stack<int> st;
st.push(-1);
vector<int> ans(n);
for(int i = 0; i < n ; i++){
int curr = arr[i];
while(st.top() != -1 && arr[st.top()] >= curr){
st.pop();
}
ans[i] = st.top();
st.push(i);
}
return ans;
}
int largestRectangleArea(int * heights , int n){
int area = INT_MIN;
vector<int> next(n);
next = nextSmallerElement(heights , n);
vector<int> prev(n);
prev = prevSmallerElement(heights , n);
for(int i = 0 ; i < n ; i++){
int length = heights[i];
if(next[i] == -1)
next[i] = n;
int breadth = next[i] - prev[i] - 1;
int newArea = length * breadth;
area = max(area , newArea);
}
return area;
}
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
int M[n][m];
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
M[i][j] = matrix[i][j] - '0';
}
}
//step 1 : compute area of 1st row
int area = largestRectangleArea(M[0] , m);
for(int i = 1 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
//step 2 : add upar wala element if it is 1
if(M[i][j] != 0)
M[i][j] = M[i][j] + M[i-1][j];
else
M[i][j] = 0;
}
area = max(area , largestRectangleArea(M[i] , m));
}
return area;
}
}; | var maximalRectangle = function(matrix) {
const m = matrix.length;
const n = matrix[m - 1].length;
const prefixSum = new Array(m).fill().map(() => new Array(n).fill(0));
for(let i = 0; i < m; i += 1) {
for(let j = 0; j < n; j += 1) {
prefixSum[i][j] = parseInt(matrix[i][j]);
if(i > 0 && prefixSum[i][j] > 0) {
prefixSum[i][j] += prefixSum[i - 1][j];
}
}
}
const getArea = (currentRow) => {
let max = 0;
for(let i = 0; i < n; i += 1) {
const height = currentRow[i];
let leftBoundary = i;
while(leftBoundary >= 0 && currentRow[leftBoundary] >= currentRow[i]) {
leftBoundary -= 1;
}
let rightBoundary = i;
while(rightBoundary < n && currentRow[rightBoundary] >= currentRow[i]) {
rightBoundary += 1;
}
const width = rightBoundary - leftBoundary - 1;
max = Math.max(max, height * width);
}
return max;
}
let max = 0;
for(let i = 0; i < m; i += 1) {
max = Math.max(max, getArea(prefixSum[i]));
}
return max;
}; | Maximal Rectangle |
A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East".
The robot can be instructed to move for a specific number of steps. For each step, it does the following.
Attempts to move forward one cell in the direction it is facing.
If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.
After the robot finishes moving the number of steps required, it stops and awaits the next instruction.
Implement the Robot class:
Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing "East".
void step(int num) Instructs the robot to move forward num steps.
int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
String getDir() Returns the current direction of the robot, "North", "East", "South", or "West".
Example 1:
Input
["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"]
[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
Output
[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]
Explanation
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.step(2); // It moves two steps East to (2, 0), and faces East.
robot.step(2); // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return [4, 0]
robot.getDir(); // return "East"
robot.step(2); // It moves one step East to (5, 0), and faces East.
// Moving the next step East would be out of bounds, so it turns and faces North.
// Then, it moves one step North to (5, 1), and faces North.
robot.step(1); // It moves one step North to (5, 2), and faces North (not West).
robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.
// Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return [1, 2]
robot.getDir(); // return "West"
Constraints:
2 <= width, height <= 100
1 <= num <= 105
At most 104 calls in total will be made to step, getPos, and getDir.
| class Robot:
def __init__(self, width: int, height: int):
self.perimeter = 2*width + 2*(height - 2)
self.pos = 0
self.atStart = True
self.bottomRight = width - 1
self.topRight = self.bottomRight + (height - 1)
self.topLeft = self.topRight + (width - 1)
def step(self, num: int) -> None:
self.atStart = False
self.pos = (self.pos + num) % self.perimeter
def getPos(self) -> List[int]:
if 0 <= self.pos <= self.bottomRight:
return [self.pos, 0]
if self.bottomRight < self.pos <= self.topRight:
return [self.bottomRight, self.pos - self.bottomRight]
if self.topRight < self.pos <= self.topLeft:
return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]
return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]
def getDir(self) -> str:
if self.atStart or 0 < self.pos <= self.bottomRight:
return 'East'
if self.bottomRight < self.pos <= self.topRight:
return 'North'
if self.topRight < self.pos <= self.topLeft:
return 'West'
return 'Sout | class Robot {
int p;
int w;
int h;
public Robot(int width, int height) {
w = width - 1;
h = height - 1;
p = 0;
}
public void step(int num) {
p += num;
}
public int[] getPos() {
int remain = p % (2 * (w + h));
if (remain <= w)
return new int[]{remain, 0};
remain -= w;
if (remain <= h)
return new int[]{w, remain};
remain -= h;
if (remain <= w)
return new int[]{w - remain, h};
remain -= w;
return new int[]{0, h - remain};
}
public String getDir() {
int[] pos = getPos();
if (p == 0 || pos[1] == 0 && pos[0] > 0)
return "East";
else if (pos[0] == w && pos[1] > 0)
return "North";
else if (pos[1] == h && pos[0] < w)
return "West";
else
return "South";
}
} | class Robot {
private:
int width, height, perimeter;
int dir = 0;
int x = 0, y = 0;
map<int, string> mp = {{0, "East"}, {1, "North"}, {2, "West"}, {3, "South"}};
public:
Robot(int width, int height) {
this->width = width;
this->height = height;
this->perimeter = 2 * (height + width) - 4;
}
void step(int num) {
if(!num) return;
num = num % perimeter;
if(x == 0 && y == 0 && num == 0) dir = 3;
while(num--){
if(x == 0 && y == 0) dir = 0;
else if(x == width-1 && y == 0) dir = 1;
else if(x == width-1 && y == height-1) dir = 2;
else if(x == 0 && y == height-1) dir = 3;
if(dir == 0) x += 1;
if(dir == 1) y += 1;
if(dir == 2) x -= 1;
if(dir == 3) y -= 1;
}
}
vector<int> getPos() {
return {x, y};
}
string getDir() {
return mp[dir];
}
}; | const EAST = "East";
const NORTH = "North";
const WEST = "West";
const SOUTH = "South";
const DIRECTIONS = [EAST, NORTH, WEST, SOUTH];
const ORIGIN = [0,0];
/**
* @param {number} width
* @param {number} height
*/
var Robot = function(width, height) {
this.width = width;
this.height = height;
this.path = []; // circular buffer of entire path of robot
this.dirAtSquare = []; // dir robot is facing at each square
this.currentPos = -1;
this.preprocess();
};
/**
* Loop around the map once and store the path into a circular buffer.
*
* (0,0) is set to face SOUTH. The only time it is EAST is at the beginning
* if the robot didn't move at all.
*
* @return {void}
*/
Robot.prototype.preprocess = function() {
// go right
for (let i = 1; i < this.width; i++) {
this.path.push([i, 0]);
this.dirAtSquare.push(0);
}
// go up
const xMax = this.width - 1;
for (let i = 1; i < this.height; i++) {
this.path.push([xMax, i]);
this.dirAtSquare.push(1);
}
// go left
const yMax = this.height - 1;
for (let i = xMax - 1; i >= 0; i--) {
this.path.push([i, yMax]);
this.dirAtSquare.push(2);
}
// go down
const xMin = 0;
for (let i = yMax - 1; i >= 0; i--) {
this.path.push([xMin, i]);
this.dirAtSquare.push(3);
}
}
/**
* @param {number} num
* @return {void}
*/
Robot.prototype.step = function(num) {
this.currentPos += num;
};
/**
* @return {number[]}
*/
Robot.prototype.getPos = function() {
return this.currentPos === -1
? ORIGIN // we haven't moved
: this.path[this.currentPos % this.path.length];
};
/**
* @return {string}
*/
Robot.prototype.getDir = function() {
return this.currentPos === -1
? DIRECTIONS[0] // we haven't moved
: DIRECTIONS[this.dirAtSquare[this.currentPos % this.dirAtSquare.length]];
};
/**
* Your Robot object will be instantiated and called as such:
* var obj = new Robot(width, height)
* obj.step(num)
* var param_2 = obj.getPos()
* var param_3 = obj.getDir()
*/ | Walking Robot Simulation II |
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].
When a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product).
The supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100).
Implement the Cashier class:
Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices.
double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.
Example 1:
Input
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
Output
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
Explanation
Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);
cashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount.
// bill = 1 * 100 + 2 * 200 = 500.
cashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount.
// bill = 10 * 300 + 10 * 100 = 4000.
cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount.
// Original bill = 1600
// Actual bill = 1600 * ((100 - 50) / 100) = 800.
cashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount.
cashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount.
cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.
// Original bill = 14700, but with
// Actual bill = 14700 * ((100 - 50) / 100) = 7350.
cashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6th customer, no discount.
Constraints:
1 <= n <= 104
0 <= discount <= 100
1 <= products.length <= 200
prices.length == products.length
1 <= products[i] <= 200
1 <= prices[i] <= 1000
The elements in products are unique.
1 <= product.length <= products.length
amount.length == product.length
product[j] exists in products.
1 <= amount[j] <= 1000
The elements of product are unique.
At most 1000 calls will be made to getBill.
Answers within 10-5 of the actual value will be accepted.
| class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.n = n
self.discount = discount
self.price = { }
self.customer = 0
for i in range(len(products)) :
self.price[products[i]] = prices[i]
def getBill(self, product: List[int], amount: List[int]) -> float:
self.customer += 1
bill = 0
for i in range(len(product)) :
bill += amount[i] * self.price[product[i]]
if self.customer == self.n :
bill = bill * (1 - self.discount / 100)
self.customer = 0
return bill
# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount) | class Cashier {
private Map<Integer, Integer> catalogue;
private int n;
private double discount;
private int orderNumber;
public Cashier(int n, int discount, int[] products, int[] prices) {
this.catalogue = new HashMap<>();
for (int i = 0; i < prices.length; i++) {
this.catalogue.put(products[i], prices[i]);
}
this.n = n;
this.discount = ((double) 100 - discount)/100;
this.orderNumber = 0;
}
public double getBill(int[] product, int[] amount) {
this.orderNumber++;
double bill = 0.0;
for (int i = 0; i < amount.length; i++) {
int p = product[i];
int price = this.catalogue.get(p);
bill += price*amount[i];
}
if (this.orderNumber % n == 0)
bill *= this.discount;
return bill;
}
}
/**
* Your Cashier object will be instantiated and called as such:
* Cashier obj = new Cashier(n, discount, products, prices);
* double param_1 = obj.getBill(product,amount);
*/ | class Cashier {
public:
int nn = 0;
double dis = 0;
vector<int> pro;
vector<int> pri;
int currCustomer = 0; //Declaring these variables here to use it in other fxns as well
Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {
nn = n;
dis = discount;
pro = products;
pri = prices; //Assigning given values to our created variables
}
double getBill(vector<int> product, vector<int> amount) {
currCustomer++; //Increasing customer count
double bill = 0; //Bill anount set to 0
for(int i = 0; i < product.size(); i++){ //Iterating over every product
int proId = 0;
while(pro[proId] != product[i]) proId++; //Finding product ID index
bill = bill + (amount[i]*pri[proId]); //Adding total amount to bill
}
if(currCustomer == nn){ //Checking if the customer is eligible for discount
bill = bill * (1 - dis/100); //Giving discount
currCustomer = 0; //Setting customer count to 0 so next third person can have discount
}
return bill; //Returning final bill amount
}
}; | var Cashier = function(n, discount, products, prices) {
this.n = n;
this.cc = 0;
this.discount = (100 - discount) / 100;
this.products = new Map();
const len = products.length;
for(let i = 0; i < len; i++) {
this.products.set(products[i], prices[i]);
}
};
Cashier.prototype.getBill = function(product, amount) {
let total = 0, len = product.length;
for(let i = 0; i < len; i++) {
total += amount[i] * this.products.get(product[i]);
}
this.cc++;
if(this.cc % this.n == 0) {
total = total * this.discount;
this.cc = 0;
}
return total;
}; | Apply Discount Every n Orders |
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Constraints:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
All elements of candidates are distinct.
1 <= target <= 500
| class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
path = []
answer = []
def dp(idx, total):
if total == target:
answer.append(path[:])
return
if total > target:
return
for i in range(idx, len(candidates)):
path.append(candidates[i])
dp(i, total + candidates[i])
path.pop()
dp(0, 0)
return answer | class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> cur = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
dfs(0, candidates, target, 0, cur, result);
return result;
}
public void dfs(int start, int[] candidates, int target, int sum, List<Integer> cur, List<List<Integer>> result){
if(sum == target){
result.add(new ArrayList<>(cur));
return;
}
for(int i = start; i < candidates.length; i++) {
if(sum + candidates[i] <= target) {
cur.add(candidates[i]);
dfs(i, candidates, target, sum + candidates[i], cur, result);
cur.remove((cur.size()- 1));
}
}
return;
}
} | class Solution {
void combination(vector<int>& candidates, int target, vector<int> currComb, int currSum, int currIndex, vector<vector<int>>& ans){
if(currSum>target) return; //backtrack
if(currSum==target){
ans.push_back(currComb); //store the solution and backtrack
return;
}
for(int i=currIndex; i<candidates.size(); i++){ //try all possible options for the next level
currComb.push_back(candidates[i]); //put 1 option into the combination
currSum+=candidates[i];
combination(candidates, target, currComb, currSum, i, ans); //try with this combination, whether it gives a solution or not.
currComb.pop_back(); //when this option backtrack to here, remove this and go on to the next option.
currSum-=candidates[i];
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> currComb;
combination(candidates, target, currComb, 0, 0, ans);
return ans;
}
}; | function recursion(index, list, target, res, arr){
if(index == arr.length){
if(target == 0){
res.push([...list]);
}
return;
}
if(arr[index] <= target){
list.push(arr[index]);
recursion(index, list, target - arr[index], res, arr);
list.pop();
}
recursion(index + 1, list, target, res, arr);
}
var combinationSum = function(candidates, target) {
let res = [];
recursion(0, [], target, res, candidates);
return res;
}; | Combination Sum |
You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
Example 1:
Input: matrix = [[1,-1],[-1,1]]
Output: 4
Explanation: We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
Example 2:
Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
Output: 16
Explanation: We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
Constraints:
n == matrix.length == matrix[i].length
2 <= n <= 250
-105 <= matrix[i][j] <= 105
| class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
# count -'s
count = 0
for row in matrix:
for col_num in row:
if col_num < 0:
count += 1
tot_sum = sum([sum([abs(x) for x in row])
for row in matrix])
if count % 2 == 0:
return tot_sum
else:
min_val = min([min([abs(x) for x in row])
for row in matrix])
return tot_sum - 2 * min_val | class Solution {
public long maxMatrixSum(int[][] matrix) {
long ans = 0;
int neg = 0;
int min = Integer.MAX_VALUE;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] < 0) {
neg++;
}
ans += Math.abs(matrix[i][j]);
if(min > Math.abs(matrix[i][j]))
min = Math.abs(matrix[i][j]);
}
}
if(neg % 2 == 0)
return ans;
else
return ans - 2*min;
}
} | /**
* @author : archit
* @GitHub : archit-1997
* @Email : [email protected]
* @file : maximumMatrixSum.cpp
* @created : Saturday Aug 21, 2021 20:11:56 IST
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
long long maxMatrixSum(vector<vector<int>>& matrix) {
int r=matrix.size(),c=matrix[0].size();
//we need to find the min number in the matrix and also count of negative numbers in the matrix
int small=INT_MAX,count=0;
long long int sum=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
int val=matrix[i][j];
//finding the smallest absolute value in the matrix
small=min(small,abs(val));
//counting the negative numbers
if(val<0)
count++;
//finding the sum of all the values
sum+=abs(val);
}
}
//if even number of negatives, then just return sum
if(count%2==0)
return sum;
else
//subtract the value of the min absolute element
return sum-2*small;
}
}; | var maxMatrixSum = function(matrix) {
const MAX= Number.MAX_SAFE_INTEGER;
const m = matrix.length;
const n = matrix[0].length;
let negs = 0;
let totAbsSum = 0;
let minAbsNum = MAX;
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
if (matrix[i][j] < 0) ++negs;
totAbsSum += Math.abs(matrix[i][j]);
minAbsNum = Math.min(minAbsNum, Math.abs(matrix[i][j]));
}
}
if (negs % 2 === 1) totAbsSum -= (2 * minAbsNum);
return totAbsSum;
}; | Maximum Matrix Sum |
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] is 0 or 1
| from collections import *
class Solution:
def maxDistance(self, grid) -> int:
m,n=len(grid),len(grid[0])
queue=deque([])
for i in range(m):
for j in range(n):
if grid[i][j]==1:
queue.append((i,j))
c=-1
while queue:
# print(queue)
temp=len(queue)
for _ in range(temp):
(i,j)=queue.popleft()
for (x,y) in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):
if x < 0 or x >= m or y < 0 or y >= n or grid[x][y]==1:
continue
grid[x][y]=1
queue.append((x,y))
c+=1
return c if c!=0 else -1 | class Solution {
class Point {
int x, y;
public Point(int x, int y){
this.x=x;
this.y=y;
}
}
int[][] dist;
int n,ans;
int[] dx={0, 0, +1, -1};
int[] dy={+1, -1, 0, 0};
public int maxDistance(int[][] grid) {
n=grid.length;
dist = new int[n][n];
Queue<Point> q = new LinkedList<>();
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (grid[i][j]==0) dist[i][j]=2*1000*1000*1000;
else {
dist[i][j]=0;
q.add(new Point(i, j)); // multisource on grid[i][j] = 1
}
}
}
ans=-1;
while(!q.isEmpty()){
Point p = q.poll();
int x = p.x;
int y = p.y;
for (int k = 0; k < 4; k++) {
int r=dx[k]+x;
int c=dy[k]+y;
if (valid(r,c)&&grid[r][c]==0&&dist[r][c]>dist[x][y]+1){
dist[r][c]=dist[x][y]+1;
Point newP = new Point(r,c);
q.add(newP);
}
}
}
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
ans=Math.max(ans,dist[i][j]); // Manhattan distance is the same as the distance on the grid in general
}
}
if (ans==0||ans==2*1000*1000*1000) ans=-1;
return ans;
}
public boolean valid(int r, int c){
return r>=0&&c>=0&&r<n&&c<n;
}
} | class Solution {
vector<int> dr = {0,0,1,-1};
vector<int> dc = {1,-1,0,0};
public:
bool isPos(int r,int c,int n){
return ( r>=0 && c>=0 && r<n && c<n );
}
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size();
vector< vector<int> > dist(n,vector<int>(n,-1));
queue< vector<int> > pq;
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<n ; j++){
if( 1==grid[i][j] ){
dist[i][j] = 0;
pq.push({i,j});
}
}
}
int ans = 0;
while( !pq.empty() ){
vector<int> vect = pq.front();
pq.pop();
int r = vect[0];
int c = vect[1];
if( 0==grid[r][c] ){
ans = max(ans,dist[r][c]);
}
for(int i=0 ; i<4 ; i++){
int nr = r+dr[i];
int nc = c+dc[i];
if( isPos(nr,nc,n) && -1==dist[nr][nc] ){
dist[nr][nc] = dist[r][c]+1;
pq.push({nr,nc});
}
}
}
return (ans==0 ? -1 : ans);
}
}; | /**
* @param {number[][]} grid
* @return {number}
*/
const DIR = [
[0,1],
[0,-1],
[1,0],
[-1,0]
];
var maxDistance = function(grid) {
const ROWS = grid.length;
const COLS = grid[0].length;
const cost = new Array(ROWS).fill().map(()=>new Array(COLS).fill(Infinity));
const que = [];
for(let row=0; row<ROWS; row++) {
for(let col=0; col<COLS; col++) {
if(grid[row][col] === 1) {
que.push([row, col]);
cost[row][col] = 0;
}
}
}
if(que.length == 0 || que.length == ROWS * COLS) return -1;
while(que.length) {
const [row, col] = que.shift();
for(const dir of DIR) {
const newRow = row+dir[0];
const newCol = col+dir[1];
if(newRow < 0 || newCol < 0 || newRow >= ROWS || newCol >= COLS) continue;
if(cost[newRow][newCol] > cost[row][col] + 1) {
cost[newRow][newCol] = cost[row][col] + 1;
que.push([newRow, newCol]);
}
}
}
let max = 0;
for(const row of cost) {
max = Math.max(max, ...row);
}
return max;
}; | As Far from Land as Possible |
There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.
You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.
You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].
Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.
Example 1:
Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].
The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.
Example 2:
Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]
Output: [1,1]
Example 3:
Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]
Output: [1,1,0]
Constraints:
1 <= n <= 109
0 <= lamps.length <= 20000
0 <= queries.length <= 20000
lamps[i].length == 2
0 <= rowi, coli < n
queries[j].length == 2
0 <= rowj, colj < n
| class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
rows = collections.Counter()
cols = collections.Counter()
diags1 = collections.Counter()
diags2 = collections.Counter()
lamps = {tuple(lamp) for lamp in lamps}
for i, j in lamps:
rows[i] += 1
cols[j] += 1
diags1[i + j] += 1
diags2[i - j] += 1
ans = []
directions = ((-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 0), (0, 1),
(1, -1), (1, 0), (1, 1))
for i, j in queries:
if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:
ans.append(1)
else:
ans.append(0)
for di, dj in directions:
newI, newJ = i + di, j + dj
if (newI, newJ) not in lamps:
continue
lamps.remove((newI, newJ))
rows[newI] -= 1
cols[newJ] -= 1
diags1[newI + newJ] -= 1
diags2[newI - newJ] -= 1
return ans | class Solution {
public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {
//we take 5 hashmap
//1st hashmap for row
HashMap<Integer, Integer> row = new HashMap<>();
//2nd hashmap for column
HashMap<Integer, Integer> col = new HashMap<>();
//3rd hashmap for lower diagonal
HashMap<Integer, Integer> d1 = new HashMap<>();
//4th diagonal for upper diagonal
HashMap<Integer, Integer> d2 = new HashMap<>();
//5th diagonal for cell no meaning lamp is present at this spot
HashMap<Integer, Integer> cellno = new HashMap<>();
for(int i = 0;i<lamps.length;i++){
//get row and column from lamps array
int row1 = lamps[i][0];
int col1 = lamps[i][1];
//place row in row hashmap
row.put(row1, row.getOrDefault(row1, 0) + 1);
//place column in col hashmap
col.put(col1, col.getOrDefault(col1, 0) + 1);
//place d1 dia in d1
d1.put((row1+col1), d1.getOrDefault((row1+col1), 0) + 1);
//place d2 diagonal
d2.put((row1-col1), d2.getOrDefault((row1-col1), 0) + 1);
//place cellno in cell no hashmap
int cell = row1*n+col1;
cellno.put(cell, cellno.getOrDefault(cell, 0) + 1);
}
//direction array which travels in 8 adjacent direction
int[][] dir = {{-1, 0},{-1, 1},{0, 1},{1, 1},{1, 0},{1, -1},{0, -1},{-1, -1}};
int[] ans = new int[queries.length];
//process all queries
for(int i = 0;i<queries.length;i++){
int row1 = queries[i][0];
int col1 = queries[i][1];
int cell = row1 * n + col1;
ans[i] = (row.containsKey(row1) || col.containsKey(col1) || d1.containsKey(row1 + col1) || d2.containsKey(row1-col1) || cellno.containsKey(cell))? 1:0;
//if query has a bulb
if(cellno.containsKey(cell)){
int val = cellno.get(cell);
cellno.remove(cell);
//for row
if(row.containsKey(row1)){
int rowval = row.get(row1);
rowval-=val;
if(rowval == 0){
row.remove(row1);
}else{
row.put(row1, rowval);
}
}
//for col
if(col.containsKey(col1)){
int colval = col.get(col1);
colval-=val;
if(colval == 0){
col.remove(col1);
}else{
col.put(col1, colval);
}
}
//for d1
if(d1.containsKey(row1+col1)){
int d1val = d1.get(row1+col1);
d1val-=val;
if(d1val == 0){
d1.remove(row1+col1);
}else{
row.put((row1+col1), d1val);
}
}
//for d2
if(d2.containsKey(row1 - col1)){
int d2val = d2.get(row1-col1);
d2val-=val;
if(d2val == 0){
d2.remove(row1-col1);
}else{
d2.put((row1-col1), d2val);
}
}
}
//moves all 8 direction and remove the illumination
for(int j = 0;j<dir.length;j++){
int rowdash = row1 + dir[j][0];
int coldash = col1 + dir[j][1];
int cellno1 = rowdash * n + coldash;
if(cellno.containsKey(cellno1)){
int val = cellno.get(cellno1);
cellno.remove(cellno1);
//for row
if(row.containsKey(rowdash)){
int rowval = row.get(rowdash);
rowval -= val;
if(rowval == 0){
row.remove(rowdash);
}else{
row.put(rowdash, rowval);
}
}
//for col
if(col.containsKey(coldash)){
int colval = col.get(coldash);
colval-=val;
if(colval == 0){
col.remove(coldash);
}else{
col.put(coldash, colval);
}
}
//for d1
if(d1.containsKey(rowdash+coldash)){
int d1val = d1.get(rowdash+coldash);
d1val-=val;
if(d1val == 0){
d1.remove(rowdash+coldash);
}else{
row.put((rowdash+coldash), d1val);
}
}
//for d2
if(d2.containsKey(rowdash - coldash)){
int d2val = d2.get(rowdash-coldash);
d2val-=val;
if(d2val == 0){
d2.remove(rowdash-coldash);
}else{
d2.put((rowdash-coldash), d2val);
}
}
}
}
}
return ans;
}
} | class Solution {
public:
// store info about rows , coulms and diagonal that is illuminated
// if (i,j) is lamp , then every cell (x,y) is illuminated if
// x==i (row) || y==j (column) || x+y == i+j (anti diagonal) || x-y == i-j (main diagonal)
vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
vector<int>ans;
unordered_map<int,int>row,col,mainDiag,antiDiag;
set<pair<int,int>>s;
for(auto &l : lamps){
int x = l[0],y=l[1];
// Even if the same lamp is listed more than once, it is turned on.
// To prevent duplicate entries
if(s.find({x,y}) == s.end())
{
row[x]++;
col[y]++;
antiDiag[x+y]++;
mainDiag[x-y]++;
s.insert({x,y}); // This helps us to get the lamp in O(1)
}
}
for(auto &q : queries)
{
// For every query {x,y} do 2 things :
// 1. Check whether grid[x][y] is illuminated or not, accordingly set answer either to '1' OR '0'
// 2. if grid is illuminated, turn off the lamps at {x,y} and 8 adjacent lamps = 9 lamps
int x = q[0],y = q[1];
if(row[x]>0 or col[y]>0 or antiDiag[x+y]>0 or mainDiag[x-y]>0)
{
// illumination
ans.push_back(1);
// Turn off the 9 lamps = 1 center and 8 adjacent lamps
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
int nx = x+i;
int ny = y+j;
// NxN board, check boundaries condition
if(nx >= 0 and nx < n and ny >=0 and ny < n and s.find({nx,ny})!=s.end())
{
row[nx]--;
col[ny]--;
antiDiag[nx+ny]--;
mainDiag[nx-ny]--;
s.erase({nx,ny});
}
}
}
}
else // No illumination
ans.push_back(0);
}
return ans;
}
}; | var gridIllumination = function(n, lamps, queries) {
const directions = [[0,0], [-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]];
const lampCoord = new Map();
const rowHash = {}, colHash = {}, leftDiag = {}, rightDiag = {};
// First, illuminate the lamps
for (let [r, c] of lamps) {
if (lampCoord.has(`${r}-${c}`)) continue;
lampCoord.set(`${r}-${c}`);
rowHash[r] = rowHash[r] + 1 || 1;
colHash[c] = colHash[c] + 1 || 1;
leftDiag[r + c] = leftDiag[r + c] + 1 || 1;
rightDiag[c - r] = rightDiag[c - r] + 1 || 1;
}
// Second, query the lamps
let output = [];
for (let [row, col] of queries) query(row, col);
return output;
function query(row, col) {
if (rowHash[row] || colHash[col] || leftDiag[row + col] || rightDiag[col - row]) {
output.push(1);
// Check 8 adjacent cells
for (let [r, c] of directions) {
let newR = row + r, newC = col + c;
if (newR < 0 || newC < 0 || newR >= n || newC >= n) continue;
// If the coordinate is a lamp, un-illuminate the lamp
if (lampCoord.has(`${newR}-${newC}`)) {
rowHash[newR]--, colHash[newC]--, leftDiag[newR + newC]--, rightDiag[newC - newR]--;
lampCoord.delete(`${newR}-${newC}`);
}
}
} else output.push(0);
}
}; | Grid Illumination |
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
| class Solution:
def maximumGap(self, nums: List[int]) -> int:
if len(nums)<2: return 0
#radix sort
#N = length of nums
#find number of digits in largest number - O(K) where K = length of largest number
longest = 0
for i in nums:
longest = max(longest,len(str(i)))
#normalize so that all numbers have same number of digits by adding 0s at the start of shorter numbers - O(N*K)
for i in range(len(nums)):
if len(str(nums[i]))!=longest:
nums[i] = '0'*(longest-len(str(nums[i]))) + str(nums[i])
else:
nums[i] = str(nums[i])
#apply counting sort starting with each digit from the end of the last digits - O(K*N)
for digit in range(longest-1,-1,-1):
vals = [[] for k in range(10)]
for num in nums:
vals[int(num[digit])] += [num]
#join list sorted by that digit position together:
new = []
for i in vals:
new += i
nums = new.copy()
#find the largest difference in the now sorted nums - O(N)
best_diff = 0
for i in range(1,len(nums)):
best_diff = max(best_diff,int(nums[i])-int(nums[i-1]))
return best_diff
#Overall complexity is O(N*K) but K is at most 10 so O(10*N) = O(N) so linear
#Please correct me if I am wrong! | class Solution {
public int maximumGap(int[] nums) {
Arrays.sort(nums);
int res=0;
if(nums.length==0){
return 0;
}
for (int i =0;i<nums.length-1;i++){
res=Math.max(Math.abs(nums[i]-nums[i+1]),res);
}
return res;
}
} | class Solution {
public:
int maximumGap(vector<int>& nums) {
sort(nums.begin(),nums.end());
int res;
int maxx=INT_MIN;
map<int,int> m;
if(nums.size()==1)
return 0;
for(int i =0;i<nums.size()-1;i++)
{
m[i]=nums[i+1]-nums[i];
}
for(auto it: m)
{
if(it.second>maxx)
{
maxx=it.second;
}
}
return maxx;
}
}; | /**
* The buckets solution.
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @param {number[]} nums
* @return {number}
*/
var maximumGap = function(nums) {
const n = nums.length
if (n < 2) {
return 0
}
if (n < 3) {
return Math.abs(nums[0] - nums[1])
}
let maxNum = -Infinity
let minNum = +Infinity
for (let i = 0; i < n; i++) {
maxNum = Math.max(maxNum, nums[i])
minNum = Math.min(minNum, nums[i])
}
if (maxNum === minNum) {
return 0
}
const k = n - 1
const averageGap = (maxNum - minNum) / k
const minBuckets = new Array(k)
const maxBuckets = new Array(k)
minBuckets[0] = minNum
maxBuckets[0] = minNum
minBuckets[k - 1] = maxNum
maxBuckets[k - 1] = maxNum
for (let i = 0; i < n; i++) {
if (minNum === nums[i] || nums[i] === maxNum) {
continue
}
const j = Math.floor((nums[i] - minNum) / averageGap)
minBuckets[j] = minBuckets[j] ? Math.min(minBuckets[j], nums[i]) : nums[i]
maxBuckets[j] = maxBuckets[j] ? Math.max(maxBuckets[j], nums[i]) : nums[i]
}
let largestGap = 0
let prevMaxIndex = 0
for (let i = 1; i < n - 1; i++) {
if (minBuckets[i]) {
largestGap = Math.max(largestGap, minBuckets[i] - maxBuckets[prevMaxIndex])
}
if (maxBuckets[i]) {
prevMaxIndex = i
}
}
return largestGap
} | Maximum Gap |
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:
Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
Constraints:
1 <= tasks.length <= 105
1 <= tasks[i] <= 109
| class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
dic={}
c=0
for i in tasks:
if i in dic.keys():
dic[i]+=1
else:
dic[i]=1
for i in dic.keys():
if dic[i]==1:
return -1
while dic[i]>=2:
if dic[i]-3>1:
dic[i]-=3
c+=1
else:
dic[i]-=2
c+=1
return c | /**
Each round, we can complete either 2 or 3 tasks of the same difficulty level
Time: O(n)
Space: O(n)
*/
class Solution {
public int minimumRounds(int[] tasks) {
int round = 0;
Map<Integer, Integer> taskMap = new HashMap<>(); // map of <task, number of each task>
for (int i = 0; i < tasks.length; i++) {
taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : taskMap.entrySet()) {
if (entry.getValue() == 1) {
return -1; // we cannot complete if there is only 1 task
}
// try to take as many 3's as possible
round += entry.getValue() / 3;
/*
We can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous
ex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]
In this example, treat the last [5,5,5], [5] as [5,5], [5,5]
*/
if (entry.getValue() % 3 != 0) {
round++;
}
}
return round;
}
} | class Solution {
public:
int minimumRounds(vector<int>& tasks) {
map<int,int> hm;
for(int i=0;i<tasks.size();i++){
hm[tasks[i]]++;
}
int num,freq,ans=0;
for (auto i : hm){
freq = i.second;
if(freq==1)
return -1;
if(freq%3==0){
ans += freq/3;
}
else{
ans += freq/3 + 1;
}
}
return ans;
}
}; | var minimumRounds = function(tasks) {
const hash = {};
let minRounds = 0;
for (const task of tasks) {
hash[task] = hash[task] + 1 || 1;
}
for (const count of Object.values(hash)) {
if (count < 2) return -1;
minRounds += Math.ceil(count / 3);
}
return minRounds;
}; | Minimum Rounds to Complete All Tasks |
A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].
Example 1:
Input: arr = [1,2,3,4,5,6,7,8]
Output: 5
Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: arr = [1,3,7,11,12,14,18]
Output: 3
Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
Constraints:
3 <= arr.length <= 1000
1 <= arr[i] < arr[i + 1] <= 109
| class Solution(object): #DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A)
def lenLongestFibSubseq(self, A):
index = {Ai: i for i, Ai in enumerate(A)}
dp = collections.defaultdict(lambda: 2)
ans = 0
for k, Ak in enumerate(A): #Following IJK idiom here
for j in range(k-1,0,-1):
i = index.get(Ak - A[j], None)
if Ak - A[j] >= A[j]: break #Pruning for illegal Ai
if i is not None and i < j:
cur_len = dp[j, k] = dp[i, j] + 1
ans = max(ans, cur_len)
return ans # ans is either 0 or >=3 for SURE | class Solution {
/*
* dp[i][j] is the max length of fibbonacci series whose last two elements
* are A[i] & A[j]
* for any integer A[k] we need to find two number A[i] & A[j] such that
* i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time
* complexity.
* if there exist i,j,k such that i < j < k and A[i] + A[j] == A[k] then
* dp[k][j] = dp[i][j] + 1 (A[k], A[j] are last two elements of fibbonacc series)
*/
public int lenLongestFibSubseq(int[] A) {
int n = A.length;
int[][] dp = new int[n][n];
int result = 0;
for (int k = 2; k < n; k++) {
int i = 0, j = k-1;
while(i < j) {
int sum = A[i] + A[j] - A[k];
if (sum < 0) {
i++;
} else if (sum > 0) {
j--;
} else {
// ith, jth kth element are fibbonaci sequence
dp[j][k] = dp[i][j] + 1; // since numbers are unique
result = Math.max(result, dp[j][k]);
i++;
j--;
}
}
}
return result + 2 >= 3? result + 2: 0;
}
} | class Solution {
public:
int help(int i,int j, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp){
if(dp[i][j]!=-1)
return dp[i][j];
int x=nums[i]+nums[j];
if(mp.find(x)!=mp.end())
{
dp[i][j]=help(j,mp[x],mp,nums,dp);
return 1+dp[i][j];
}
return 1;
}
int solve(int idx ,int n, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp)
{
int maxi=INT_MIN;
for(int i=idx;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int x=nums[i]+nums[j];
if(mp.find(x)!=mp.end())
{
maxi=max(maxi,2+help(j,mp[x],mp,nums,dp));
}
}
}
return (maxi==INT_MIN?0:maxi);
}
int lenLongestFibSubseq(vector<int>& arr) {
unordered_map<int,int> mp;
int n=arr.size();
vector<vector<int>> dp(n,vector<int> (n,-1));
for(int i=0;i<arr.size();i++)
mp[arr[i]]=i;
return solve(0,n,mp,arr,dp);
}
}; | var lenLongestFibSubseq = function(arr) {
let ans = 2;
const set = new Set(arr);
const len = arr.length
for(let i = 0; i < len; i++) {
for(let j = i + 1; j < len; j++) {
let a = arr[i], b = arr[j], len = 2;
while(set.has(a + b)) {
len++;
let temp = a + b;
a = b;
b = temp;
}
ans = Math.max(len, ans);
}
}
return ans == 2 ? 0 : ans;
}; | Length of Longest Fibonacci Subsequence |
A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s to make it fancy.
Return the final string after the deletion. It can be shown that the answer will always be unique.
Example 1:
Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".
Example 2:
Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".
Example 3:
Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".
Constraints:
1 <= s.length <= 105
s consists only of lowercase English letters.
| class Solution:
def makeFancyString(self, s: str) -> str:
if len(s) < 3:
return s
ans = ''
ans += s[0]
ans += s[1]
for i in range(2,len(s)):
if s[i] != ans[-1] or s[i] != ans[-2]:
ans += s[i]
return ans | class Solution {
public String makeFancyString(String s) {
char prev = s.charAt (0);
int freq = 1;
StringBuilder res = new StringBuilder ();
res.append (s.charAt (0));
for (int i = 1; i < s.length (); i++) {
if (s.charAt (i) == prev)
freq++;
else {
prev = s.charAt (i);
freq = 1;
}
if (freq < 3)
res.append (s.charAt (i));
}
return res.toString ();
}
} | class Solution {
public:
string makeFancyString(string s) {
int cnt=1;
string ans=""; ans.push_back(s[0]);
for(int i=1;i<s.length();++i) {
cnt=s[i]==s[i-1]? cnt+1:1;
if(cnt<3) {
ans.push_back(s[i]);
}
}
return ans;
}
};
}; | var makeFancyString = function(s) {
let res = '';
let currCount = 0;
for (let i = 0; i < s.length; i++) {
if (currCount === 2 && s[i] === s[i - 1]) continue;
else if (s[i] === s[i - 1]) {
currCount++;
res += s[i];
}
else {
currCount = 1;
res += s[i]
}
}
return res;
}; | Delete Characters to Make Fancy String |
A square matrix is said to be an X-Matrix if both of the following conditions hold:
All the elements in the diagonals of the matrix are non-zero.
All other elements are 0.
Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.
Example 1:
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is an X-Matrix.
Example 2:
Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
Output: false
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is not an X-Matrix.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105
| class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for i in range(n):
for j in range(n):
if i==j or (i+j) ==n-1:
if grid[i][j] == 0:
return False
elif grid[i][j] != 0:
return False
return True; | class Solution {
public boolean checkXMatrix(int[][] grid) {
int n = grid.length;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++ ){
if ( i == j || i + j == n - 1 ) {
if ( grid[i][j] == 0 ) return false;
}
else if ( grid[i][j] != 0 ) return false;
}
}
return true;
}
} | class Solution {
public:
bool checkXMatrix(vector<vector<int>>& grid) {
int n = grid.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(i == j or i == n - j - 1){
if(!grid[i][j])
return false;
}else if(grid[i][j])
return false;
}
}
return true;
}
}; | var checkXMatrix = function(grid) {
for (let i=0; i<grid.length; i++) {
for (let j=0; j<grid[i].length; j++) {
let leftDiagonal = grid[i].length - 1;
if (i === j && grid[i][j] !== 0 || j === leftDiagonal - i && grid[i][j] !== 0) {
continue;
}
if (i === j && grid[i][j] === 0 || j === leftDiagonal - i && grid[i][j] === 0) {
return false;
}
if (grid[i][j] !== 0) {
return false;
}
}
}
return true;
}; | Check if Matrix Is X-Matrix |
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 105].
-109 <= Node.val <= 109
All Node.val are unique.
p != q
p and q will exist in the tree.
| class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
# escape condition
if (not root) or (root == p) or (root == q):
return root
# search left and right subtree
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
# both found, root is the LCA
return root
return left or right | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> path_to_p= new ArrayList<>();
List<TreeNode> path_to_q= new ArrayList<>();
getPath(root,p,path_to_p);
getPath(root,q,path_to_q);
int n=path_to_q.size()>path_to_p.size()?path_to_p.size():path_to_q.size();
TreeNode anscesstor=root;
for(int i=0;i<n;i++){
if(path_to_q.get(i)==path_to_p.get(i)) anscesstor=path_to_p.get(i);
}
return anscesstor;
}
boolean getPath(TreeNode root, TreeNode target,List<TreeNode> list){
if(root==null) return false;
list.add(root);
if(root==target) return true;
if(getPath(root.left,target,list) || getPath(root.right,target,list)){
return true;
}
list.remove(list.size()-1);
return false;
}
} | class Solution
{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(!root)
{
return NULL;
}
if(root==p or root == q)
{
return root;
}
TreeNode *left=lowestCommonAncestor(root->left,p,q);
TreeNode *right=lowestCommonAncestor(root->right,p,q);
if(left and right) return root;
if(left) return left;
else return right;
}
}; | var lowestCommonAncestor = function(root, p, q) {
if(!root || root.val == p.val || root.val == q.val) return root;
let left = lowestCommonAncestor(root.left, p, q);
let right = lowestCommonAncestor(root.right, p, q);
return (left && right) ? root : left || right;
}; | Lowest Common Ancestor of a Binary Tree |
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.
You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:
The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').
The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').
For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.
Return the number of rods that have all three colors of rings on them.
Example 1:
Input: rings = "B0B6G0R6R0R6G9"
Output: 1
Explanation:
- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.
- The rod labeled 6 holds 3 rings, but it only has red and blue.
- The rod labeled 9 holds only a green ring.
Thus, the number of rods with all three colors is 1.
Example 2:
Input: rings = "B0R0G0R9R0B0G0"
Output: 1
Explanation:
- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.
- The rod labeled 9 holds only a red ring.
Thus, the number of rods with all three colors is 1.
Example 3:
Input: rings = "G4"
Output: 0
Explanation:
Only one ring is given. Thus, no rods have all three colors.
Constraints:
rings.length == 2 * n
1 <= n <= 100
rings[i] where i is even is either 'R', 'G', or 'B' (0-indexed).
rings[i] where i is odd is a digit from '0' to '9' (0-indexed).
| class Solution:
def countPoints(self, r: str) -> int:
ans = 0
for i in range(10):
i = str(i)
if 'R'+i in r and 'G'+i in r and 'B'+i in r:
ans += 1
return ans | class Solution {
public int countPoints(String rings) {
Map<Integer,Set<Character>> m=new HashMap<>();
for(int i=0;i<rings.length();i=i+2){
char c=rings.charAt(i);
int index=(int)rings.charAt(i+1);
if(m.containsKey(index)){
Set<Character> x=m.get(index);
x.add(c);
m.put(index,x);
}else{
Set<Character> x=new HashSet<>();
x.add(c);
m.put(index,x);
}
}
int count=0;
for(Set<Character> k : m.values()){
if(k.size()==3) count++;
}
return count;
}
} | class Solution {
public:
int countPoints(string rings) {
int n=rings.length();
//It is given that number of rod is 10 0 to 9 so we have to place ring any of these
vector<int>vp(10,0);//store the no of rings
for(int i=0;i<n;i+=2)
{
char col=rings[i];
vp[rings[i+1]-'0']|=(col=='R'? 1: col =='G' ? 2 : 4);//checking for rings
}
int count=0;
for(int i=0;i<10;i++)
{
if(vp[i]==7)
{
count++;
}
}
return count;
}
}; | /**
* @param {string} rings
* @return {number}
*/
var countPoints = function(rings) {
let rods = Array(10).fill("");
for(let i = 0; i < rings.length; i += 2){
if(!(rods[rings[i+1]].includes(rings[i]))) rods[rings[i+1]] += rings[i]
}
return rods.filter(rod => rod.length > 2).length
}; | Rings and Rods |
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
You must find a solution with a memory complexity better than O(n2).
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Example 2:
Input: matrix = [[-5]], k = 1
Output: -5
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= 109
All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
1 <= k <= n2
Follow up:
Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
| class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
return sorted(list(sum(matrix, [])))[k-1] | /**
* Using PriorityQueue
*
* Time Complexity:
* O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.
* If we were adding all elements in one go, then the complexity would be O(min(N,K))
* Refer: https://stackoverflow.com/a/34697891
* O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.
* Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))
*
* Space Complexity: O(min(N, K))
*
* N = Length of one side of the matrix. K = input value k.
*/
class Solution {
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || k <= 0) {
throw new IllegalArgumentException("Input is invalid");
}
int n = matrix.length;
if (k > n * n) {
throw new NoSuchElementException("k is greater than number of elements in matrix");
}
if (k == 1) {
return matrix[0][0];
}
if (k == n * n) {
return matrix[n - 1][n - 1];
}
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));
for (int i = 0; i < Math.min(n, k); i++) {
queue.offer(new int[] { i, 0 });
}
while (k > 1) {
int[] cur = queue.poll();
if (cur[1] < n - 1) {
cur[1]++;
queue.offer(cur);
}
k--;
}
return matrix[queue.peek()[0]][queue.peek()[1]];
}
} | class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size(), start = matrix[0][0], end = matrix[n-1][n-1];
unordered_map<int, int>mp;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
mp[matrix[i][j]]++;
for(int i = start; i <= end; i++)
if(mp.find(i) != mp.end()){
for(int j = 0; j < mp[i]; j++){
k--;
if(k == 0) return i;
}
}
return -1;
}
}; | var kthSmallest = function(matrix, k) {
let arr = matrix.flat()
arr.sort((a,b)=>a-b)
return arr[k-1]
}; | Kth Smallest Element in a Sorted Matrix |
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1,1,0] horizontally results in [0,1,1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
For example, inverting [0,1,1] results in [1,0,0].
Example 1:
Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Constraints:
n == image.length
n == image[i].length
1 <= n <= 20
images[i][j] is either 0 or 1.
| class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[(1 - i) for i in row[::-1]] for row in image] | class Solution {
public int[][] flipAndInvertImage(int[][] image) {
for (int i = 0; i < image.length; ++i) {
flip(image[i]);
}
for (int i = 0; i < image.length; ++i) {
for (int j = 0; j < image[i].length; ++j) {
image[i][j] = image[i][j] == 1 ? 0:1;
}
}
return image;
}
public static void flip(int[] row) {
int i = 0;
int j = row.length - 1;
while (i < j) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
++i;
--j;
}
}
} | class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
int n = image.size();
vector<int >ans;
for(int i=0;i<image.size();i++){
ans=image[i];
reverse(ans.begin(),ans.end());
image[i]=ans;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(image[i][j] == 0){
image[i][j] = 1;
}
else{
image[i][j] = 0;
}
}
}
return image;
}
}; | var flipAndInvertImage = function(image) {
const resversedArr = []
for(let i=0; i<image.length; i++){
resversedArr.push(resverseArr(image[i]));
}
return resversedArr;
};
function resverseArr(arr){
const lastIndex = arr.length -1, reversedArr = [];
for(i=0; i<=lastIndex; i++){
if(arr[i] !== arr[lastIndex-i]){
reversedArr[i] = arr[lastIndex-i] === 0 ? 1 : 0;
reversedArr[lastIndex-i] = arr[i] === 0 ? 1 : 0;
}else{
reversedArr[i] = arr[i] === 0 ? 1 : 0;
}
}
return reversedArr;
}```
/*
*/ | Flipping an Image |
Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return the shortest such subarray and output its length.
Example 1:
Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Example 2:
Input: nums = [1,2,3,4]
Output: 0
Example 3:
Input: nums = [1]
Output: 0
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
Follow up: Can you solve it in O(n) time complexity? | #lets start adding elements to stack. We have to fin the min length [a, b] interval (corresponding to the problem description).
# a has to be the first element's index we pop from the array. lets say y is the last element's index we pop.
# and max_pop is the maximum element(not index) we pop during stacking.After stacking process is done we are going to have
#last elements in the stack E(E is the stack after stacking is done).We have to find M = maximum_element(max_pop, all elements of E)
#Index of M is going to be right edge of the [a, b] interval
class Solution:
def findUnsortedSubarray(self, nums) -> int:
stack = []
min_index = len(nums)
max_index = 0
max_pop = float('-inf')
for i in range(len(nums)):
while stack and nums[i] < stack[-1][0]:
p = stack.pop()
if p[0] > max_pop:
max_pop = p[0]
if p[1] < min_index:
min_index = p[1]
if p[1] > max_index:
max_index = p[1]
stack.append([nums[i], i])
max_r = max_index
for st in stack:
if st[0] < max_pop:
max_r = st[1]
if min_index == len(nums):
return 0
return max_r - min_index +1 | class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] numsClone = nums.clone();
Arrays.sort(nums);
int s = Integer.MAX_VALUE;
int e = Integer.MIN_VALUE;
for(int i = 0; i<nums.length; i++) {
if(numsClone[i] != nums[i]) {
s = Math.min(s, i);
e = Math.max(e, i);
}
}
if(s == Integer.MAX_VALUE || e == Integer.MIN_VALUE) {
return 0;
}
return e-s+1;
}
} | class Solution {
public:
int max_value = 1000000;
int min_value = -1000000;
int findUnsortedSubarray(vector<int>& nums) {
// max_list refers to: the max value on the left side of the current element
// min_list refers to: the min value on the right side of the current element
vector<int> max_list(nums.size(), 0);
vector<int> min_list(nums.size(), 0);
min_list[nums.size()-1] = max_value;
max_list[0] = min_value;
// init two lists
for(int i=nums.size()-2; i>=0; i--)
min_list[i] = min(min_list[i+1], nums[i+1]);
for(int i=1; i<nums.size(); i++)
max_list[i] = max(max_list[i-1], nums[i-1]);
// get left bound
int left = 0;
while(left < nums.size() && min_list[left] >= nums[left])
left++;
// get right bound
int right = nums.size() - 1;
while(right >= 0 && max_list[right] <= nums[right])
right--;
if (left == nums.size()) // monotonic ascending array
return 0;
else
return (right-left+1);
}
}; | var findUnsortedSubarray = function(nums) {
let left = 0;
let right = nums.length - 1;
const target = [...nums].sort((a, b) => a - b);
while (left < right && nums[left] === target[left]) left += 1;
while (right > left && nums[right] === target[right]) right -= 1;
const result = right - left;
return result === 0 ? 0 : result + 1;
}; | Shortest Unsorted Continuous Subarray |
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles.
Example 1:
Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]
Output: 6
Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.
Example 2:
Input: rectangles = [[4,5],[7,8]]
Output: 0
Explanation: There are no interchangeable pairs of rectangles.
Constraints:
n == rectangles.length
1 <= n <= 105
rectangles[i].length == 2
1 <= widthi, heighti <= 105
| class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
ratios = defaultdict(int)
for x, y in rectangles:
ratios[x/y] += 1
res = 0
for val in ratios.values():
res += (val*(val-1)//2)
return res | class Solution {
public long interchangeableRectangles(int[][] rectangles) {
Map <Double, Long> hash = new HashMap<>();
for (int i = 0; i < rectangles.length; i++) {
Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]);
hash.put(tmp, hash.getOrDefault(tmp, 0L) + 1);
}
long ans = 0;
for (Map.Entry<Double,Long> entry : hash.entrySet()) {
if (entry.getValue() > 1) {
Long n = entry.getValue();
ans += (n * (n - 1)) / 2;
}
}
return ans;
}
} | class Solution {
public:
long long interchangeableRectangles(vector<vector<int>>& rectangles) {
int n = rectangles.size();
unordered_map<double,int> mp;
for(int i = 0;i<n;i++){
double ratio = rectangles[i][0]/(double)rectangles[i][1];
mp[ratio]++;
}
long long count = 0;
for(auto i: mp){
long long x = i.second;
x = (x * (x-1))/2.0;
count += x;
}
return count;
}
}; | /**
* @param {number[][]} rectangles
* @return {number}
*/
var interchangeableRectangles = function(rectangles) {
let map = new Map();
for (let i = 0; i < rectangles.length; i++) {
let [a, b] = rectangles[i];
let val = a / b;
if (!map.get(val)) map.set(val, [0, 0]);
else {
const [count, total] = map.get(val);
map.set(val, [count + 1, total + count + 1]);
}
}
return [...map.entries()].reduce((prev, [key, [count, total]]) => {
if (count < 1) return prev;
return prev + total;
}, 0);
}; | Number of Pairs of Interchangeable Rectangles |
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Example 2:
Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
Output: [22,28,8,6,17,44]
Constraints:
1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
All the elements of arr2 are distinct.
Each arr2[i] is in arr1.
| class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
arr = []
hashmap = {char: arr1.count(char) for char in arr1}
[arr.extend([char] * hashmap.pop(char)) for char in arr2]
return arr + sorted([int(key) * hashmap[key] for key in hashmap] | class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map <Integer, Integer> map = new TreeMap();
for(int i = 0; i<arr1.length; i++){
if(map.containsKey(arr1[i])){
map.replace(arr1[i], map.get(arr1[i]),map.get(arr1[i])+1);
}
else{
map.put(arr1[i], 1);
}
}
int[] arr = new int [arr1.length];
int ind = 0;
for(int i = 0; i<arr2.length; i++){
for(int j = 0; j<map.get(arr2[i]);j++){
arr[ind] = arr2[i];
ind++;
}
map.remove(arr2[i]);
}
for(int i: map.keySet()){
for(int j = 0; j<map.get(i);j++){
arr[ind] = i;
ind++;
}
}
return arr;
}
} | class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
map<int,int>sk;
vector<int>res;
for(auto i:arr1){
sk[i]++;
}
for(auto j:arr2){
for(auto z:sk){
if(z.first==j){
int x=z.second;
for(int l=0;l<x;l++){
res.push_back(z.first);
}
}
}
}
for(auto z:sk){
if(z.second==4 && find(res.begin(), res.end(),z.first)==res.end()){
int p=z.second;
for(int aqq=0;aqq<p;aqq++){
res.push_back(z.first);
}
}
if(z.second==3 && find(res.begin(), res.end(),z.first)==res.end()){
int p=z.second;
for(int aq=0;aq<p;aq++){
res.push_back(z.first);
}
}
if(z.second==2 && find(res.begin(), res.end(),z.first)==res.end()){
int p=z.second;
for(int a=0;a<p;a++){
res.push_back(z.first);
}
}
if(z.second==1 && find(res.begin(), res.end(),z.first)==res.end()){
res.push_back(z.first);
}
}
return res;
}
}; | /**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number[]}
*/
var relativeSortArray = function(arr1, arr2) {
const indices = new Map();
arr2.forEach(indices.set, indices);
return arr1.sort((a, b) => {
if (indices.has(a)) {
return indices.has(b) ? indices.get(a) - indices.get(b) : -1;
}
if (indices.has(b)) {
return 1;
}
return a - b;
});
}; | Relative Sort Array |
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
Example 2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
Example 3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
Constraints:
2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3
| class Solution(object):
def checkIfExist(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
'''
执行用时:24 ms, 在所有 Python 提交中击败了59.63%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了58.72%的用户
'''
arr = sorted(arr) # 排序
for i in range(len(arr) - 1): # 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现
l = 0
r = len(arr) - 1
while (l <= r):
mid = int((l + r) / 2) # 目前位置
val1 = arr[mid] # 目前位置的数值
val2 = arr[i] * 2 # 要寻找的目标
if(val1 == val2 and mid != i): # arr[mid] 必須和 arr[i] * 2 且不同位置
return True
elif(val2 < val1): # 目标在目前位置的左边,所以要往左边找
r = mid - 1
else: # 目标在目前位置的右边,所以要往右边找
l = mid + 1
return False | class Solution {
public boolean checkIfExist(int[] arr) {
/*
执行用时:3 ms, 在所有 Java 提交中击败了29.57%的用户
内存消耗:41 MB, 在所有 Java 提交中击败了42.27%的用户
2022年8月3日 14:36
*/
int l, mid = 0, r;
int val1, val2;
Arrays.sort(arr); // 排序
for(int i=0; i < arr.length - 1; i++){ // 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现
l = 0;
r = arr.length - 1;
while(l <= r){
mid = (l + r) / 2; // 目前位置
val1 = arr[mid]; // 目前位置的数值
val2 = arr[i] * 2; // 要寻找的目标
if(val1 == val2 && mid != i) // arr[mid] 必須和 arr[i] * 2 且不同位置
return true;
else if(val2 < val1) // 目标在目前位置的左边,所以要往左边找
r = mid - 1;
else // 目标在目前位置的右边,所以要往右边找
l = mid + 1;
}
}
return false;
}
} | class Solution {
public:
bool checkIfExist(vector<int>& arr) {
sort(arr.begin(), arr.end());
int i =0;
int j = 1;
int n = arr.size();
while(i<n && j<n)
{
if( arr[i]<0 && arr[j]<0 && arr[i]==2*arr[j])return true;
else if(2*arr[i]<arr[j])
{
i++;
}
else if(2*arr[i]>arr[j])j++;
else if(i==j && arr[i]==0){
i++;
j++;
}
else return true;
}
return false;
}
}; | /**
* @param {number[]} arr
* @return {boolean}
*/
var checkIfExist = function(arr) {
for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if ( i!==j && arr[i]==2*arr[j]){
return true;
}
}
}
return false;
}; | Check If N and Its Double Exist |
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
| class Solution(object):
def groupThePeople(self, groupSizes):
"""
:type groupSizes: List[int]
:rtype: List[List[int]]
"""
dict_group={}
for i in range(len(groupSizes)):
if groupSizes[i] not in dict_group:
dict_group[groupSizes[i]]=[i]
else:
dict_group[groupSizes[i]].append(i)
return_list=[]
for i in dict_group:
num_list=dict_group[i]
for j in range(0,len(num_list),i):
return_list.append(num_list[j:j+i])
return return_list | class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
List<List<Integer>> temp = new ArrayList<List<Integer>>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0; i<groupSizes.length; i++){
int k = groupSizes[i];
boolean flag = true;
for(int j = 0; j<temp.size(); j++){
// If there is a list of reqired group size and it is filled lesser than we can put element in that one
if(k == temp.get(j).get(0) && k >temp.get(j).get(1)){
result.get(j).add(i);
temp.get(j).set(1,temp.get(j).get(1)+1);
flag=false;
break;
}
}
if(flag){
// comment 1
// We create a list with index and put it to result
List<Integer> res = new ArrayList();
res.add(i);
result.add(res);
// comment 2
// we create a new list recording max value can stored and currently filled
List<Integer> tempRes = new ArrayList();
tempRes.add(k);
tempRes.add(1);
temp.add(tempRes);
}
}
return result;
}
} | class Solution {
public:
vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
vector<vector<int>>ans;
unordered_map<int,vector<int>> store;
for(int i=0;i<groupSizes.size();i++){
if(store[groupSizes[i]].size()==groupSizes[i]){
ans.push_back(store[groupSizes[i]]) ;
store[groupSizes[i]].clear();
}
store[groupSizes[i]].push_back(i);}
for(auto &x:store){
ans.push_back(x.second);}
return ans;
}
}; | /**
* @param {number[]} groupSizes
* @return {number[][]}
*/
var groupThePeople = function(groupSizes) {
let indices = [], result = [];
groupSizes.forEach((x, idx) => {
if (indices[x]) indices[x].push(idx);
else indices[x] = [idx];
if (indices[x].length === x) {
result.push(indices[x]);
indices[x] = undefined;
}
});
return result;
}; | Group the People Given the Group Size They Belong To |
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.
Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the k digits representing the answer.
Example 1:
Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
Output: [9,8,6,5,3]
Example 2:
Input: nums1 = [6,7], nums2 = [6,0,4], k = 5
Output: [6,7,6,0,4]
Example 3:
Input: nums1 = [3,9], nums2 = [8,9], k = 3
Output: [9,8,9]
Constraints:
m == nums1.length
n == nums2.length
1 <= m, n <= 500
0 <= nums1[i], nums2[i] <= 9
1 <= k <= m + n
| class Solution:
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
m = len(nums1)
n = len(nums2)
dp = {}
# get the max number string with "length" from index "i" in nums1 and index "j" in nums2
# using number string to easy to compare
def getMaxNumberString(i, j, length):
if length == 0:
return ""
# using memoization to optimize for the overlapping subproblems
key = (i, j, length)
if key in dp:
return dp[key]
# greedy to find the possible max digit from nums1 and nums2
# 1) bigger digit in the higher position of the number will get bigger number
# 2) at the same time, we need to ensure that we still have enough digits to form a number with "length" digits
# try to find the possible max digit from index i in nums1
index1 = None
for ii in range(i, m):
if (m - ii + n - j) < length:
break
if index1 is None or nums1[index1] < nums1[ii]:
index1 = ii
# try to find the possible max digit from index j in nums2
index2 = None
for jj in range(j, n):
if (m - i + n - jj) < length:
break
if index2 is None or nums2[index2] < nums2[jj]:
index2 = jj
maxNumberStr = None
if index1 is not None and index2 is not None:
if nums1[index1] > nums2[index2]:
maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)
elif nums1[index1] < nums2[index2]:
maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)
else:
# get the same digit from nums1 and nums2, so need to try two cases and get the max one
maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1))
elif index1 is not None:
maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)
elif index2 is not None:
maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)
dp[key] = maxNumberStr
return maxNumberStr
result_str = getMaxNumberString(0, 0, k)
# number string to digit array
result = []
for c in result_str:
result.append(int(c))
return result | class Solution {
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
String ans="";
for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq
String one = solve(nums1, i); // find the best seq matching len of i
String two = solve(nums2, k-i); // len of k-i
StringBuilder sb = new StringBuilder();
int a = 0, b = 0;
while(a < i || b < k-i){ // merge it to the max
sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));
}
if (sb.toString().compareTo(ans)>0){ // if better, we replace.
ans=sb.toString();
}
}
int[] res = new int[k];
for (int i = 0; i < k;++i){
res[i]=ans.charAt(i)-'0';
}
return res;
}
private String solve(int[] arr, int k){
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0;i<arr.length;++i){
while(!stack.isEmpty()&&arr.length-i+stack.size()>k&&stack.peek()<arr[i]){
stack.pop();
}
stack.push(arr[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k;i++){
sb.append(stack.pollLast());
}
return sb.toString();
}
} | class Solution {
public:
vector<int> maxArray(vector<int>&nums,int k){
int n=nums.size();
stack<int>seen;
for(int i=0;i<n;i++){
int right=n-i-1;
while(not seen.empty() and seen.top()<nums[i] and right+seen.size()>=k)seen.pop();
if(seen.size()<k)seen.push(nums[i]);
}
vector<int>res(k,0);
for(int i=res.size()-1;i>=0;i--){
res[i]=seen.top();
seen.pop();
}
return res;
}
bool greater(vector<int>&arr1,int i,vector<int>&arr2,int j){
for(;i<arr1.size() and j<arr2.size();i++,j++){
if(arr1[i]==arr2[j])continue;
return arr1[i]>arr2[j];
}
return i!=arr1.size();
}
vector<int> merge(vector<int>&arr1,vector<int>&arr2){
vector<int>res(arr1.size()+arr2.size());
for(int ind=0,i=0,j=0;ind<res.size();ind++){
if(greater(arr1,i,arr2,j)){
res[ind]=arr1[i];
i++;
}else{
res[ind]=arr2[j];
j++;
}
}
return res;
}
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
int m=nums1.size(),n=nums2.size();
vector<int>ans;
for(int len1=max(0,k-n);len1<=min(m,k);len1++){
int len2 = k-len1;
vector<int> arr1 = maxArray(nums1,len1);
vector<int> arr2 = maxArray(nums2,len2);
vector<int> temp_res = merge(arr1,arr2);
if(greater(temp_res,0,ans,0)){
ans.resize(temp_res.size());
for(int i=0;i<temp_res.size();i++){
ans[i]=temp_res[i];
}
}
}
return ans;
}
}; | const maxNumber = (a, b, k) => {
let m = a.length, n = b.length;
let res = [];
for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) {
let maxA = maxArray(a, i), maxB = maxArray(b, k - i);
let merge = mergeArray(maxA, maxB);
if (merge > res) res = merge;
}
return res;
};
const maxArray = (a, k) => {
let drop = a.length - k, res = [];
for (const x of a) {
while (drop > 0 && res.length && res[res.length - 1] < x) {
res.pop();
drop--;
}
res.push(x);
}
if (res.length >= k) {
res = res.slice(0, k);
} else {
res = res.concat(Array(k - res.length).fill(0));
}
return res;
};
const mergeArray = (a, b) => {
let res = [];
while (a.length + b.length) res.push(a > b ? a.shift() : b.shift())
return res;
}; | Create Maximum Number |
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t) | class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] haha1 = new int[26];//26 because input contains of only lower english letters
int[] haha2 = new int[26];
for (int i = 0; i < s.length(); ++i) {
haha1[(int)s.charAt(i)-97] += 1;//omitting 97 because 'a' is 97, it will be 0 now
haha2[(int)t.charAt(i)-97] += 1;
}
for (int i = 0; i < haha1.length; ++i) {
if (haha1[i] != haha2[i]) return false;
}
return true;
}
} | class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
if(s != t)
return false;
return true;
}
}; | var isAnagram = function(s, t) {
if(s.length !== t.length) return false
let charFreq = {}
for(let char of s){
charFreq[char] ? charFreq[char] +=1 : charFreq[char] = 1
}
for(let char of t){
if(!(charFreq[char])) return false
charFreq[char] -= 1
}
return true
}; | Valid Anagram |
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.
Return the maximum product you can get.
Example 1:
Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Constraints:
2 <= n <= 58
| class Solution:
def integerBreak(self, n: int) -> int:
dp = [0 for _ in range(n+1)]
dp[1] = 1
for i in range(2, n+1):
for j in range(1, i//2+1):
dp[i] = max(j * (i-j), j * dp[i-j], dp[i])
return dp[-1] | class Solution {
public int integerBreak(int n) {
//dp array: maximum product of splitling int i
int[] dp = new int[n + 1];
// traverse
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i / 2; j++) {
dp[i] = Math.max(Math.max(j * (i - j), j * dp[i - j]), dp[i]);
}
}
return dp[n];
}
} | class Solution
{
public:
int integerBreak(int n)
{
if (n == 2)
return 1;
if (n == 3)
return 2;
if (n == 4)
return 4;
int k = n / 3;
int m = n % 3;
int ans;
if (m == 0)
ans = pow(3, k);
else if (m == 1)
ans = pow(3, k - 1) * 4;
else if (m == 2)
ans = pow(3, k) * m;
return ans;
}
}; | var integerBreak = function(n) {
if(n == 2) return 1;
if(n == 3) return 2;
if(n == 4) return 4;
let c = ~~(n/3);
let d = n % 3;
if(d === 0){
return 3 ** c;
}
if(d === 1){
return 3 ** (c-1) * 4;
}
if(d === 2){
return 3 ** (c) * 2;
}
}; | Integer Break |
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points, return the minimum number of arrows that must be shot to burst all balloons.
Example 1:
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
Example 2:
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
Example 3:
Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].
Constraints:
1 <= points.length <= 105
points[i].length == 2
-231 <= xstart < xend <= 231 - 1
| class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
ans=[points[0]]
for i in points[1:]:
if(i[0]<=ans[-1][1]):
ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])]
else:
ans.append(i)
return len(ans)
| class Solution {
public int findMinArrowShots(int[][] points) {
int minNumArrows = 1;
Arrays.sort(points, new Comparator<int[]>(){
@Override
public int compare(int[] i1, int[] i2)
{
if(i1[0] < i2[0])
return -1;
else if (i1[0] > i2[0])
return 1;
return 0;
}
});
// This is where they will trip you up ( at the merge stage )
// Wait ... do we actually have to merge here? The intervals have been sorted already
// No you must merge
// See if they can be merged
// If mergeable - overwrite OR write into a new subintervals code ( new ArrayList )
// Ok ... so first we compare (a1,a2) and then next step compare (a2,a3)
// Now if (a1,a2) had an overlap -> why not make the next a2 = merged(a1,a2)?
// That would do a carry over effect then
int n = points.length;
int[] candid = new int[2]; // always first interval anyways
candid[0] = points[0][0];
candid[1] = points[0][1];
for(int i = 1; i < n; i++)
{
// System.out.printf("Current set = (%d,%d)\n", candid[0], candid[1]);
int[] next = points[i];
if(hasOverlap(candid,next))
{
int[] merged = mergeInterval(candid,next);
candid[0] = merged[0];
candid[1] = merged[1];
}
else
{
candid[0] = next[0];
candid[1] = next[1];
minNumArrows++;
}
}
return minNumArrows;
}
public boolean hasOverlap(int[] i1, int[] i2)
{
boolean hasOverlap = false;
if(i1[0] <= i2[0] && i2[0] <= i1[1])
hasOverlap = true;
if(i2[0] <= i1[0] && i1[0] <= i2[1])
hasOverlap = true;
return hasOverlap;
}
public int[] mergeInterval(int[] i1, int[] i2)
{
int[] merged = new int[2];
merged[0] = Math.max(i1[0],i2[0]);
merged[1] = Math.min(i1[1],i2[1]);
return merged;
}
} | class Solution {
public:
static bool cmp(vector<int>&a,vector<int>&b)
{
return a[1]<b[1];
}
int findMinArrowShots(vector<vector<int>>& points) {
sort(points.begin(),points.end(),cmp);
//burst the first ballon at least
int arrow=1;
int end=points[0][1];
for(int i=1;i<points.size();i++)
{
//start time of other interval is greater than current end time means we need one more arrow for bursting it
if(points[i][0]>end)
{
arrow++;
end=points[i][1];
}
}
return arrow;
}
}; | var findMinArrowShots = function(points) {
points.sort((a, b) => a[0] - b[0])
let merged = [points[0]];
let earliestEnd = points[0][1];
for (let i = 1; i < points.length; i++) {
let lastEnd = merged[merged.length - 1][1];
let currStart = points[i][0];
let currEnd = points[i][1];
if (lastEnd >= currStart && currStart <= earliestEnd) {
merged[merged.length - 1][1] = Math.max(lastEnd, currEnd)
earliestEnd = Math.min(earliestEnd, points[i][1]);
}
else {
merged.push(points[i])
earliestEnd = points[i][1]
}
}
return merged.length
}; | Minimum Number of Arrows to Burst Balloons |
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
Example 1:
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
Constraints:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
At most 104 calls will be made to add.
It is guaranteed that there will be at least k elements in the array when you search for the kth element.
| class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.hp = []
for x in nums:
self.add(x)
return None
def add(self, val: int) -> int:
heapq.heappush(self.hp, (val))
if len(self.hp) > self.k:
heapq.heappop(self.hp)
return self.get_kth_largest()
def get_kth_largest(self):
return self.hp[0] | class KthLargest {
PriorityQueue<Integer> queue=new PriorityQueue();
int k=0;
public KthLargest(int k, int[] nums) {
this.k=k;
for(int i:nums)
add(i);
}
public int add(int val) {
if(k>queue.size())
queue.add(val);
else
if(val>queue.peek())
{
queue.poll();
queue.add(val);
}
return queue.peek();
}
} | class KthLargest {
int k;
priority_queue<int, vector<int>, greater<int>> minheap;
int n;
public:
KthLargest(int k, vector<int>& nums) {
this->k=k;
this->n=nums.size();
// push the initial elements in the heap
for(auto x : nums){
minheap.push(x);
}
// if the no. of elements are greater than k then remove them
while(n>k){
minheap.pop();
n--;
}
}
int add(int val) {
// if heap is empty or no. of elements are less than k then add the input
if(minheap.empty() || n<k){
minheap.push(val);
this->n=n+1;
}
// else compare it with top
else{
int minn=minheap.top();
// if the input is greater than top
if(minn<val){
minheap.pop();
minheap.push(val);
}
}
// at any point of time top of the heap is required ans
return minheap.top();
}
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/ | var KthLargest = function(k, nums) {
// sort ascending because I am familiar with it
// when applying my binary search algorithm
this.nums = nums.sort((a,b) => a - b);
this.k = k;
};
KthLargest.prototype.add = function(val) {
// search a place to push val
// using binary search
let left = 0; right = this.nums.length - 1;
while (left < right) {
let mid = left + Math.floor((right + 1 - left)/2);
if (val < this.nums[mid]) {
right = mid - 1;
} else {
left = mid
}
}
// push val into the nums
this.nums.splice(left+(this.nums[left] < val ? 1 : 0), 0, val);
// because our nums is sorted
// so kth largest element is easy to be returned
return this.nums[this.nums.length-this.k]
}; | Kth Largest Element in a Stream |
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
| class Solution:
def findShortestSubArray(self, nums):
# Group indexes by element type
d = defaultdict(list)
for i,x in enumerate(nums):
d[x].append(i)
#
# Find highest Degree
m = max([ len(v) for v in d.values() ])
#
# Find shortest span for max. degree
best = len(nums)
for v in d.values():
if len(v)==m:
best = min(best,v[-1]-v[0]+1)
return best | class Solution {
public int findShortestSubArray(int[] nums) {
int ans = Integer.MAX_VALUE;
Map<Integer, Integer> count = new HashMap<>();
Map<Integer, Integer> startIndex = new HashMap<>();
Map<Integer, Integer> endIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
}
for (int i = 0; i < nums.length; i++) {
int no = nums[i];
if (!startIndex.containsKey(no)) {
startIndex.put(no, i);
}
endIndex.put(no, i);
}
int degree = Integer.MIN_VALUE;
for (Integer key : count.keySet()) {
degree = Math.max(degree, count.get(key));
}
for (Integer key : count.keySet()) {
if (count.get(key) == degree) {
int arraySize = endIndex.get(key) - startIndex.get(key) + 1;
ans = Math.min(ans, arraySize);
}
}
return ans;
}
} | class Solution {
public:
int findShortestSubArray(vector<int>& nums)
{
unordered_map<int,int> cnt,first;
int deg=0,ans=0;
for(int i=0;i<nums.size();i++)
{
if(cnt[nums[i]]==0)
first[nums[i]]=i;
cnt[nums[i]]++;
if(cnt[nums[i]]>deg)
{
ans=i-first[nums[i]]+1;
deg=cnt[nums[i]];
}
else if(cnt[nums[i]]==deg)
{
ans=min(ans,i-first[nums[i]]+1);
}
}
return ans;
}
};
//if you like the solution plz upvote. | /**
* 1. compute all positions for each number
* 2. filter arrays of max length
* 3. select minimum difference between its first and last elems
*/
var findShortestSubArray = function(nums) {
const numPositions = {};
for (let i=0; i<nums.length; i++) {
const num = nums[i];
if (numPositions[num] == null) numPositions[num] = [];
numPositions[num].push(i);
}
let maxLen = 0;
// will store the positions of most frequent numbers
let maxPos = [];
for (const positions of Object.values(numPositions)) {
const curLen = positions.length;
if (curLen === maxLen) {
maxPos.push(positions);
} else if (curLen > maxLen) {
maxLen = curLen;
maxPos = [positions]
}
}
let minDist = Number.MAX_SAFE_INTEGER;
for (const positions of maxPos) {
minDist = Math.min(minDist, positions[positions.length-1] - positions[0] + 1);
}
return minDist;
}; | Degree of an Array |
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
Example 1:
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints:
1 <= points.length <= 1000
-106 <= xi, yi <= 106
All pairs (xi, yi) are distinct.
| class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
cost = 0
heap = []
#set to store past points to prevent cycle
visited = set([0])
#i == the index of current point
i = 0
while len(visited) < len(points):
#Add all costs from current point to unreached points to min heap
for j in range(len(points)):
if j == i or j in visited:
continue
distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
heapq.heappush(heap, (distance, j))
#Add new min cost edge
while True:
dist, point = heapq.heappop(heap)
if point not in visited:
cost += dist
#Add point to visited to prevent cycle
visited.add(point)
#Update point
i = point
break
return cost | class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[0]-b[0]);
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
pq.add(new int[]{calDis(points,i,j),i,j});
}
}
int c = 0, ans = 0;
UnionFind uf = new UnionFind(n);
while(c < n-1){
int[] cur = pq.poll();
if(uf.find(cur[1]) != uf.find(cur[2])) {
ans += cur[0];
uf.union(cur[1],cur[2]);
c++;
}
}
return ans;
}
private int calDis(int[][] points, int a, int b) {
return Math.abs(points[a][0] - points[b][0]) + Math.abs(points[a][1] - points[b][1]);
}
class UnionFind{
int[] parent;
UnionFind(int n){
this.parent = new int[n];
for(int i=0;i<n;i++)parent[i]=i;
}
public int find(int u){
if(parent[u]!=u)parent[u] = find(parent[u]);
return parent[u];
}
public void union(int u, int v){
parent[find(u)] = parent[find(v)];
}
}
} | class Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n = points.size();
priority_queue<vector<int>> q;
unordered_set<int> vis;
int ans = 0;
q.push({0,0,0});
vector<int> cur;
while(!q.empty() && vis.size()<n){
cur = q.top(); q.pop();
if(vis.count(cur[2]))continue;
ans += -cur[0];
vis.insert(cur[2]);
for(int i=0;i<n;i++){
if(!vis.count(i)){
int d = abs(points[cur[2]][0] - points[i][0]) +
abs(points[cur[2]][1] - points[i][1]);
q.push({-d,cur[2],i});
}
}
}
return ans;
}
}; | /**
* @param {number[][]} points
* @return {number}
*/
//By Kruskal Approach
let union_find,mapping_arr,count,maxCost,rank
const find=(root)=>{
if(union_find[root]===root)return root;
return union_find[root]= find(union_find[root]);
}
const union=([src,dst,d])=>{
let rootX=find(src);
let rootY=find(dst);
if(rootX!=rootY){
if(rank[rootX]<rank[rootY]){
union_find[rootX]=rootY;
}else if(rank[rootX]>rank[rootY]){
union_find[rootY]=rootX;
}else{
union_find[rootY]=rootX;
rank[rootX]++;
}
count--;
maxCost+=d;
}
}
var minCostConnectPoints = function(points) {
let edges=[];
union_find=[];
rank=[];
maxCost=0;
count=points.length;
for(let i=0;i<points.length;i++){
union_find[i]=i;
rank[i]=1
let src=points[i];
for(let j=i+1;j<points.length;j++){
let dst=points[j];
let d= Math.abs(src[0]-dst[0])+Math.abs(src[1]-dst[1])
edges.push([i,j,d]);
}
}
edges.sort((a,b)=>a[2]-b[2])
for(let i=0;i<edges.length;i++){
if(count>1)
union(edges[i]);
}
return maxCost;
}; | Min Cost to Connect All Points |
You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.
Return an array answer of the same length as queries where answer[j] is the answer to the jth query.
Example 1:
Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
- For queries[1]=2, the items which can be considered are [1,2] and [2,4].
The maximum beauty among them is 4.
- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
The maximum beauty among them is 5.
- For queries[4]=5 and queries[5]=6, all items can be considered.
Hence, the answer for them is the maximum beauty of all items, i.e., 6.
Example 2:
Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4.
Note that multiple items can have the same price and/or beauty.
Example 3:
Input: items = [[10,1000]], queries = [5]
Output: [0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen.
Hence, the answer to the query is 0.
Constraints:
1 <= items.length, queries.length <= 105
items[i].length == 2
1 <= pricei, beautyi, queries[j] <= 109
| class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort()
dic = dict()
res = []
gmax = 0
for p,b in items:
gmax = max(b,gmax)
dic[p] = gmax
keys = sorted(dic.keys())
for q in queries:
ind = bisect.bisect_left(keys,q)
if ind<len(keys) and keys[ind]==q:
res.append(dic[q])
elif ind==0:
res.append(0)
else:
res.append(dic[keys[ind-1]])
return res | class Solution {
public int[] maximumBeauty(int[][] items, int[] queries) {
int[] ans = new int[queries.length];
Arrays.sort(items, (a, b) -> (a[0] - b[0]));
int maxBeautySoFar = Integer.MIN_VALUE;
int[] maxBeauty = new int[items.length];
for(int i = 0; i < items.length; i++) {
if(maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];
maxBeauty[i] = maxBeautySoFar;
}
for(int i = 0; i < queries.length; i++) {
int idx = findLargestIdxWithPriceLessThan(items, queries[i]);
if(idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];
}
return ans;
}
public int findLargestIdxWithPriceLessThan(int[][] items, int price) {
int l = 0;
int r = items.length - 1;
int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE;
while(l <= r) {
int mid = (l + r)/2;
if(items[mid][0] > price) {
r = mid - 1;
} else {
maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);
l = mid + 1;
}
}
return maxIdxLessThanEqualToPrice;
}
} | class Solution {
public:
vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
vector<vector<int>> v;
int n = queries.size();
for(int i = 0; i < n; i++){
v.push_back({queries[i],i});
}
sort(v.begin(),v.end());
sort(items.begin(),items.end());
vector<int> ans(n);
int j=0;
n = items.size();
int mx = 0;
for(auto &i: v){
while(j<n && items[j][0]<=i[0]){
mx = max(mx,items[j][1]);
j++;
}
ans[i[1]] = mx;
}
return ans;
}
}; | var maximumBeauty = function(items, queries) {
items.sort((a,b) => a[0]-b[0]);
const n = items.length;
let mx = items[0][1];
for (let i = 0; i<n; i++) {
mx = Math.max(mx, items[i][1]);
items[i][1] = mx;
}
const ans = [];
for (const q of queries) {
let l = 0, r = n-1, a = 0;
while (l<=r) {
let mid = Math.floor(l+(r-l)/2);
if (items[mid][0]<=q) {
a = items[mid][1]
l = mid+1;
} else r = mid-1;
}
ans.push(a)
}
return ans;
}; | Most Beautiful Item for Each Query |
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
cur's original left subtree should be the left subtree of the new left subtree root.
cur's original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]
Example 2:
Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 104].
The depth of the tree is in the range [1, 104].
-100 <= Node.val <= 100
-105 <= val <= 105
1 <= depth <= the depth of tree + 1
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def Solve(
self,
root,
val,
depth,
curr,
):
if root == None:
return None
if depth == 1:
return TreeNode(val, root)
if curr == depth - 1:
(left, right) = (root.left, root.right)
(root.left, root.right) = (TreeNode(val, left),
TreeNode(val, None, right))
return root
self.Solve(root.left, val, depth, curr + 1)
self.Solve(root.right, val, depth, curr + 1)
return root
def addOneRow(
self,
root,
val,
depth,
):
return self.Solve(root, val, depth, 1) | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
findAndAdd(root, val, depth, 1);
return root;
}
public void findAndAdd(TreeNode root, int val, int depth, int currDepth){
if(depth == 1 && currDepth == 1){
root.left = new TreeNode(root.val, root.left, root.right);
root.right = null;
root.val = val;
return;
}
if(root == null)
return;
if(currDepth == depth - 1){
root.left = new TreeNode(val, root.left, null);
root.right = new TreeNode(val, null, root.right);
}else{
findAndAdd(root.left, val, depth, currDepth + 1);
findAndAdd(root.right, val, depth, currDepth + 1);
}
return;
}
} | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def Solve(
self,
root,
val,
depth,
curr,
):
if root == None:
return None
if depth == 1:
return TreeNode(val, root)
if curr == depth - 1:
(left, right) = (root.left, root.right)
(root.left, root.right) = (TreeNode(val, left),
TreeNode(val, None, right))
return root
self.Solve(root.left, val, depth, curr + 1)
self.Solve(root.right, val, depth, curr + 1)
return root
def addOneRow(
self,
root,
val,
depth,
):
return self.Solve(root, val, depth, 1) | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @param {number} depth
* @return {TreeNode}
*/
var addOneRow = function(root, val, depth) {
if (depth === 1) return new TreeNode(val, root);
const refactor = (node = root, currentDep = 1) => {
if (!node) return;
if (currentDep === depth - 1) {
const { left, right } = node;
node.left = new TreeNode(val, left);
node.right = new TreeNode(val, null, right);
}
refactor(node.left, currentDep + 1);
refactor(node.right, currentDep + 1);
};
refactor();
return root;
}; | Add One Row to Tree |
You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.
The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.
Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.
Example 1:
Input: intervals = [[1,2]]
Output: [-1]
Explanation: There is only one interval in the collection, so it outputs -1.
Example 2:
Input: intervals = [[3,4],[2,3],[1,2]]
Output: [-1,0,1]
Explanation: There is no right interval for [3,4].
The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.
The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.
Example 3:
Input: intervals = [[1,4],[2,3],[3,4]]
Output: [-1,2,-1]
Explanation: There is no right interval for [1,4] and [3,4].
The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.
Constraints:
1 <= intervals.length <= 2 * 104
intervals[i].length == 2
-106 <= starti <= endi <= 106
The start point of each interval is unique.
| class Solution:
def findRightInterval(self, A: List[List[int]]) -> List[int]:
n = len(A)
ans = [-1] * n
for i in range(n):
A[i].append(i)
A.sort()
heap = []
for i in range(n):
if A[i][0] == A[i][1]:
ans[A[i][2]] = A[i][2]
else:
while heap and heap[0][0] <= A[i][0]:
ans[heapq.heappop(heap)[1]] = A[i][2]
heapq.heappush(heap, [A[i][1], A[i][2]])
return ans | /*
- Time: O(N*log(N))
Loop through the array with n elements and run binary search with log(N) time for each of them.
- Space: O(N)
Used a hashmap map of size N to store the original indeces of intervals
*/
class Solution {
public int[] findRightInterval(int[][] intervals) {
int n = intervals.length;
int[] res = new int[n];
Map<int[], Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(intervals[i], i);
}
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
for (int i = 0; i < n; i++) {
int[] interval = binarySearch(intervals, intervals[i][1], i);
res[map.get(intervals[i])] = interval == null ? -1 : map.get(interval);
}
return res;
}
private int[] binarySearch(int[][] intervals, int target, int start) {
int l = start, r = intervals.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (intervals[m][0] >= target) {
// keep moving the right boundary to the left to get the first
// element bigger than target
r = m - 1;
} else {
// if the element we get is bigger than the target, we move the
// left boundary to look at right part of the array
l = m + 1;
}
}
return l == intervals.length ? null : intervals[l];
}
} | class Solution {
public:
vector<int> findRightInterval(vector<vector<int>>& intervals) {
map<int, int> mp;
int n = intervals.size();
for(int i = 0; i < n; i++)
mp[intervals[i][0]] = i;
vector<int> ans;
for(auto &i : intervals)
{
auto it = mp.lower_bound(i[1]);
ans.push_back(it == mp.end() ? -1 : it->second);
}
return ans;
}
}; | var findRightInterval = function(intervals) {
const data = intervals
.map((interval, i) => ({ interval, i }))
.sort((a, b) => a.interval[0] - b.interval[0]);
const res = Array(intervals.length).fill(-1);
for (let pos = 0; pos < data.length; pos++) {
let left = pos;
let right = data.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (data[pos].interval[1] <= data[mid].interval[0]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (left < data.length) {
res[data[pos].i] = data[left].i;
}
}
return res;
}; | Find Right Interval |
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
| class Solution:
def numTilePossibilities(self, tiles: str) -> int:
n= len(tiles)
tiles=list(tiles)
s1=set()
for i in range(1,n+1):
s1.update(permutations(tiles,i))
return len(s1) | class Solution {
private int result=0;
public int numTilePossibilities(String tiles) {
Map<Character,Integer> map = new HashMap<>();
for(char c:tiles.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
find(map);
return result-1;
}
public void find(Map<Character,Integer> map){
result++;
for(Map.Entry<Character,Integer> m:map.entrySet()){
char c=m.getKey();
int val =m.getValue();
if(val>0){
map.put(c,val-1);
find(map);
map.put(c,val);
}
}
}
} | class Solution {
public:
void recur(vector<string> &ans, string tiles, int index, int &res)
{
res++;
for(int i=index; i<tiles.size(); i++)
{
if(i != index && tiles[i] == tiles[index])
continue;
swap(tiles[i], tiles[index]);
recur(ans, tiles, index+1, res);
}
}
int numTilePossibilities(string tiles) {
vector<string> ans;
sort(tiles.begin(), tiles.end());
int res = 0;
recur(ans, tiles, 0, res);
return res - 1;
}
}; | //""This solution isn`t the best way but it`s simple""
var numTilePossibilities = function(tiles) {
return search(tiles);
};
// this function takes a state and check if it`s valid or !
// valid state is not null state and unique
// e.g ["","A","A"]=>is not valid state because is has null state and repeated
// values by contrast ["A"] is valid state
// !!state below is to check if state not null
const isValidState=(state="",res=[])=>!!state&&!res.includes(state);
// this function permutes tiles by backtracking
const search=(tiles="",state='',result=[])=>{
if(isValidState(state,result))//check if the current state valid
result.push(state)
//loop through tiles and every time you push letter to state
// the remaining tiles will decreased by one
/**
* ---e.g--
* level 1 tiles=AAB state=""
* it will loop through the tiles ;
* now I am in index 0 push tiles[0] to state now state=A
* by making this operation number of option tiles will be
* decreased to newTiles="AB"
* ...
* ..
* .
* */
for(let i=0;i<tiles.length;i++){
state+=tiles[i];
const newTiles=tiles.substring(0,i)+tiles.substring(i+1);
search(newTiles,state,result)
state=state.slice(0,state.length-1);
}
return result.length;
} | Letter Tile Possibilities |
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.
You can work on the projects following these two rules:
Every week, you will finish exactly one milestone of one project. You must work every week.
You cannot work on two milestones from the same project for two consecutive weeks.
Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.
Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Example 1:
Input: milestones = [1,2,3]
Output: 6
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 2.
- During the 3rd week, you will work on a milestone of project 1.
- During the 4th week, you will work on a milestone of project 2.
- During the 5th week, you will work on a milestone of project 1.
- During the 6th week, you will work on a milestone of project 2.
The total number of weeks is 6.
Example 2:
Input: milestones = [5,2,1]
Output: 7
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 1.
- During the 3rd week, you will work on a milestone of project 0.
- During the 4th week, you will work on a milestone of project 1.
- During the 5th week, you will work on a milestone of project 0.
- During the 6th week, you will work on a milestone of project 2.
- During the 7th week, you will work on a milestone of project 0.
The total number of weeks is 7.
Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.
Thus, one milestone in project 0 will remain unfinished.
Constraints:
n == milestones.length
1 <= n <= 105
1 <= milestones[i] <= 109
| class Solution:
def numberOfWeeks(self, m: List[int]) -> int:
return min(sum(m), 2 * (sum(m) - max(m)) + 1) | class Solution {
public long numberOfWeeks(int[] milestones) {
int i,j,max=-1,n=milestones.length;
long sum=0;
for(i=0;i<n;i++)
{
max=Math.max(max, milestones[i]);
sum+=milestones[i];
}
long x=sum-max;
if(max-x>1)
return sum-(max-x-1);
return sum;
}
} | class Solution {
public:
long long numberOfWeeks(vector<int>& milestones) {
long long unsigned int maxel = *max_element(milestones.begin(), milestones.end());
long long unsigned int sum = 0;
for (auto& m : milestones) sum += m;
if (sum - maxel >= maxel) return sum;
return (sum - maxel) * 2 + 1;
}
}; | var numberOfWeeks = function(milestones) {
let maxElement = 0,arraySum = 0;
for(let milestone of milestones){
arraySum += milestone;
maxElement = Math.max(maxElement,milestone);
}
let rest = arraySum - maxElement;
let difference = maxElement - rest;
if(difference <= 1) return arraySum;
return (arraySum - difference) + 1;
}; | Maximum Number of Weeks for Which You Can Work |
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
Constraints:
The number of nodes in the tree is in the range [1, 2 * 104].
1 <= Node.val <= 105
1 <= low <= high <= 105
All Node.val are unique.
| class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
res = 0
def dfs(node):
nonlocal res
if not node:
return
if node.val >= low and node.val <= high:
res += node.val
dfs(node.left)
dfs(node.right)
dfs(root)
return res | class Solution {
private int sum = 0;
public int rangeSumBST(TreeNode root, int low, int high) {
dfs(root, low, high);
return sum;
}
public void dfs(TreeNode root, int low, int high){
if(root == null) return;
if(root.val < low) dfs(root.right, low, high);
else if(root.val > high) dfs(root.left, low, high);
if(root.val >= low && root.val <= high) {
sum += root.val;
dfs(root.left, low, high);
dfs(root.right, low, high);
}
}
} | class Solution {
public:
int solve(TreeNode* root, int low, int high){
if(root == NULL)
return 0;
int sum = 0;
if(low <= root->val && root->val <= high){
sum = root->val;
}
return sum + solve(root->left, low, high) + solve(root->right, low, high);
}
int rangeSumBST(TreeNode* root, int low, int high) {
return solve(root, low, high);
}
}; | var rangeSumBST = function(root, low, high) {
let sum = 0;
const summer = (root) => {
if(!root) {
return;
}
sum = root.val >= low && root.val <= high ? root.val + sum : sum;
summer(root.left)
summer(root.right)
}
summer(root);
return sum;
}; | Range Sum of BST |
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.
| class Solution(object):
def plusOne(self, digits):
for i in range(len(digits)-1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
return digits
return [1] + digits | class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
//last digit not a 9, just add 1 to it
if(digits[len - 1] != 9){
digits[len - 1] = digits[len - 1] + 1;
return digits;
}
//last digit is a 9, find the closest digit that is not a 9
else{
int i = len - 1;
while(i >= 0 && digits[i] == 9){
digits[i] = 0;
i--;
}
if(i == -1){
int[] ret = new int[len + 1];
for(int j = 0; j < len; j++){
ret[j+1] = digits[j];
}
ret[0] = 1;
return ret;
}
digits[i] = digits[i] + 1;
}
return digits;
}
} | class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size(), carry = 0, temp = 0;
vector<int> arr;
for(int i=len-1; i>=0; i--) { // traverse from back to front
temp = digits[i] + carry;
if(i == len-1) {
temp++;
}
arr.push_back(temp % 10);
carry = temp/10;
}
if(carry) {
arr.push_back(carry);
}
reverse(arr.begin(), arr.end());
return arr;
}
}; | var plusOne = function(digits) {
for(let i=digits.length-1; i>=0; i--){
if(digits[i] === 9){
digits[i] = 0
}else{
digits[i] += 1
return digits
}
}
digits.unshift(1)
return digits
}; | Plus One |
Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100
| class Solution:
def matrixBlockSum(self, matrix: List[List[int]], k: int) -> List[List[int]]:
ROWS, COLS = len(matrix), len(matrix[0])
prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)]
for r in range(1, ROWS + 1):
for c in range(1, COLS + 1):
prefix_sums[r][c] = prefix_sums[r - 1][c] + prefix_sums[r][c - 1] + \
matrix[r - 1][c - 1] - prefix_sums[r - 1][c - 1]
res = [[0] * COLS for _ in range(ROWS)]
for r in range(ROWS):
for c in range(COLS):
res[r][c] = prefix_sums[min(r + k + 1, ROWS)][min(c + k + 1, COLS)] - \
prefix_sums[max(r - k, 0)][min(c + k + 1, COLS)] - \
prefix_sums[min(r + k + 1, ROWS)][max(c - k, 0)] + \
prefix_sums[max(r - k, 0)][max(c - k, 0)]
return res | class Solution {
public int[][] matrixBlockSum(int[][] mat, int k) {
int m = mat.length,n = mat[0].length;
int[][] answer = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int val = 0;
// take new variables to get starting index of mat[r][c]
int p = i-k,q=j-k;
//make sure p and q are atleast 0 (i.e. valid)
while(p<0)
p++;
while(q<0)
q++;
//traverse again in the matrix with starting at p,q and ending at i+k and j+k
//add conditions to make sure the indices dont cross the values of m and n
for(int x = p;x<=i+k && x<m;x++){
for(int y = q;y<=j+k && y<n;y++){
val += mat[x][y];
}
}
answer[i][j] = val;
}
}
return answer;
}
} | class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int n = mat.size(), m = mat[0].size();
vector<vector<int>> pref(n+1, vector<int>(m+1, 0));
// Calculating prefix sum
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
// note that while counting for [i-1][j] and [i][j-1];
// pref[i-1][j-1] will be added twice. So we reduce it once.
pref[i][j] = mat[i-1][j-1] + pref[i-1][j] + pref[i][j-1] - pref[i-1][j-1];
}
}
// Find the sum of the elements specified in the K-block
vector<vector<int>> res(n, vector<int>(m, 0));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
// checking for all pairs to be in bounds.
int r1 = max(0, i-k);
int c1 = max(0, j-k);
int r2 = min(n-1, i+k);
int c2 = min(m-1, j+k);
// finding res[i][j] = bottom right - bottom left - top right + top left
res[i][j] = pref[r2+1][c2+1] - pref[r2+1][c1] - pref[r1][c2+1] + pref[r1][c1];
}
}
return res;
}
}; | /**
* @param {number[][]} mat
* @param {number} k
* @return {number[][]}
*/
var matrixBlockSum = function(mat, k) {
let sum = 0;
let dp = Array(mat.length + 1);
dp[0] = Array(mat[0].length).fill(0);
// sum of row el
for (let i = 0; i < mat.length; i++){
dp[i + 1] = Array(mat[0].length).fill(0);
for (let j = 0; j < mat[0].length; j++){
dp[i + 1][j] += mat[i][j] + sum;
sum = dp[i + 1][j];
}
sum = 0;
}
// sum of col el
for (let j = 0; j < mat[0].length; j++){
for (let i = 0; i < mat.length; i++){
dp[i + 1][j] += sum;
sum = dp[i + 1][j];
}
sum = 0;
}
dp = dp.slice(1);
// cal sum of blocks
for (let i = 0; i < mat.length; i++){
let r1 = Math.max(0, i - k);
let r2 = Math.min(mat.length - 1, i + k);
for (let j = 0; j < mat[0].length; j++){
let c1 = Math.max(0, j - k);
let c2 = Math.min(mat[0].length - 1, j + k);
let value = dp[r2][c2];
if (r1 - 1 >= 0){
value -= dp[r1 - 1][c2];
}
if (c1 - 1 >= 0){
value -= dp[r2][c1 - 1]
}
if (r1 - 1 >= 0 && c1 - 1 >= 0){
value += dp[r1 - 1][c1 - 1];
}
mat[i][j] = value;
}
}
return mat;
}; | Matrix Block Sum |
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1
Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
| class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
@cache
def dfs(i, sum_):
if i == len(nums):
if sum_ == target: return 1
else: return 0
return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i])
if abs(target) > sum(nums): return 0
return dfs(0, 0) | class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for(int i:nums){
sum += i;
}
if(target>sum || target<-sum || ((target+sum)&1)!=0) return 0;
return subsetSum(nums,(target+sum)/2);
}
private int subsetSum(int[] nums,int target){
int[][] dp = new int[nums.length+1][target+1];
dp[0][0] = 1;
for(int i=1;i<nums.length+1;i++){
for(int j=0;j<target+1;j++){
if(nums[i-1]<=j){
dp[i][j] += dp[i-1][j-nums[i-1]] + dp[i-1][j];
}
else dp[i][j] += dp[i-1][j];
}
}
return dp[nums.length][target];
}
} | class Solution { // YAA
public:
int solve(vector<int>& nums, int target, int idx, unordered_map<string, int> &dp) {
if(idx == nums.size()) {
if(target == 0) {
return 1;
}
return 0;
}
string key = to_string(idx) + " " + to_string(target);
if(dp.find(key) != dp.end()) {
return dp[key];
}
// +
int x = solve(nums, target - nums[idx], idx+1, dp);
// -
int y = solve(nums, target + nums[idx], idx+1, dp);
// sum
return dp[key] = x+y;
}
int findTargetSumWays(vector<int>& nums, int target) {
unordered_map<string, int> dp;
return solve(nums, target, 0, dp);
}
}; | var findTargetSumWays = function(nums, target) {
const memo = new Map()
return backtrack(0, 0)
function backtrack(i, cur){
const key = `${i} ${cur}`
if(i == nums.length) return cur == target ? 1 : 0
if(!memo.has(key)) memo.set(key, backtrack(i + 1, -nums[i] + cur) + backtrack(i + 1, nums[i] + cur))
return memo.get(key)
}
}; | Target Sum |
Given an array arr of positive integers, consider all binary trees such that:
Each node has either 0 or 2 children;
The values of arr correspond to the values of each leaf in an in-order traversal of the tree.
The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.
Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
A node is a leaf if and only if it has zero children.
Example 1:
Input: arr = [6,2,4]
Output: 32
Explanation: There are two possible trees shown.
The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.
Example 2:
Input: arr = [4,11]
Output: 44
Constraints:
2 <= arr.length <= 40
1 <= arr[i] <= 15
It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 231).
| class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
n = len(arr)
d = {}
def findMax(start,end):
if (start,end) in d: return d[(start,end)]
maxx = start
for i in range(start+1,end+1):
if arr[maxx] < arr[i] : maxx = i
d[(start,end)] = arr[maxx]
return arr[maxx]
dp = [[float('inf') for i in range(n)] for j in range(n)]
for gap in range(n):
for row in range(n - gap):
col = row + gap
if gap == 0:
dp[row][col] = 0
elif gap == 1:
dp[row][col] = arr[row] * arr[col]
else:
for k in range(row,col):
val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]
if val < dp[row][col]: dp[row][col] = val
return dp[0][-1] | class Solution {
public int mctFromLeafValues(int[] arr) {
int sum = 0;
Stack<Integer> stack = new Stack<>();
for (int num: arr) {
sum += cleanUpStack(num, stack);
}
sum += cleanUpStack(17, stack);
return sum;
}
private int cleanUpStack(int target, Stack<Integer> stack) {
int last = 0;
int sum = 0;
while (!stack.isEmpty() && stack.peek() <= target) {
int cur = stack.pop();
sum += last * cur;
last = cur;
}
if (target != 17) {
sum += target * last;
stack.push(target);
}
return sum;
}
} | class Solution {
public:
int dp[40][40]={0};
int solve(vector<int> arr,int start,int end)
{
if(start==end)
return 0;
if(dp[start][end]!=0)
return dp[start][end];
int mn=INT_MAX;
for(int i=start;i<=end-1;i++)
{
int left=solve(arr,start,i);
int right=solve(arr,i+1,end);
int temp=left+right+*max_element(arr.begin()+start,arr.begin()+i+1) * *max_element(arr.begin()+i+1,arr.begin()+end+1);
mn=min(mn,temp);
}
return dp[start][end]=mn;
}
int mctFromLeafValues(vector<int>& arr)
{
return solve(arr,0,arr.size()-1);
}
};
//if you like the solution plz upvote. | var mctFromLeafValues = function(arr) {
const dp = [];
for (let i = 0; i < arr.length; i++) {
dp[i] = [];
}
return treeBuilder(0, arr.length - 1);
function treeBuilder(start, end) {
if (start == end) {
return 0;
}
if (dp[start][end]) {
return dp[start][end];
}
let min = Number.MAX_VALUE;
for (let i = start; i < end; i++) {
const left = treeBuilder(start, i);
const right = treeBuilder(i + 1, end);
const maxLeft = Math.max(...arr.slice(start, i + 1));
const maxRight = Math.max(...arr.slice(i + 1, end + 1));
const rootVal = maxLeft * maxRight;
min = Math.min(min, rootVal + left + right);
}
dp[start][end] = min;
return min;
}
}; | Minimum Cost Tree From Leaf Values |
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.
For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.
Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
Example 1:
Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.
Example 2:
Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.
Example 3:
Input: s = "110100010"
Output: false
Explanation:
The longest contiguous segment of 1s has length 2: "110100010"
The longest contiguous segment of 0s has length 3: "110100010"
The segment of 1s is not longer, so return false.
Constraints:
1 <= s.length <= 100
s[i] is either '0' or '1'.
| class Solution:
def checkZeroOnes(self, s: str) -> bool:
s1 = s.split('0')
s0 = s.split('1')
r1 = max([len(i) for i in s1])
r0 = max([len(i) for i in s0])
return r1>r0 | class Solution {
public boolean checkZeroOnes(String s) {
int length1 = 0;
int length0 = 0;
int i = 0;
while(i < s.length()){
int temp = 0;
while(i < s.length() && s.charAt(i) == '1'){ //counting 1s
temp++;
i++;
}
length1 = Math.max(temp,length1);
temp = 0;
while(i < s.length() && s.charAt(i) == '0'){ // counting 0s
temp++;
i++;
}
length0 = Math.max(temp,length0);
}
return length1 > length0;
}
} | class Solution {
public:
bool checkZeroOnes(string s) {
int count1=0;
int count2=0;
int max1=0;int max2=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='1')
{
count1++;
if(s[i+1]!=s[i])
{
max1=max(count1,max1);
count1=0;
}
}
if(s[i]=='0')
{
count2++;
if(s[i+1]!=s[i])
{
max2=max(count2,max2);
count2=0;
}
}
}
if(max1>max2)
return true;
return false;
}
}; | var checkZeroOnes = function(s) {
let longest1 = 0;
let longest0 = 0;
let count1 = 0;
let count0 = 0;
for (let i = 0; i < s.length; i++) {
const bit = s.charAt(i);
if (bit === "1") count1++;
else count1 = 0;
if (bit === "0") count0++;
else count0 = 0;
longest1 = Math.max(longest1, count1);
longest0 = Math.max(longest0, count0);
}
return longest1 > longest0;
}; | Longer Contiguous Segments of Ones than Zeros |
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).
For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:
Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]
Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]
Every day (86400-second chunks): [10,10000]
Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).
Design and implement an API to help the company with their analysis.
Implement the TweetCounts class:
TweetCounts() Initializes the TweetCounts object.
void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).
List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.
freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0
tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60
tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet
tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets
Constraints:
0 <= time, startTime, endTime <= 109
0 <= endTime - startTime <= 104
There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.
| import bisect
class TweetCounts:
def __init__(self):
self.tweets = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if not tweetName in self.tweets:
self.tweets[tweetName] = []
index = bisect.bisect_left(self.tweets[tweetName], time)
self.tweets[tweetName].insert(index, time)
def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
def find(step):
nonlocal tweet
result = []
for i in range(startTime, endTime+1, step):
result.append(bisect.bisect_right(tweet, min(endTime, i + step - 1)) - bisect.bisect_left(tweet, i))
return result
tweet = self.tweets[tweetName]
if freq == "minute":
return find(60)
elif freq == "hour":
return find(3600)
else:
return find(86400) | class TweetCounts {
Map<String, List<Integer>> map;
public TweetCounts() {
map = new HashMap<>();
}
public void recordTweet(String tweetName, int time) {
map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time);
}
public List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {
List<Integer> res = new ArrayList<>();
if(map.containsKey(tweetName)) {
Collections.sort(map.get(tweetName));
while(startTime<=endTime) {
int interval = Freq.valueOf(freq).getVal();
int end = Math.min(startTime+interval-1, endTime); // need this to handle the last interval
res.add(getFreq(map.get(tweetName), startTime, end));
startTime=end+1; // ex: for minute, the interval is 60 so our end is 59. The next startTime is end+1
}
}
return res;
}
public int getFreq(List<Integer> list, int start, int end) {
int st = Collections.binarySearch(list, start);
if(st<0) {
st = (st+1)*-1; // our exact start time might not be in the list, to get the 1st timestamp greater than start
}
int en = Collections.binarySearch(list, end);
if(en<0) {
en = (en+2)*-1; // our exact end time might not be in the list, to get the last timestamp just smaller than end
}
return en-st+1; // the freq count
}
}
enum Freq {
minute(60), hour(3600), day(86400);
Map<Freq, Integer> map = new HashMap<>();
Freq(int val) {
map.put(this, val);
}
public int getVal() {
return map.get(this);
}
}
/**
* Your TweetCounts object will be instantiated and called as such:
* TweetCounts obj = new TweetCounts();
* obj.recordTweet(tweetName,time);
* List<Integer> param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);
*/ | #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
//less_equal to use it as a multiset
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
class TweetCounts {
public:
unordered_map<string, pbds> tweet;
TweetCounts() {
tweet.clear();
}
void recordTweet(string tweetName, int time) {
tweet[tweetName].insert(time);
}
vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
int interval;
if(freq == "minute") interval = 60;
else if(freq == "hour") interval = 3600;
else interval = 86400;
vector<int> ans;
for(int i=startTime; i<=endTime; i+=interval)
{
int start = i, end = min(endTime, i+interval-1);
//[start - end] or [start - end+1)
auto low = tweet[tweetName].order_of_key(start);
auto high = tweet[tweetName].order_of_key(end+1);
ans.push_back(high-low);
}
return ans;
}
}; | var TweetCounts = function() {
this.map = new Map();
};
TweetCounts.prototype.recordTweet = function(tweetName, time) {
if (!this.map.has(tweetName)) this.map.set(tweetName, []);
this.map.get(tweetName).push(time);
};
TweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, endTime) {
if (!this.map.has(tweetName)) return [];
const tweets = this.map.get(tweetName);
const buckets = createBuckets(freq, startTime, endTime);
for (let i = 0; i < tweets.length; i++) {
const tweetTime = tweets[i];
let left = 0;
let right = buckets.length - 1;
while (left <= right) {
const mid = (left + right) >> 1;
const [startTime, endTime, count] = buckets[mid];
if (startTime <= tweetTime && tweetTime <= endTime) {
buckets[mid][2] = count + 1;
break;
}
if (endTime < tweetTime) left = mid + 1;
else right = mid - 1;
}
}
const res = [];
for (let i = 0; i < buckets.length; i++) {
res.push(buckets[i][2]);
}
return res;
function createBuckets(freq, startTime, endTime) {
const chunks = { "minute": 60, "hour": 3600, "day": 86400 };
const buckets = [];
let start = startTime;
while (start <= endTime) {
const end = Math.min(start + chunks[freq] - 1, endTime);
buckets.push([start, end, 0])
start = end + 1;
}
return buckets;
}
}; | Tweet Counts Per Frequency |