algo_input
stringlengths 240
3.91k
| solution_py
stringlengths 10
6.72k
| solution_java
stringlengths 87
8.97k
| solution_c
stringlengths 10
7.38k
| solution_js
stringlengths 10
4.56k
| title
stringlengths 3
77
|
---|---|---|---|---|---|
You are given a 0-indexed integer array nums consisting of 3 * n elements.
You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:
The first n elements belonging to the first part and their sum is sumfirst.
The next n elements belonging to the second part and their sum is sumsecond.
The difference in sums of the two parts is denoted as sumfirst - sumsecond.
For example, if sumfirst = 3 and sumsecond = 2, their difference is 1.
Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.
Return the minimum difference possible between the sums of the two parts after the removal of n elements.
Example 1:
Input: nums = [3,1,2]
Output: -1
Explanation: Here, nums has 3 elements, so n = 1.
Thus we have to remove 1 element from nums and divide the array into two equal parts.
- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.
- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.
- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.
The minimum difference between sums of the two parts is min(-1,1,2) = -1.
Example 2:
Input: nums = [7,9,5,8,1,3]
Output: 1
Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.
If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.
To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.
It can be shown that it is not possible to obtain a difference smaller than 1.
Constraints:
nums.length == 3 * n
1 <= n <= 105
1 <= nums[i] <= 105
| class Solution:
def minimumDifference(self, nums: List[int]) -> int:
h=heapq
k=len(nums)//3
min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, []
h.heapify(max_heap) , h.heapify(min_heap)
for x in nums[:-k]:
h.heappush(min_heap,-x)
min_sum+=x
if len(min_heap)>k: min_sum+=h.heappop(min_heap)
min_sol.append(min_sum)
for x in nums[::-1][:-k]:
h.heappush(max_heap,x)
max_sum+=x
if len(max_heap)>k: max_sum-=h.heappop(max_heap)
max_sol.append(max_sum)
min_sol =min_sol[k-1:]
max_sol=max_sol[k-1:][::-1]
return min( min_value - max_value for min_value , max_value in zip(min_sol,max_sol) ) | class Solution {
public long minimumDifference(int[] nums) {
int n=nums.length; //length of nums
int len3=n/3; // 1/3 length
long res=Long.MAX_VALUE; // final result;
//Try to make first part as min as possible;
//first[m] store the value, the min value of the size=len3, from[0,1,..., m];
long[] first=new long[n];
//Try to make second part as max as possible;
//second[m] store the value, the max value of the size=len3, from[m,...,n-1];
long[] second=new long[n];
//--------------------for first part compute -------------------------------------
//Build max heap for first part;
PriorityQueue<Integer> max=new PriorityQueue<Integer>(Comparator.reverseOrder());
long sum=0;
// Initialize with the first 1/3 n part.
for(int i=0;i<len3;i++){
sum+=nums[i];
max.add(nums[i]);
}
//For the second part between 1/3 ~ 2/3. When we move to next index.
//we keep the sum as total 1/3n size: each time poll the max one and add the new one;
//And we keep tracking the exchange by long[] first;
//
for(int i=len3;i<=2*len3;i++){
first[i]=sum; //add sum from 1/3
max.add(nums[i]); //put new one in queue;
sum+=nums[i]; //sum + new one;
sum-=max.poll(); //sum - max one;
}
//--------------------for second part compute -----------------------
sum=0;
//Build min heap for first part;
PriorityQueue<Integer> min=new PriorityQueue<Integer>();
// Initialize with the last 1/3 n part.
for(int i=0;i<len3;i++){
sum+=nums[n-1-i];
min.add(nums[n-1-i]);
}
//For the second part between 2/3~1/3 When we move to next index:
// we keep update the sum with(+ new element, - min element), and update second;
for(int i=len3;i<=2*len3;i++){
second[n-i]=sum;
min.add(nums[n-1-i]);
sum+=nums[n-1-i];
sum-=min.poll();
}
//-----------------compute the final result------------
//find the max value in second part [ i,..., n-1];
//find the min value in first part [0,....,i];
// find the result;
for(int i=len3;i<=2*len3;i++){
res=Math.min(res,first[i]-second[i]);
}
return res;
}
} | class Solution {
public:
long long minimumDifference(vector<int>& nums) {
int N = nums.size();
int n = N/3;
priority_queue<int> pq;
map<int, long long> m;
long long sum = 0;
for(int i=0;i<n;i++){
sum += nums[i];
pq.push(nums[i]);
}
for(int i=0;i<=n;i++){
if(i == 0){
m[i] = sum;
}
else{
pq.push(nums[n+i-1]);
sum += nums[i+n-1];
sum -= pq.top();
pq.pop();
m[i] = sum;
}
}
sum = 0;
priority_queue<int, vector<int>, greater<int>> p;
for(int i=N-1;i>N-1-n;i--){
sum += nums[i];
p.push(nums[i]);
}
for(int i=0;i<=n;i++){
if(i == 0){
m[n-i] -= sum;
}
else{
p.push(nums[N-n-i]);
sum += nums[N-n-i];
sum -= p.top();
p.pop();
m[n-i] -= sum;
}
}
long long ans = 9223372036854775807;
for(auto it : m){
ans = min(ans, it.second);
}
return ans;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var minimumDifference = function(nums) {
//Creating heap
class Heap{
constructor(type){
this.type = type;
this.data = [];
this.data[0] = undefined;
}
print(){
for(let i=1;i<this.data.length;i++){
console.log(this.data[i])
}
}
getSize(){
return this.data.length-1;
}
insert(value){
this.data.push(value);
if(this.data.length==2){
return ;
}
let lastIndex = this.data.length-1;
while(this.data[Math.floor(lastIndex/2)]!==undefined && this.compare(this.data[lastIndex],this.data[Math.floor(lastIndex/2)])>0){
let temp = this.data[Math.floor(lastIndex/2)];
this.data[Math.floor(lastIndex/2)] = this.data[lastIndex];
this.data[lastIndex] = temp;
lastIndex = Math.floor(lastIndex/2);
}
}
//This returns a positive number if a is greater than b. Here meaing of being greater depends on the type of heap. For max heap it will return positive number if a>b and for min heap it will return positive number if a<b .
compare(a,b){
if(this.type==="min"){
return b-a;
}else{
return a-b;
}
}
removeTop(){
let max = this.data[1];
if(this.getSize()>1){
this.data[1] = this.data.pop();
this.heapify(1);
}else{//If the size is 0 then just remove the element, no shifting and hipify will be applicable
this.data.pop();
}
return max;
}
getTop(){
let max = null;
if(this.getSize()>=1){
max = this.data[1];
}
return max;
}
heapify(pos){
if(pos*2>this.data.length-1){
//That means element at index 'pos' is not having any child
return;
}
if(
(this.data[pos*2]!==undefined && this.compare(this.data[pos*2],this.data[pos])>0)
|| (this.data[pos*2+1]!==undefined && this.compare(this.data[pos*2+1],this.data[pos])>0)
){
if(this.data[pos*2+1]===undefined || this.compare(this.data[pos*2+1],this.data[pos*2])<=0){
let temp = this.data[pos*2];
this.data[pos*2] = this.data[pos];
this.data[pos] = temp;
this.heapify(pos*2);
}else{
let temp = this.data[pos*2+1];
this.data[pos*2+1] = this.data[pos];
this.data[pos] = temp;
this.heapify(pos*2+1);
}
}
}
}
let maxHeap=new Heap(),minHeap=new Heap('min'),sum=0;
let n = nums.length/3,leftArr=[],rightArr=[];
for(let i=0;i<2*n;i++){
if(maxHeap.getSize()<n){
sum += nums[i];
maxHeap.insert(nums[i]);
}else{
if(maxHeap.getTop()>nums[i]){
let top = maxHeap.removeTop();
sum -= top;
sum += nums[i];
maxHeap.insert(nums[i]);
}
}
if(maxHeap.getSize()===n){
leftArr.push(sum);
}
}
sum=0;
for(let i=3*n-1;i>=n;i--){
if(minHeap.getSize()<n){
sum += nums[i];
minHeap.insert(nums[i]);
}else{
if(minHeap.getTop()<nums[i]){
let top = minHeap.removeTop();
sum -= top;
sum += nums[i];
minHeap.insert(nums[i]);
}
}
if(minHeap.getSize()===n){
rightArr.push(sum);
}
}
rightArr.reverse();
let min = Number.MAX_SAFE_INTEGER;
for(let i=0;i<leftArr.length;i++){
min = Math.min(min,leftArr[i]-rightArr[i]);
}
return min;
}; | Minimum Difference in Sums After Removal of Elements |
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104
| class Solution:
def reverseStr(self, s: str, k: int) -> str:
a=list(s)
for i in range(0,len(a),2*k):
a[i:i+k]=a[i:i+k][::-1]
print(a)
return("".join(a)) | class Solution {
public String reverseStr(String s, int k) {
char[] ch=s.toCharArray();
int cnt=1,i=0;
StringBuilder sb=new StringBuilder();
String ans="";
if(k>=s.length()){
sb.append(s);
sb.reverse();
return sb.toString();
}
for(i=0;i<s.length()-k;i+=k){
String str=s.substring(i,i+k);
if(cnt%2!=0){
sb.append(str);
sb.reverse();
ans+=sb.toString();
cnt++;
sb=new StringBuilder();
}
else{
ans+=str;
cnt++;
}
}
if(cnt%2!=0){
sb.append(s.substring(i,s.length()));
sb.reverse();
ans+=sb.toString();
}
else{
ans+=s.substring(i,s.length());
}
return ans;
}
} | Time: O(n) Space: O(1)
class Solution {
public:
string reverseStr(string s, int k) {
int n=size(s);
for(int i=0;i<n;i=i+2*k){
int j=i+k-1,k=i;
if(j>=n)
j=n-1;
while(k<(j)){
swap(s[k],s[j]);
k++,j--;
}
}
return s;
}
}; | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var reverseStr = function(s, k) {
const sArr = s.split('');
let start = 0;
let end = k - 1;
const swapBlock = (start, end) => {
while (start < end) {
[sArr[start], sArr[end]] = [sArr[end], sArr[start]];
start++;
end--;
}
};
while (start < end) {
swapBlock(start, end);
start = start + (k * 2);
end = sArr[start + (k-1)] ? start + (k-1) : s.length - 1;
}
return sArr.join('');
}; | Reverse String II |
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:
hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.
Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.
The test cases will be generated such that an answer always exists.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
Output: "ee"
Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0.
"ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
Example 2:
Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
Output: "fbx"
Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32.
The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32.
"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
Note that "bxz" also has a hash of 32 but it appears later than "fbx".
Constraints:
1 <= k <= s.length <= 2 * 104
1 <= power, modulo <= 109
0 <= hashValue < modulo
s consists of lowercase English letters only.
The test cases are generated such that an answer always exists.
| class Solution:
def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:
val = lambda ch : ord(ch) - ord("a") + 1
hash, res, power_k = 0, 0, pow(power, k, mod)
for i in reversed(range(len(s))):
hash = (hash * power + val(s[i])) % mod
if i < len(s) - k:
hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod
res = i if hash == hashValue else res
return s[res:res + k] | class Solution {
public String subStrHash(String s, int power, int modulo, int k, int hashValue) {
// calculate all the powers from power^0 till power^k
// utilized binary exponentiation
long[] powers = new long[k];
for (int i = 0; i < k; i++)
powers[i] = binaryExponentiation(power, i, modulo);
// pre compute the initial hash from behind.
// I have explained at top you why traversing from behind is easy
long currentHashValue = 0;
int index = s.length() - 1;
int powerIndex = k-1;
while (index >= s.length() - k) {
// (a+b) % modulo = ( (a % modulo) + (b % modulo) ) % modulo;
// do it for k times from behind
currentHashValue += ((s.charAt(index--) - 'a' + 1) % modulo * powers[powerIndex--] % modulo) % modulo;
}
currentHashValue %= modulo;
int startIndex = 0;
if (currentHashValue == hashValue) {
startIndex = s.length() - k;
}
// I have pre computed already for k values from behind. so start from (length of S - k - 1)
// Let's take an example of "leetcode" itself
// "de" is pre computed
// point is to add one character from behind and remove one from end (Sliding from back to first)
// Modular Arithmetic for (a-b) % modulo = ( (a % modulo) - (b % modulo) + modulo) % modulo;
// keep tracking of the start index if hash value matches. That's it.
for (int i = s.length() - k - 1; i >= 0; i--) {
// below line a --> currentHashValue
// below line b --> (s.charAt(i+k) - 'a' + 1 * powers[k-1])
currentHashValue = ((currentHashValue % modulo) - (((s.charAt(i+k) - 'a' + 1) * powers[k-1]) % modulo) + modulo) % modulo;
// we need to multiply a power once for all
// MULTIPLICATION
currentHashValue = currentHashValue * power;
// Modular Arithmetic for (a+b) % modulo is below line
currentHashValue = (currentHashValue % modulo + (s.charAt(i) - 'a' + 1) % modulo) % modulo;
if (currentHashValue == hashValue) {
startIndex = i;
}
}
return s.substring(startIndex, startIndex+k);
}
private long binaryExponentiation(long a, long b, long mod) {
a %= mod;
long result = 1;
while (b > 0) {
if (b % 2 == 1)
result = result * a % mod;
a = a * a % mod;
b >>= 1;
}
return result;
}
} | '''
class Solution {
public:
string subStrHash(string s, int power, int modulo, int k, int hashValue) {
int n=s.size();
long long int sum=0;
long long int p=1;
// Intializing a window from end of size k
for(int i=0;i<k;i++){
sum=(sum+((s[n-k+i]-'a'+1)*p));
if(i!=k-1)
p=(p*power)%modulo;
}
// storing the res when ever we get required answer
int res=n-k; // storing the res when ever we get required answer
// slide window to right and removing ith index element and adding (i-k)th index element
for(int i=n-1;i>=k;i--)
{
//removing last element from window
sum-=(s[i]-'a'+1)*(p%modulo);
// dividing by modulo to avoid integer overflow conditions
sum=sum%modulo;
// muliplying the given string by power
sum=sum*(power%modulo);
// adding (i-k)th element in the window
sum+=s[i-k]-'a'+1;
// if sum < 0 then it created problem in modulus thats why making it positive
while(sum%modulo<0){
sum=sum+modulo;
}
if(sum%modulo==hashValue){
res=i-k; // storing the starting window index because we have to return the first string from starting
}
}
return s.substr(res,k);
}
};
''' | let arrChar ="1abcdefghijklmnopqrstuvwxyz".split("");
var subStrHash = function(s, power, modulo, k, hashValue) {
for(let i=0;i<s.length;i++){
let subStr = s.substring(i,i+k);
if(hash(subStr,power,modulo)==hashValue){
return subStr;
}
}
};
let hash = function(str,power,m){
let result=0;
for(let i=0;i<str.length;i++){
result += arrChar.indexOf(str[i])*Math.pow(power,i);
}
return result%m;
} | Find Substring With Given Hash Value |
There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.
There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.
Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.
The subtree rooted at a node x contains node x and all of its descendant nodes.
Example 1:
Input: parents = [-1,0,0,2], nums = [1,2,3,4]
Output: [5,1,1,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
Example 2:
Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]
Output: [7,1,1,4,2,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.
- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
Example 3:
Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]
Output: [1,1,1,1,1,1,1]
Explanation: The value 1 is missing from all the subtrees.
Constraints:
n == parents.length == nums.length
2 <= n <= 105
0 <= parents[i] <= n - 1 for i != 0
parents[0] == -1
parents represents a valid tree.
1 <= nums[i] <= 105
Each nums[i] is distinct.
| class Solution:
def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:
ans = [1] * len(parents)
if 1 in nums:
tree = {}
for i, x in enumerate(parents):
tree.setdefault(x, []).append(i)
k = nums.index(1)
val = 1
seen = set()
while k != -1:
stack = [k]
while stack:
x = stack.pop()
seen.add(nums[x])
for xx in tree.get(x, []):
if nums[xx] not in seen:
stack.append(xx)
seen.add(nums[xx])
while val in seen: val += 1
ans[k] = val
k = parents[k]
return ans | class Solution {
public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {
int n = parents.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = 1;
}
int oneIndex = -1;
for (int i = 0; i < n; i++) {
if (nums[i] == 1) {
oneIndex = i;
break;
}
}
// 1 not found
if (oneIndex == -1) {
return res;
}
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 1; i < n; i++) {
Set<Integer> children = graph.getOrDefault(parents[i], new HashSet<Integer>());
children.add(i);
graph.put(parents[i], children);
}
Set<Integer> visited = new HashSet<Integer>();
int parentIter = oneIndex;
int miss = 1;
while (parentIter >= 0) {
dfs(parentIter, graph, visited, nums);
while (visited.contains(miss)) {
miss++;
}
res[parentIter] = miss;
parentIter = parents[parentIter];
}
return res;
}
public void dfs(int ind, Map<Integer, Set<Integer>> graph, Set<Integer> visited, int []nums) {
if (!visited.contains(nums[ind])) {
Set <Integer> children = graph.getOrDefault(ind, new HashSet<Integer>());
for (int p : children) {
dfs(p, graph, visited, nums);
}
visited.add(nums[ind]);
}
}
} | class Solution {
public:
unordered_set<int> visited;
vector<int> nums ;
vector<vector<int>> adj;
void dfs(int node){
for(auto child:adj[node]){
if(!visited.count(nums[child])){
visited.insert(nums[child]);
dfs(child);
}
}
}
vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
int n = parents.size(), missing = 1;
adj.resize(n);
vector<int> res;
this->nums = nums;
res.resize(n,1);
for(int i=1; i<n; i++) adj[parents[i]].push_back(i);
int node = -1;
for(int i=0; i<n; i++){
if(nums[i] == 1) {
node = i;
break ;
}
}
if(node == -1) return res;
while(node != -1) {
visited.insert(nums[node]);
dfs(node);
while(visited.count(missing)) missing++;
res[node] = missing;
node = parents[node];
}
return res;
}
}; | var smallestMissingValueSubtree = function(parents, nums) {
let n=parents.length,next=[...Array(n)].map(d=>[]),used={}
for(let i=1;i<n;i++)
next[parents[i]].push(i)
let dfs=(node)=>{
if(used[nums[node]])
return
used[nums[node]]=true
for(let child of next[node])
dfs(child)
}
let cur=nums.indexOf(1),leftAt=1,res=[...Array(n)].map(d=>1)
while(cur!==-1){
dfs(cur)
while(used[leftAt])
leftAt++
res[cur]=leftAt
cur=parents[cur]
}
return res
}; | Smallest Missing Genetic Value in Each Subtree |
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 104
s and goal consist of lowercase letters.
| from collections import Counter
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
diffCharactersCount = 0
diffCharactersInS = []
diffCharactersInGoal = []
for i in range(len(s)):
if s[i] != goal[i]:
diffCharactersCount += 1
diffCharactersInS.append(s[i])
diffCharactersInGoal.append(goal[i])
if diffCharactersCount == 2:
# if there are only 2 different characters, then they should be swappable
if ((diffCharactersInS[0] == diffCharactersInGoal[1]) and (diffCharactersInS[1] == diffCharactersInGoal[0])):
return True
return False
elif diffCharactersCount == 0:
# if there is atleast one repeating character in the string then its possible for swap
counts = Counter(s)
for k,v in counts.items():
if v > 1:
return True
# if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings
return False | class Solution {
public boolean buddyStrings(String s, String goal) {
char a = '\u0000', b = '\u0000';
char c = '\u0000', d = '\u0000';
int lenS = s.length();
int lenGoal = goal.length();
boolean flag = true;
HashSet<Character> hset = new HashSet<>();
if(lenS != lenGoal)
return false;
if(s.equals(goal)){
for(int i = 0; i < lenS; i++){
if(!hset.contains(s.charAt(i))){
hset.add(s.charAt(i));
}
else
return true;
}
return false;
}
else{
for(int i = 0; i < lenS; i++){
if(s.charAt(i) == goal.charAt(i)){
continue;
}
if(a == '\u0000'){
a = s.charAt(i);
c = goal.charAt(i);
continue;
}
if(b == '\u0000'){
b = s.charAt(i);
d = goal.charAt(i);
continue;
}
return false;
}
if(a == d && c == b && a != '\u0000')
return true;
return false;
}
}
} | class Solution {
public:
//In case string is duplicated, check if string has any duplicate letters
bool dupeCase(string s){
unordered_set<char> letters;
for(auto it : s){
if(letters.count(it)){ //Found dupe letter (they can be swapped)
return true;
} else {
letters.insert(it);
}
}
return false; //all letters unique
}
bool buddyStrings(string s, string goal) {
//check len
if(goal.length() != s.length()) return false;
//If strings are the same, use diff. method
if(s == goal) return dupeCase(s);
//Track index of differences
vector<int> diff;
for(int i = 0; i < s.length(); i++){
if(s[i] != goal[i]){ //If diff found
if(diff.size() > 2){ //If this is third diff, return false
return false;
} else { //If not store in diff array
diff.push_back(i);
}
}
}
//If only one diff found, return false
if(diff.size() == 1) return false;
//else return if swap works
return (s[diff[0]] == goal[diff[1]] && s[diff[1]] == goal[diff[0]]);
}
}; | var buddyStrings = function(A, B) {
if(A.length != B.length) return false;
const diff = [];
for(let i = 0; i < A.length; i++) {
if(A[i] != B[i]) diff.push(i);
if(diff.length > 2) return false;
}
if(!diff.length) return A.length != [...new Set(A)].length;
const [i, j] = diff;
return A[i] == B[j] && B[i] == A[j];
}; | Buddy Strings |
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.
Example 1:
Input: timePoints = ["23:59","00:00"]
Output: 1
Example 2:
Input: timePoints = ["00:00","23:59","00:00"]
Output: 0
Constraints:
2 <= timePoints.length <= 2 * 104
timePoints[i] is in the format "HH:MM".
| class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
timePoints.sort()
def getTimeDiff(timeString1, timeString2):
time1 = int(timeString1[:2]) * 60 + int(timeString1[3:])
time2 = int(timeString2[:2]) * 60 + int(timeString2[3:])
minDiff = abs(time1 - time2)
return min(minDiff, 1440 - minDiff)
result = getTimeDiff(timePoints[0], timePoints[-1]) # edge case, we need to check minDiff of first and last time after sorting
for i in range(len(timePoints)-1):
curMin = getTimeDiff(timePoints[i], timePoints[i+1])
if curMin < result:
result = curMin
return result
| class Solution {
public int findMinDifference(List<String> timePoints) {
int N = timePoints.size();
int[] minutes = new int[N];
for(int i = 0; i < N; i++){
int hr = Integer.parseInt(timePoints.get(i).substring(0, 2));
int min = Integer.parseInt(timePoints.get(i).substring(3, 5));
minutes[i] = hr * 60 + min;
}
Arrays.sort(minutes);
int res = Integer.MAX_VALUE;
for(int i = 0; i < N - 1; i++){
res = Math.min(res, minutes[i + 1] - minutes[i]);
}
int b = minutes[0];
int a = minutes[N - 1];
return Math.min(res, (b - a + 1440) % 1440);
}
} | class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
unordered_set<string> st;
for(auto &i: timePoints)
{
if(st.count(i)) return 0;
st.insert(i);
}
int ans = INT_MAX;
int first = -1,prev = 0; // first variable will take the diffrence of the first time stamp given in the input and 00:00
int hour = 0, minute = 0;
while(hour<24)
{
minute=0;
while(minute < 60)
{
string hh = to_string(hour), mm = to_string(minute);
if(hh.size() == 1) hh = '0' + hh;
if(mm.size() == 1) mm = '0' + mm;
string p = hh + ":"+ mm;
if(st.count(p))
{
if(first == -1){first = prev;}
else
{
ans = min(ans,prev);
}
prev = 0;
}
prev++;
minute++;
}
hour++;
}
ans = min(first+prev,ans);
return ans;
}
}; | var findMinDifference = function(timePoints) {
const DAY_MINUTES = 24 * 60;
const set = new Set();
for (let index = 0; index < timePoints.length; index++) {
const time = timePoints[index];
const [hours, minutes] = time.split(':');
const totalMinutes = hours * 60 + +minutes;
if (set.has(totalMinutes)) return 0;
set.add(totalMinutes);
}
const timeMinutes = [...set].sort((a, b) => a - b);
return timeMinutes.reduce((min, time, index) => {
const next = timeMinutes[index + 1];
const diff = next ? next - time : DAY_MINUTES - time + timeMinutes[0];
return Math.min(min, diff);
}, Infinity);
}; | Minimum Time Difference |
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
Constraints:
1 <= s.length <= 30
s consists of lowercase English letters, digits, and square brackets '[]'.
s is guaranteed to be a valid input.
All the integers in s are in the range [1, 300].
| class Solution:
def decodeString(self, s):
it, num, stack = 0, 0, [""]
while it < len(s):
if s[it].isdigit():
num = num * 10 + int(s[it])
elif s[it] == "[":
stack.append(num)
num = 0
stack.append("")
elif s[it] == "]":
str1 = stack.pop()
rep = stack.pop()
str2 = stack.pop()
stack.append(str2 + str1 * rep)
else:
stack[-1] += s[it]
it += 1
return "".join(stack) | class Solution {
public String decodeString(String s) {
int bb = s.indexOf('['); // location of beginning bracket
int nbb = s.indexOf('[', bb + 1); // location of next beginning bracket
int eb = s.indexOf(']'); // location of ending bracket
int n = 0; // number of times to repeat
int nl = 1; // number of digits for n
char nd; // next digit
String insert = ""; // repeated string
String end = ""; // remainder of string after repeated portion
while (bb != -1) { // while the string contains a beginning bracket
while (nbb < eb && nbb > bb) { // while the next beginning bracket is before the ending bracket
bb = nbb; // update location of beginning bracket
nbb = s.indexOf('[', bb + 1); // update location of next beginning bracket
}
nl = 1; // reset length of n
while (bb - nl >= 0) { // while there are characters in front of the beginning bracket
nd = s.charAt(bb - nl); // next digit
if (nd <= '9' && nd >= '0') { // if next digit is an integer
n += (int)(nd - '0') * Math.pow(10, nl - 1); // update value of n
nl++; // increment length of n
}
else break; // not an integer
}
insert = s.substring(bb + 1, eb); // set repeated string
end = s.substring(eb + 1); // set remainder of string
s = s.substring(0, bb - nl + 1); // remove everything after the digits
while (n > 0) {
s += insert; // add repeated string n times
n--;
}
s += end; // add remainder of string
bb = s.indexOf('['); // new location of beginning bracket
nbb = s.indexOf('[', bb + 1); // new location of next beginning bracket
eb = s.indexOf(']'); // new location of ending bracket
}
return s;
}
} | class Solution {
public:
string decodeString(string s) {
stack<char> st;
for(int i = 0; i < s.size(); i++){
if(s[i] != ']') {
st.push(s[i]);
}
else{
string curr_str = "";
while(st.top() != '['){
curr_str = st.top() + curr_str ;
st.pop();
}
st.pop(); // for '['
string number = "";
// for calculating number
while(!st.empty() && isdigit(st.top())){
number = st.top() + number;
st.pop();
}
int k_time = stoi(number); // convert string to number
while(k_time--){
for(int p = 0; p < curr_str.size() ; p++)
st.push(curr_str[p]);
}
}
}
s = "";
while(!st.empty()){
s = st.top() + s;
st.pop();
}
return s;
}
}; | var decodeString = function(s) {
const stack = [];
for (let char of s) {
if (char === "]") {
let curr = stack.pop();
let str = '';
while (curr !== '[') {
str = curr+ str;
curr = stack.pop();
}
let num = "";
curr = stack.pop();
while (!isNaN(curr)) {
num = curr + num;
curr = stack.pop();
}
stack.push(curr);
for (let i=0; i<Number(num);i++) {
stack.push(str);
}
}
else stack.push(char);
}
return stack.join('');
}; | Decode String |
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
Example 1:
Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We do not need to change it.
Example 3:
Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix cannot be a zero matrix.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 3
mat[i][j] is either 0 or 1.
| class Solution:
flips = [11, 23, 38, 89, 186, 308, 200, 464, 416]
def minFlips(self, mat: List[List[int]]) -> int:
mask = self.make_mask(mat)
check = self.make_mask([[1 for c in r] for r in mat])
min_steps = -1
last = 0
for x in range(2**9):
x = x & check
flips = last ^ x
last = x
if not flips:
continue
for i in range(len(mat)):
for j in range(len(mat[0])):
index = (i * 3 + j)
if 1 << index & flips:
mask ^= self.flips[index]
if check & ~mask == check:
steps = self.count_bits(x & check)
if min_steps < 0 or steps < min_steps:
min_steps = steps
return min_steps
def make_mask(self, mat):
d = 0
for i in range(3):
for j in range(3):
if i < len(mat) and j < len(mat[0]):
d |= mat[i][j] << (i * 3 + j)
return d
def count_bits(self, x):
count = 0
i = 1
while i <= x:
count += int(bool(x & i))
i <<= 1
return count | class Solution {
public int minFlips(int[][] mat) {
int m = mat.length, n = mat[0].length;
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
int steps = 0;
int initialState = toBinary(mat);
queue.add(initialState);
visited.add(initialState);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int state = queue.poll();
if (state == 0) return steps;
int mask = 1;
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
int nextState = flip(state, x, y, n, m);
if (!visited.contains(nextState)) {
visited.add(nextState);
queue.add(nextState);
}
mask = mask << 1;
}
}
}
steps++;
}
return -1;
}
private int toBinary(int[][] M) {
int bin = 0;
for (int y = 0; y < M.length; y++) {
for (int x = 0; x < M[0].length; x++) {
bin = (bin << 1) + M[y][x];
}
}
return bin;
}
private int flip(int state, int x, int y, int n, int m) {
int flip = 1 << ((y*n) + x);
flip += (x > 0) ? 1 << ((y*n) + (x-1)) : 0;
flip += (x < n-1) ? 1 << ((y*n) + (x+1)) : 0;
flip += (y > 0) ? 1 << (((y-1)*n) + x) : 0;
flip += (y < m-1) ? 1 << (((y+1)*n) + x) : 0;
return state ^ flip;
}
} | class Solution {
public:
bool check(string str) {
for(auto &i: str)
if(i=='1')
return false;
return true;
}
int minFlips(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
string str = "";
for(auto &i: mat) {
for(auto &j: i)
str+=(j+'0');
}
unordered_set<string> st;
queue<pair<string,int>> q;
q.push({str,0});
int steps = 0;
while(q.size()) {
string top = q.front().first;
int step = q.front().second;
if(check(top)) {
return step;
}
q.pop();
steps++;
for(int i=0; i<top.size(); ++i) {
string temp = top;
int x = i/n;
int y = i%n;
temp[i] = !(temp[i] - '0') + '0';
if(x+1<m)
temp[y + (x+1)*n] = !(temp[y + (x+1)*n] - '0') + '0';
if(x-1>=0)
temp[y + (x-1)*n] = !(temp[y + (x-1)*n] - '0') + '0';
if(y+1<n)
temp[(y+1) + (x)*n] = !(temp[(y+1) + (x)*n] - '0') + '0';
if(y-1>=0)
temp[(y-1) + (x)*n] = !(temp[(y-1) + (x)*n] - '0') + '0';
// cout<<i<<" : "<<temp<<" "<<step+1<<endl;
if(st.count(temp)==0) {
q.push({temp,step+1});
st.insert(temp);
}
if(check(temp)) {
return step+1;
}
}
}
return -1;
}
}; | // Helper counts how many ones are in the matrix to start with. O(mn)
var countOnes = function(mat) {
let count = 0;
for (let r = 0; r < mat.length; r++) {
count += mat[r].reduce((a, b) => a + b);
}
return count;
}
// Helper flips a cell and its neighbors. Returns updated number of ones left in matrix. O(1)
var flip = function(mat, r, c, numOnes) {
const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0], [0, 0]];
dirs.forEach(el => {
let newR = r + el[0], newC = c + el[1];
if (newR >= 0 && newR < mat.length && newC >= 0 && newC < mat[0].length) {
if (mat[newR][newC] === 0) {
mat[newR][newC] = 1;
numOnes++;
} else {
mat[newR][newC] = 0;
numOnes--;
}
}
})
return numOnes;
}
// Main function tries every possible combination of cells being flipped using backtracking. O (2^(mn))
var minFlips = function(mat) {
const rows = mat.length, cols = mat[0].length;
let minFlips = Infinity, numOnes = countOnes(mat);
var backtrackFlip = function(cell, flips) {
if (numOnes === 0) minFlips = Math.min(minFlips, flips);
for (let newCell = cell; newCell < rows * cols; newCell++) {
// Function uses a cell number instead of row / col to keep track of column flips
// For example, a 2 x 2 grid has cells "0", "1", "2", "3" and the line below calculates row / col based on that number
const r = Math.floor(newCell / cols), c = newCell % cols;
numOnes = flip(mat, r, c, numOnes);
backtrackFlip(newCell + 1, flips + 1);
numOnes = flip(mat, r, c, numOnes);
}
}
backtrackFlip(0, 0);
return minFlips === Infinity ? -1 : minFlips;
}; | Minimum Number of Flips to Convert Binary Matrix to Zero Matrix |
You are given an m x n integer matrix grid.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)
Example 3:
Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 105
| class Solution:
def getBiggestThree(self, grid: List[List[int]]) -> List[int]:
def calc(l,r,u,d):
sc=0
c1=c2=(l+r)//2
expand=True
for row in range(u,d+1):
if c1==c2:
sc+=grid[row][c1]
else:
sc+=grid[row][c1]+grid[row][c2]
if c1==l:
expand=False
if expand:
c1-=1
c2+=1
else:
c1+=1
c2-=1
return sc
m=len(grid)
n=len(grid[0])
heap=[]
for i in range(m):
for j in range(n):
l=r=j
d=i
while l>=0 and r<=n-1 and d<=m-1:
sc=calc(l,r,i,d)
l-=1
r+=1
d+=2
if len(heap)<3:
if sc not in heap:
heapq.heappush(heap,sc)
else:
if sc not in heap and sc>heap[0]:
heapq.heappop(heap)
heapq.heappush(heap,sc)
heap.sort(reverse=True)
return heap | class Solution {
public int[] getBiggestThree(int[][] grid) {
int end = Math.min(grid.length, grid[0].length);
int maxThree[] = {0,0,0};
for(int length=0; length<end; length++){
searchBigThree(grid, maxThree, length);
}
Arrays.sort(maxThree);
// If there are less than three distinct values, return all of them.
if(maxThree[0] == 0){
if(maxThree[1] == 0){
return new int[]{maxThree[2]};
}
return new int[]{maxThree[2],maxThree[1]};
}
// reverse array
maxThree[0] = maxThree[0]^maxThree[2];
maxThree[2] = maxThree[0]^maxThree[2];
maxThree[0] = maxThree[0]^maxThree[2];
return maxThree;
}
void searchBigThree(int[][] grid, int[] maxThree, int length){
int end = grid.length-(length==0?0: 2*length);
int end1 = grid[0].length-(length);
for(int start = 0; start<end; start++){
for(int start1 = length; start1<end1; start1++){
if(start+start1 >= length){
addToMaxThree(maxThree, getSum(grid, start, start1, length));
}
}
}
}
/*
get sum of edges of rhombus abcd
a
/ \
d b
\ /
c
*/
int getSum(int[][] grid, int i, int j, int length){
if(length == 0){
return grid[i][j];
}
int sum = 0;
// edge ab
for(int it=0; it<=length; it++){
sum = sum + grid[i+it][j+it];
}
// edge ad
for(int it=1; it<=length; it++){
sum = sum + grid[i+it][j-it];
}
// edge dc
for(int it=1; it<=length; it++){
sum = sum + grid[i+length+it][j-length+it];
}
// edge bc
for(int it=1; it<length; it++){
sum = sum + grid[i+length+it][j+length-it];
}
return sum;
}
void addToMaxThree(int[] maxThree, int num){
// Do not add duplicate entry
if(maxThree[0] == num || maxThree[1] == num || maxThree[2] == num ){
return;
}
Arrays.sort(maxThree);
if(maxThree[0] < num){
maxThree[0] = num;
}
}
} | class Solution {
public:
vector<int> getBiggestThree(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
set<int> s;
// 1x1, 3x3, 5x5
for (int len = 1; len <= min(m, n); len += 2) {
for (int i = 0; i + len <= n; i ++) {
for (int j = 0; j + len <= m; j ++) {
int d = len / 2;
if (d == 0) { s.insert(grid[i][j]); }
else {
int x = i, y = j + d;
long long sum = 0;
for (int k = 0; k < d; k ++) sum += grid[x++][y++];
for (int k = 0; k < d; k ++) sum += grid[x++][y--];
for (int k = 0; k < d; k ++) sum += grid[x--][y--];
for (int k = 0; k < d; k ++) sum += grid[x--][y++];
s.insert(sum);
}
}
}
}
if (s.size() < 3)
return vector<int>(s.rbegin(), s.rend());
return vector<int>(s.rbegin(), next(s.rbegin(), 3));
}
}; | var getBiggestThree = function(grid) {
const m = grid.length;
const n = grid[0].length;
const set = new Set();
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
let sum = grid[i][j];
set.add(sum)
let len = 1;
let row = i;
let col = j;
while (withinBound(row + 1, col - 1)) {
++len;
++row;
--col;
traverse(i, j, row, col, sum, len, 0, "botRight");
sum += grid[row][col];
}
}
}
let max1;
let max2;
let max3;
for (const num of set) {
if (max1 == null || num > max1) {
max3 = max2;
max2 = max1;
max1 = num;
}
else if (max2 == null || num > max2) {
max3 = max2;
max2 = num;
}
else if (max3 == null || num > max3) {
max3 = num;
}
}
const res = [];
if (max1) res[0] = max1;
if (max2) res[1] = max2;
if (max3) res[2] = max3;
return res;
function traverse(destRow, destCol, currRow, currCol, totSum, lenSize, currLen, currDir) {
if (currRow === destRow && currCol === destCol) {
set.add(totSum);
return;
}
totSum += grid[currRow][currCol];
++currLen;
if (currDir === "botRight") {
if (currLen < lenSize) {
if (!withinBound(currRow + 1, currCol + 1)) return;
traverse(destRow, destCol, currRow + 1, currCol + 1, totSum, lenSize, currLen, currDir);
}
else if (currLen === lenSize) {
if (!withinBound(currRow - 1, currCol + 1)) return;
traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, 1, "topRight");
}
}
else if (currDir === "topRight") {
if (currLen < lenSize) {
if (!withinBound(currRow - 1, currCol + 1)) return;
traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, currLen, "topRight");
}
else if (currLen === lenSize) {
if (!withinBound(currRow - 1, currCol - 1)) return;
traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, 1, "topLeft");
}
}
else if (currDir === "topLeft") {
if (!withinBound(currRow - 1, currCol - 1)) return;
traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, currLen, "topLeft");
}
}
function withinBound(row, col) {
return row >= 0 && col >= 0 && row < m && col < n;
}
}; | Get Biggest Three Rhombus Sums in a Grid |
You are given two positive integer arrays nums1 and nums2, both of length n.
The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.
|x| is defined as:
x if x >= 0, or
-x if x < 0.
Example 1:
Input: nums1 = [1,7,5], nums2 = [2,3,5]
Output: 3
Explanation: There are two possible optimal solutions:
- Replace the second element with the first: [1,7,5] => [1,1,5], or
- Replace the second element with the third: [1,7,5] => [1,5,5].
Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
Example 2:
Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
Output: 0
Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
Example 3:
Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
Output: 20
Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105
| class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
diff = []
sum = 0
for i in range(n):
temp = abs(nums1[i]-nums2[i])
diff.append(temp)
sum += temp
nums1.sort()
best_diff = []
for i in range(n):
idx = bisect.bisect_left(nums1, nums2[i])
if idx != 0 and idx != n:
best_diff.append(
min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))
elif idx == 0:
best_diff.append(abs(nums2[i]-nums1[idx]))
else:
best_diff.append(abs(nums2[i]-nums1[idx-1]))
saved = 0
for i in range(n):
saved = max(saved, diff[i]-best_diff[i])
return (sum-saved) % ((10**9)+(7)) | class Solution {
public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {
int mod = (int)1e9+7;
// Sorted copy of nums1 to use for binary search
int[] snums1 = nums1.clone();
Arrays.sort(snums1);
int maxDiff = 0; // maximum difference between original and new absolute diff
int pos = 0; // where the maximum difference occurs
int newn1 = 0; // nums1 value to copy to nums1[pos]
// For each array position i from 0 to n-1, find up to two elements
// in nums1 that are closest to nums2[i] (one on each side of nums2[i]).
// Calculate a new absolute difference for each of these elements.
for (int i=0; i<nums2.length; i++) {
int n2 = nums2[i];
int origDiff = Math.abs(nums1[i] - n2);
// Find the largest element in nums1 that is less than or equal to
// the current element in nums2, if such an element exists.
int floor = arrayFloor(snums1, n2);
if (floor > Integer.MIN_VALUE) {
// If a valid element exists, calculate a new absolute difference
// at the current position, and calculate how much smaller this is
// than the current absolute difference. If the result is better
// than what we have seen so far, update the maximum difference and
// save the data for the current position.
int newDiff = Math.abs(floor - n2);
int diff = origDiff - newDiff;
if (diff > maxDiff) {
pos = i;
newn1 = floor;
maxDiff = diff;
}
}
// Find the smallest element in nums1 that is greater than or equal to
// the current element in nums2, if such an element exists.
int ceiling = arrayCeiling(snums1, n2);
if (ceiling < Integer.MAX_VALUE) {
// Same as above
int newDiff = Math.abs(ceiling - n2);
int diff = origDiff - newDiff;
if (diff > maxDiff) {
pos = i;
newn1 = ceiling;
maxDiff = diff;
}
}
}
// If we found a replacement value, overwrite the original value.
if (newn1 > 0) {
nums1[pos] = newn1;
}
// Calculate the absolute sum difference with the replaced value.
int sum = 0;
for (int i=0; i<nums1.length; i++) {
sum = (sum + Math.abs(nums1[i] - nums2[i])) % mod;
}
return sum;
}
//
// Array versions of TreeSet.floor and TreeSet.ceiling
//
// Greatest element less than or equal to val
private int arrayFloor(int[] arr, int val) {
int lo = 0;
int hi = arr.length-1;
int max = Integer.MIN_VALUE;
while (lo <= hi) {
int mid = lo+(hi-lo)/2;
if (arr[mid] <= val) {
max = arr[mid];
lo = mid+1;
} else {
hi = mid-1;
}
}
return max;
}
// Smallest element greater than or equal to val
private int arrayCeiling(int[] arr, int val) {
int lo = 0;
int hi = arr.length-1;
int min = Integer.MAX_VALUE;
while (lo <= hi) {
int mid = lo+(hi-lo)/2;
if (arr[mid] >= val) {
min = arr[mid];
hi = mid-1;
} else {
lo = mid+1;
}
}
return min;
}
} | class Solution {
public:
int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
long sum=0, minSum;
vector<int> nums=nums1;
int n=nums.size();
// Calculate the current sum of differences.
for(int i=0;i<n;i++) sum+=abs(nums1[i]-nums2[i]);
sort(nums.begin(), nums.end());
minSum=sum;
for(int i=0;i<n;i++) {
int dist=abs(nums1[i]-nums2[i]);
int l=0, h=n-1;
// Find the number closest to nums2[i].
// The closer the element, the smaller the difference.
while(l<h) {
int m=l+(h-l)/2;
if(nums[m]>nums2[i]) {
h=m;
} else {
l=m+1;
}
dist=min(dist, abs(nums2[i]-nums[m]));
}
dist=min(dist, abs(nums2[i]-nums[l]));
minSum = min(minSum, sum - abs(nums1[i]-nums2[i]) + dist);
}
return minSum % 1000000007;
}
}; | var minAbsoluteSumDiff = function(nums1, nums2) {
const MOD = 1e9 + 7;
const n = nums1.length;
const origDiffs = [];
let diffSum = 0;
for (let i = 0; i < n; i++) {
const num1 = nums1[i];
const num2 = nums2[i];
const currDiff = Math.abs(num1 - num2);
origDiffs[i] = currDiff;
diffSum += currDiff;
}
nums1.sort((a, b) => a - b);
let minDiffSum = diffSum;
for (let i = 0; i < n; i++) {
const origDiff = origDiffs[i];
const num2 = nums2[i];
let left = 0;
let right = n - 1;
let bestDiff = origDiff;
while (left <= right) {
const mid = (left + right) >> 1;
const num1 = nums1[mid];
const candDiff = num1 - num2;
if (Math.abs(candDiff) < bestDiff) {
bestDiff = Math.abs(candDiff);
if (bestDiff === 0) break;
}
if (candDiff < 0) left = mid + 1;
else right = mid - 1;
}
const replacedDiffSum = (diffSum - origDiff) + bestDiff;
minDiffSum = Math.min(minDiffSum, replacedDiffSum);
}
return minDiffSum % MOD;
}; | Minimum Absolute Sum Difference |
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
Example 3:
Input: n = 3, k = 1
Output: "123"
Constraints:
1 <= n <= 9
1 <= k <= n!
| class Solution:
def nextPermutation(self, nums: List[int]):
n = len(nums)
high = n-1
low = -1
for i in range(n-1, 0, -1):
if nums[i] > nums[i-1]:
low = i-1
break
if low == -1:
nums[low+1:] = reversed(nums[low+1:])
return
for i in range(n-1, low, -1):
if nums[low] < nums[i]:
nums[low], nums[i] = nums[i], nums[low]
break
nums[low+1:] = reversed(nums[low+1:])
return nums
def getPermutation(self, n: int, k: int) -> str:
s = ["1","2","3","4","5","6","7","8","9"]
s = s[:n]
if k==1:
return ''.join(s)
dic = {1:1,2:2,3:6,4:24,5:120,6:720,7:5040,8:40320,9:362880}
if k==dic[n]:
return ''.join(s)[::-1]
x = 0
while k>dic[n-1]:
k -= dic[n-1]
x += 1
y=[]
y.append(s[x])
for i in range(n):
if i==x:
continue
y.append(s[i])
while k!=1:
self.nextPermutation(y)
k-= 1
y = ''.join(y)
return y | class Solution {
public String getPermutation(int n, int k) {
int fact = 1;
List<Integer> nums = new ArrayList<>();
for(int i = 1; i<n; i++){
fact = fact * i;
nums.add(i);
}
nums.add(n); // Add last permutation number.
String res = "";
k = k - 1; // We use 0 indexing.
while(true){
res = res + nums.get(k / fact);
nums.remove(k / fact);
if(nums.size() == 0) break;
k = k % fact;
fact = fact / nums.size();
}
return res;
}
} | class Solution {
public:
string getPermutation(int n, int k) {
int fact=1;
vector<int> numbers;
for(int i=1;i<n;i++){
fact=fact*i;
numbers.push_back(i);
}
numbers.push_back(n);
string ans="";
k=k-1;
while(true){
ans=ans+to_string(numbers[k/fact]);
numbers.erase(numbers.begin()+(k/fact));
if(numbers.size()==0) break;
k=k%fact;
fact=fact/numbers.size();
}
return ans;
}
}; | const dfs = (path, visited, result, numbers, limit) => {
// return if we already reached the permutation needed
if(result.length === limit) {
return;
}
// commit the result
if(path.length === numbers.length) {
result.push(path.join(''))
return;
}
// easier to reason and less prone to miss the -1 offset of normal for loop
for(const [index, number] of numbers.entries()) {
if(visited[index]) continue;
path.push(number);
visited[index] = true;
dfs(path, visited, result, numbers);
path.pop();
visited[index] = false;
}
}
var getPermutation = function(n, k) {
const numbers = Array.from({length: n}, (_, i) => i + 1);
let visitedNumbers = Array.from(numbers, () => false);
let result = [];
dfs([], visitedNumbers, result, numbers, k);
return result[k - 1];
}; | Permutation Sequence |
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Constraints:
The number of nodes in head is in the range [0, 2 * 104].
-105 <= Node.val <= 105
| class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
arr = []
while head:
arr.append(head.val)
head = head.next
def dfs(left, right):
if left > right: return
m = (left + right)//2
return TreeNode(arr[m], dfs(left, m-1), dfs(m+1, right))
return dfs(0, len(arr)-1) | class Solution {
public TreeNode sortedListToBST(ListNode head) {
ListNode tmp = head;
ArrayList<Integer> treelist = new ArrayList<>();
while(tmp != null) {
treelist.add(tmp.val);
tmp = tmp.next;
}
return createTree(treelist, 0, treelist.size()-1);
}
public TreeNode createTree(ArrayList<Integer> treelist, int start, int end) {
if(start > end)
return null;
int mid = start + (end-start)/2;
TreeNode node = new TreeNode(treelist.get(mid));//getNode(treelist.get(mid));
node.left = createTree(treelist, start, mid-1);
node.right = createTree(treelist, mid+1, end);
return node;
}
} | class Solution {
public:
typedef vector<int>::iterator vecIt;
TreeNode* buildTree(vector<int>& listToVec, vecIt start, vecIt end)
{
if (start >= end)
return NULL;
vecIt midIt = start + (end - start) / 2;
TreeNode* newNode = new TreeNode(*midIt);
newNode->left = buildTree(listToVec, start, midIt);
newNode->right = buildTree(listToVec, midIt + 1, end);
return (newNode);
}
TreeNode* sortedListToBST(ListNode* head) {
vector<int> listToVec;
while (head)
{
listToVec.push_back(head->val);
head = head->next;
}
return (buildTree(listToVec, listToVec.begin(), listToVec.end()));
}
}; | var sortedListToBST = function(head) {
if(!head) return null;
if(!head.next) return new TreeNode(head.val);
let fast = head, slow = head, prev = head;
while(fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
const root = new TreeNode(slow.val);
prev.next = null;
const newHead = slow.next;
slow.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(newHead);
return root;
}; | Convert Sorted List to Binary Search Tree |
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)). | class Solution:
def minSubArrayLen(self, target, nums):
# Init left pointer and answer
l, ans = 0, len(nums) + 1
# Init sum of subarray
s = 0
# Iterate through all numbers as right subarray
for r in range(len(nums)):
# Add right number to sum
s += nums[r]
# Check for subarray greater than or equal to target
while s >= target:
# Calculate new min
ans = min(ans, r - l + 1)
# Remove current left nubmer from sum
s -= nums[l]
# Move left index up one
l += 1
# No solution
if ans == len(nums) + 1:
return 0
# Solution
return ans | class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int n = nums.length;
int sum = 0;
int minCount = Integer.MAX_VALUE;
for(int i = 0;i<n;i++){
sum += nums[i];
while(sum >= target){
minCount = Math.min(minCount, i-left+1);
sum -= nums[left++];
}
}
return minCount == Integer.MAX_VALUE?0:minCount;
}
} | class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int m=INT_MAX,s=0,l=0;
for(int i=0;i<nums.size();i++)
{
s+=nums[i];
if(s>=target)
m=min(m,i-l+1);
while(s>=target)
{
m=min(m,i-l+1);
s-=nums[l++];
}
}
if(m==INT_MAX)
m=0;
return m;
}
}; | /**
* @param {number} target
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function(target, nums) {
let indexStartPosition = 0;
let sum = 0;
let tempcounter = 0;
let counter = Infinity;
for(var indexI=0; indexI<nums.length; indexI++){
sum = sum + nums[indexI];
tempcounter++;
while(sum >= target) {
sum = sum - nums[indexStartPosition];
indexStartPosition = indexStartPosition + 1;
counter = Math.min(counter, tempcounter);
tempcounter--;
}
}
return counter === Infinity ? 0 : counter;
}; | Minimum Size Subarray Sum |
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Example 1:
Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
Example 2:
Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length.
One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
Example 3:
Input: nums = [1,2,3,4,5,6,7,8,9]
Output: 2
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
Follow up: Could you solve this in O(n) time?
| #####################################################################################################################
# Problem: Wiggle Subsequence
# Solution : Dynamic Programming
# Time Complexity : O(n)
# Space Complexity : O(1)
#####################################################################################################################
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
positive, negative = 1, 1
if len(nums) < 2:
return len(nums)
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
positive = negative + 1
elif nums[i] < nums[i - 1]:
negative = positive + 1
return max(positive, negative) | class Solution {
int n;
int dp[][][];
public int wiggleMaxLength(int[] nums) {
n = nums.length;
dp = new int[n][1005][2];
for(int i = 0; i < n; i++){
for(int j = 0; j < 1005; j++){
Arrays.fill(dp[i][j] , -1);
}
}
int pos = f(0 , 0 , nums , -1);
for(int i = 0; i < n; i++){
for(int j = 0; j < 1005; j++){
Arrays.fill(dp[i][j] , -1);
}
}
int neg = f(0 , 1 , nums , 1001);
return Math.max(pos , neg);
}
int f(int i , int posPre , int a[] , int prev){
if(i == n) return 0;
if(dp[i][prev + 1][posPre] != -1) return dp[i][prev + 1][posPre];
if(posPre == 0){
int not = f(i + 1 , 0 , a , prev);
int take = 0;
if(a[i] - prev > 0){
take = f(i + 1 , 1 , a , a[i]) + 1;
}
return dp[i][prev + 1][posPre] = Math.max(not , take);
}
else{
int not = f(i + 1 , 1 , a , prev);
int take = 0;
if(a[i] - prev < 0){
take = f(i + 1 , 0 , a , a[i]) + 1;
}
return dp[i][prev + 1][posPre] = Math.max(not , take);
}
}
} | class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
vector<vector<int>> dp(2, vector<int>(nums.size(),0));
int ans = 1, high, low;
dp[0][0] = dp[1][0] = 1;
for(int i=1; i<nums.size(); ++i){
high = low = 0;
for(int j=0; j<i; ++j){
if(nums[i]>nums[j]) low = max(low, dp[1][j]);
else if(nums[i]<nums[j]) high = max(high, dp[0][j]);
}
dp[0][i] = low + 1;
dp[1][i] = high + 1;
ans = max({ans, dp[0][i], dp[1][i]});
}
return ans;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var wiggleMaxLength = function(nums) {
//two pass
//assume we start with positive or start with negative
//choose the longest of the two
return Math.max(helper(nums,true),helper(nums,false))
};
const helper = (nums, start) =>{
let l = 0
let r = 1
let res = nums.length
let sign = start
while(r < nums.length){
//if sign are what we expected, just flip the sign
if((sign && nums[r] > nums[l]) || (!sign && nums[r] < nums[l])){
sign = !sign
}
//if sign aren't what we expected then we "remove" one
//if we want positive then we remove the bigger number to give us a better chance of getting positive
//if we want negative we remove the smaller number go give us a chance of getting a negative
// want negative but nums[r] - nums[l] = positive => remove nums[l]
// want positive but nums[r] - nums[l] = negative => remove nums[l]
//it just so happens that the number we want to remove will always be nums[l], so we don't have to do anything special
else{
res--
}
l++
r++
}
return res
} | Wiggle Subsequence |
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
Example 1:
Input: nums = [2,1,2]
Output: 5
Example 2:
Input: nums = [1,2,1]
Output: 0
Constraints:
3 <= nums.length <= 104
1 <= nums[i] <= 106
| class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums=sorted(nums,reverse=True)
l=len(nums)
for i in range(l-2):
if nums[i]<nums[i+1]+nums[i+2]: #condition if triangle can be formed
return nums[i]+nums[i+1]+nums[i+2]
return 0 | class Solution {
public int largestPerimeter(int[] nums) {
Arrays.sort(nums);
for(int i = nums.length - 3; i >= 0; i--) {
if(nums[i] + nums[i + 1] > nums[i + 2])
return nums[i] + nums[i + 1] + nums[i + 2];
}
return 0;
}
} | class Solution {
public:
int largestPerimeter(vector<int>& nums) {
// sort the elements
sort(nums.begin(),nums.end());
// iterate in everse order to get maximum perimeter
for (int i=nums.size()-2; i>=1 ; i--){
//Triangle is formed if sum of two sides is greater than third side
if (nums[i]+nums[i-1] >nums[i+1])return (nums[i]+nums[i+1]+nums[i-1]); // return perimeter which is sum of three sides
}
return 0; // when no triangle possible it will come out of loop so return 0 here
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var largestPerimeter = function(nums) {
const sorted=nums.sort((a,b)=>a-b);
const result=[];
for(let i=0;i<sorted.length;i++){
if((sorted[i]+sorted[i+1]>sorted[i+2])&&(sorted[i+2]+sorted[i+1]>sorted[i])&&(sorted[i]+sorted[i+2]>sorted[i+1])){
result.push(sorted[i]+sorted[i+1]+sorted[i+2]);
}
}
if(result.length!==0){
return Math.max(...result);
}else{
return 0;
}
}; | Largest Perimeter Triangle |
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
Example 1:
Input: s = "aaabbb"
Output: true
Explanation:
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears before every 'b' and we return true.
Example 2:
Input: s = "abab"
Output: false
Explanation:
There is an 'a' at index 2 and a 'b' at index 1.
Hence, not every 'a' appears before every 'b' and we return false.
Example 3:
Input: s = "bbb"
Output: true
Explanation:
There are no 'a's, hence, every 'a' appears before every 'b' and we return true.
Constraints:
1 <= s.length <= 100
s[i] is either 'a' or 'b'.
| class Solution:
def checkString(self, s: str) -> bool:
if "ba" in s:
return False
else:
return True | class Solution {
public boolean checkString(String s) {
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'b'){
for(int j = i+1; j < s.length(); j++){
if(s.charAt(j) == 'a'){
return false;
}
}
}
}
return true;
}
} | class Solution {
public:
bool checkString(string s) {
for(int i = 1; i < s.size(); i++){
if(s[i - 1] == 'b' && s[i] == 'a'){
return false;
}
}
return true;
}
}; | var checkString = function(s) {
// a cannot come after b
let violation = "ba";
return s.indexOf(violation, 0) == -1;
}; | Check if All A's Appears Before All B's |
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def valid(node,left,right):
if not node: # checking node is none
return True
if not (node.val>left and node.val<right): # checking the left value is less than node and right value is greater than node
return False
return (valid(node.left,left,node.val) and valid(node.right,node.val,right)) # recursively calling left child and right child and returing the result True if both are true else False
return valid(root,float("-inf"),float("inf")) #calling recursive function to check | class Solution {
public boolean isValidBST(TreeNode root) {
return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public boolean dfs(TreeNode root, int min, int max) {
if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) || (root.val == Integer.MAX_VALUE && root.right != null)) return false;
boolean leftRight = true;
if (root.left == null && root.right == null) return true;
if (root.left != null) {
leftRight = dfs(root.left, min, root.val - 1);
}
if (root.right != null) {
leftRight = dfs(root.right, root.val + 1, max) && leftRight;
}
return leftRight;
}
} | // We know inorder traversal of BST is always sorted, so we are just finding inorder traversal and check whether it is in sorted manner or not, but only using const space using prev pointer.
class Solution {
public:
TreeNode* prev;
Solution(){
prev = NULL;
}
bool isValidBST(TreeNode* root) {
if (root == NULL)
return true;
bool a = isValidBST(root->left);
if (!a)
return false;
if (prev != NULL)
{
if (prev->val >= root->val)
return false;
}
prev = root;
return isValidBST(root->right);
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
const nodesToCheck = [{node: root, lowerLimit: -Infinity, upperLimit: Infinity}]
while (nodesToCheck.length > 0) {
const {node: currentNode, lowerLimit, upperLimit} = nodesToCheck.pop()
if (currentNode.val <= lowerLimit || currentNode.val >= upperLimit) {
return false
}
if (currentNode.left) {
nodesToCheck.push({
node: currentNode.left,
lowerLimit,
upperLimit: currentNode.val
})
}
if (currentNode.right) {
nodesToCheck.push({
node: currentNode.right,
lowerLimit: currentNode.val,
upperLimit
})
}
}
return true
}; | Validate Binary Search Tree |
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
Constraints:
1 <= s.length <= 3 * 105
s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
s represents a valid expression.
All the integers in the expression are non-negative integers in the range [0, 231 - 1].
The answer is guaranteed to fit in a 32-bit integer.
| class Solution:
def calculate(self, s: str) -> int:
stack = []
currentNumber = 0
operator = '+'
operations = '+-/*'
for i in range(len(s)):
ch = s[i]
if ch.isdigit():
currentNumber = currentNumber * 10 + int(ch)
if ch in operations or i == len(s) - 1:
if operator == '+':
stack.append(currentNumber)
elif operator == '-':
stack.append(-currentNumber)
elif operator == '*':
stack.append(stack.pop() * currentNumber)
elif operator == '/':
stack.append(int(stack.pop()/currentNumber))
currentNumber =0
operator = ch
return sum(stack) | class Solution {
public int calculate(String s) {
if(s==null ||s.length()==0)return 0;
Stack<Integer> st = new Stack<>();
int curr=0;
char op = '+';
char [] ch = s.toCharArray();
for(int i=0;i<s.length();i++){
if(Character.isDigit(ch[i])){
curr= curr*10+ch[i]-'0';
}
if(!Character.isDigit(ch[i])&& ch[i]!=' ' || i==ch.length-1){
if(op=='+'){
st.push(curr);
}else if(op=='-'){
st.push(-curr);
}else if(op=='*'){
st.push(st.pop()*curr);
}else if(op=='/'){
st.push(st.pop()/curr);
}
op=ch[i];
curr=0;
}
}
int sum=0;
while(!st.isEmpty()){
sum+=st.pop();
}
return sum;
}
} //TC=o(n),SC=o(n) | class Solution {
public:
int calculate(string s) {
stack<int> nums;
stack<char> ops;
int n = 0;
for(int i = 0; i < s.size(); ++i){
if(s[i] >= '0' && s[i] <= '9'){
string t(1, s[i]);
n = n*10 + stoi(t);
}else if( s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
nums.push(n);
n = 0;
if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){
int n2 = nums.top(); nums.pop();
int n1 = nums.top(); nums.pop();
if(ops.top() == '*') nums.push(n1*n2);
else nums.push(n1/n2);
ops.pop();
}
ops.push(s[i]);
}
}
nums.push(n);
if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){
int n2 = nums.top(); nums.pop();
int n1 = nums.top(); nums.pop();
if(ops.top() == '*') nums.push(n1*n2);
else nums.push(n1/n2);
ops.pop();
}
stack<int> tnums;
stack<char> tops;
while(!nums.empty()){ tnums.push(nums.top()); nums.pop();}
while(!ops.empty()) { tops.push(ops.top()); ops.pop(); }
while(!tops.empty()){ //cout<<tops.top()<<" " ;
int n1 = tnums.top(); tnums.pop();
int n2 = tnums.top(); tnums.pop();
if(tops.top() == '+') tnums.push(n1 + n2);
else tnums.push(n1 - n2);
tops.pop();
}
return tnums.top();
}
}; | /**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
const n = s.length;
let currNum = 0, lastNum = 0, res = 0;
let op = '+';
for (let i = 0; i < n; i++) {
let currChar = s[i];
if (currChar !== " " && !isNaN(Number(currChar))) {
currNum = currNum * 10 + Number(currChar);
}
if (isNaN(Number(currChar)) && currChar !== " " || i === n - 1) {
if (op === '+' || op === '-') {
res += lastNum;
lastNum = (op === '+' ? currNum : -currNum);
} else if (op === '*') {
lastNum *= currNum;
} else if (op === '/') {
lastNum = Math.floor(Math.abs(lastNum) / currNum) * (lastNum < 0 ? -1 : 1);
}
op = currChar;
currNum = 0;
}
}
res += lastNum;
return res;
}; | Basic Calculator II |
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The height of the n-ary tree is less than or equal to 1000.
Follow up: Recursive solution is trivial, could you do it iteratively?
| function preorder(root: Node | null): number[] {
const res: number[] = [];
const getNodeVal = (node: Node | null): void => {
if (node) {
res.push(node.val);
for (let i = 0; i < node.children.length; i++) {
getNodeVal(node.children[i]);
}
}
};
getNodeVal(root);
return res;
} | class Solution {
public List<Integer> preorder(Node root) {
if (root == null) return new ArrayList<Integer>();
Stack<Node> stk = new Stack<Node>();
ArrayList<Integer> arr = new ArrayList<Integer>();
stk.push(root);
Node ref;
while(!stk.empty()) {
ref = stk.pop();
// System.out.println(ref.val);
arr.add(ref.val);
for(int i=ref.children.size() - 1;i>=0;i--) {
stk.push(ref.children.get(i));
}
}
return arr;
}
} | class Solution {
public:
vector<int> preorder(Node* root) {
vector<int>ans;
stack<Node*>st;
st.push(root);
while(!st.empty()){
auto frnt=st.top();
st.pop();
ans.push_back(frnt->val);
for(int i=frnt->children.size()-1;i>=0;i--){
st.push(frnt->children[i]);
}
}
return ans;
}
}; | var preorder = function(root) {
return [root.val].concat(root.children.map( (c)=>c ? preorder(c) : [] ).flat() );
}; | N-ary Tree Preorder Traversal |
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
Return a list of all MHTs' root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
Constraints:
1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
All the pairs (ai, bi) are distinct.
The given input is guaranteed to be a tree and there will be no repeated edges.
| class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n==0:
return []
if n==1:return [0]
adj=[[] for i in range (n)]
degree=[0]*n
for i in edges:
adj[i[0]].append(i[1])
adj[i[1]].append(i[0])
degree[i[0]]+=1
degree[i[1]]+=1
print(adj)
q=[]
for i in range(n):
if degree[i]==1:
q.append(i)
while n>2:
size=len(q)
n-=size
while size>0:
v=q.pop(0)
for i in adj[v]:
degree[i]-=1
if degree[i]==1:
q.append(i)
size-=1
return q
| class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if(edges.length == 0) {
List<Integer> al = new ArrayList<>();
al.add(0);
return al;
}
HashMap<Integer, Set<Integer>> map = new HashMap<>(); // map == graph
int [] degree = new int[n];
for(int [] edge : edges){
int src = edge[0];
int dest = edge[1];
map.putIfAbsent(src, new HashSet<>());
map.get(src).add(dest);
map.putIfAbsent(dest, new HashSet<>());
map.get(dest).add(src);
degree[src]++;
degree[dest]++;
}
Queue<Integer> q = new ArrayDeque<>();
for(int i = 0; i < degree.length; i++){
if(degree[i] == 1){
q.offer(i);
}
}
int count = n;
while(count > 2){
int size = q.size();
count -= size;
while(size-- > 0){
Integer src = q.poll();
for(Integer connection : map.get(src)){
degree[connection]--;
if(degree[connection] == 1){
q.offer(connection);
}
}
}
}
return new ArrayList<>(q);
}
} | class Solution {
public:
int getheight(vector<int> a[],int sv,int n)
{
int lvl = 0;
vector<int> vis(n,0);
queue<int> q;
q.push(sv);
vis[sv] = 0;
while(q.size())
{
int sz = q.size();
lvl++;
while(sz--)
{
int curr = q.front();
q.pop();
vis[curr] = 1;
for(auto it:a[curr])
{
if(vis[it]==0)
{
q.push(it);
}
}
}
}
return lvl;
}
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
vector<int> a[n];
vector<int> indegree(n,0);
for(auto it:edges)
{
a[it[0]].push_back(it[1]);
a[it[1]].push_back(it[0]);
indegree[it[0]]++;
indegree[it[1]]++;
}
//cutting leafs whose indegree is 1
queue<int> q;
vector<int> ans;
for(int i = 0;i<n;i++)
{
if(indegree[i]==1)
{
q.push(i);
indegree[i]--;
}
}
while(q.size())
{
int sz=q.size();
ans.clear();
while(sz--)
{
int curr = q.front();
q.pop();
ans.push_back(curr);
for(auto it:a[curr])
{
indegree[it]--;
if(indegree[it]==1)
q.push(it);
}
}
}
if(n==1)return {0};
return ans;
//brute force gives tle
// int mn = INT_MAX;
// unordered_map<int,vector<int>> mp;
// for(int i = 0;i<n;i++)
// {
// int x = getheight(a,i,n);
// mp[x].push_back(i);
// // cout<<i<<" "<<x<<endl;
// mn = min(mn,x);
// }
// return mp[mn];
}
}; | var findMinHeightTrees = function(n, edges) {
//edge case
if(n <=0) return [];
if(n === 1) return [0]
let graph ={}
let indegree = Array(n).fill(0)
let leaves = []
// build graph
for(let [v,e] of edges){
//as this is undirected graph we will build indegree for both e and v
if(!(v in graph)) graph[v] = [];
if(!(e in graph)) graph[e] = [];
graph[v].push(e)
graph[e].push(v)
indegree[v]++
indegree[e]++
}
// get all nodes with indegree 1
for(let i =0; i<indegree.length; i++){
if(indegree[i] === 1) leaves.push(i)
}
let total = n;
while(total > 2){
let size = leaves.length
// as we are removing nodes from our total
total -= size;
for(let i =0 ; i<size; i++){
let vertex = leaves.shift()
for(let edge of graph[vertex] ){
indegree[edge]--
if(indegree[edge] === 1) leaves.push(edge)
}
}
}
return leaves;
}; | Minimum Height Trees |
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.
It is guaranteed that there will be a rectangle with a sum no larger than k.
Example 1:
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
Example 2:
Input: matrix = [[2,2,-1]], k = 3
Output: 3
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-100 <= matrix[i][j] <= 100
-105 <= k <= 105
Follow up: What if the number of rows is much larger than the number of columns?
| class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
import numpy as np
matrix = np.array(matrix, dtype=np.int32)
M,N = matrix.shape
ret = float("-inf")
CUM = np.zeros((M,N), dtype=np.int32)
for shift_r in range(M):
CUM[:M-shift_r] += matrix[shift_r:]
_CUM = np.zeros((M-shift_r,N), dtype=np.int32)
for shift_c in range(N):
_CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]
tmp = _CUM[(_CUM<=k) & (_CUM>ret)]
if tmp.size:
ret = tmp.max()
if ret == k:
return ret
return ret
''' | class Solution {
public int maxSumSubmatrix(int[][] matrix, int tar) {
int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar;
for(i=0;i<n;i++){
for(j=0;j<m;j++){
dp[i][j]=matrix[i][j];
if(j>0) dp[i][j]+=dp[i][j-1];
}
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(i>0) dp[i][j]+=dp[i-1][j];
}
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
for(k=i;k<n;k++){
for(l=j;l<m;l++){
val=dp[k][l];
if((i-1)>=0 && (j-1)>=0) val += dp[i-1][j-1];
if((i-1)>=0) val=val-dp[i-1][l];
if((j-1)>=0) val=val-dp[k][j-1];
if(val>max && val<=target) max=val;
}
}
}
}
return max;
}
} | class Solution {
public:
// function for finding maximum subarray having sum less than k
int find_max(vector<int>& arr, int k)
{
int n = arr.size();
int maxi = INT_MIN;
// curr_sum will store cumulative sum
int curr_sum = 0;
// set will store the prefix sum of array
set<int> s;
// put 0 into set, if curr_sum == k, (curr_sum - k) will be zero
s.insert(0);
for(int i = 0; i < n; i++)
{
// calculate cumulative sum
curr_sum += arr[i];
// find the prefix sum in set having sum == curr_sum - k
auto it = s.lower_bound(curr_sum - k);
// if prefix sum is present, update the maxi
if(it != s.end())
{
maxi = max(maxi, curr_sum - *it);
}
// insert prefix sum into set
s.insert(curr_sum);
}
return maxi;
}
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int m = matrix[0].size();
int maxi = INT_MIN;
// fix the position two two rows and take cumulative sum of columns between two fixed rows
for(int start_row = 0; start_row < n; start_row++)
{
vector<int> col_array(m, 0);
for(int end_row = start_row; end_row < n; end_row++)
{
// take cumulative sum of columns between two fixed rows
for(int col = 0; col < m; col++)
{
col_array[col] += matrix[end_row][col];
}
// find maximum subarray having sum less than equal to k
int curr_max = find_max(col_array, k);
// update the maximum sum
maxi = max(maxi, curr_max);
}
}
return maxi;
}
}; | /**
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
var maxSumSubmatrix = function(matrix, k) {
if (!matrix.length) return 0;
let n = matrix.length, m = matrix[0].length;
let sum = new Array(n + 1).fill(0).map(a => new Array(m + 1).fill(0));
let ans = -Infinity;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
for(let x = 1; x <= i; ++x) {
for(let y = 1; y <= j; ++y) {
let s = rangeSum(sum, x, y, i, j);
if (s <= k) {
ans = Math.max(s, ans);
}
}
}
}
}
return ans;
}
const rangeSum = (sum, x1, y1, x2, y2) => {
return sum[x2][y2] - sum[x1-1][y2] - sum[x2][y1-1] + sum[x1-1][y1-1];
} | Max Sum of Rectangle No Larger Than K |
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
Type-1: Remove the character at the start of the string s and append it to the end of the string.
Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
The string is called alternating if no two adjacent characters are equal.
For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Example 1:
Input: s = "111000"
Output: 2
Explanation: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating.
Example 3:
Input: s = "1110"
Output: 1
Explanation: Use the second operation on the second element to make s = "1010".
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'.
| class Solution:
def minFlips(self, s: str) -> int:
prev = 0
start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize
odd = len(s)%2
for val in s:
val = int(val)
if val == prev:
if odd:
start_0_odd = min(start_0_odd, start_1)
start_1_odd += 1
start_1 += 1
else:
if odd:
start_1_odd = min(start_1_odd, start_0)
start_0_odd += 1
start_0 += 1
prev = 1 - prev
return min([start_1, start_0, start_1_odd, start_0_odd]) | class Solution {
public int minFlips(String s) {
/*
* Sliding Window Approach
*/
int n = s.length();
int mininumFlip = Integer.MAX_VALUE;
int misMatchCount = 0;
for(int i = 0; i < (2 * n); i++){
int r = i % n;
//add mis watch count in current window
if((s.charAt(r) - '0') != (i % 2 == 0 ? 1 : 0)) misMatchCount++;
//remove mismatch count which are not relvent for current window
if(i >= n && (s.charAt(r) - '0') != (r % 2 == 0 ? 1 : 0)) misMatchCount--;
//misMatchCount : when valid binary string start from 1
//n - misMatchCount : when valid binary string start from 0
if(i >= n - 1) mininumFlip = Math.min(mininumFlip, Math.min(misMatchCount, n - misMatchCount));
}
return mininumFlip;
}
} | class Solution {
public:
int minFlips(string s)
{
int n = s.size();
string ss = s+s;
string s1, s2;
int ans = INT_MAX;
for(int i=0; i<ss.size(); i++)
{
s1+=(i%2?'1':'0');
s2+=(i%2?'0':'1');
}
int ans1 = 0, ans2 = 0;
for(int i=0; i<ss.size(); i++)
{
if(s1[i]!=ss[i]) ans1++;
if(s2[i]!=ss[i]) ans2++;
if(i>=n-1)
{
if(i!=n-1 && s1[i-n]!=ss[i-n]) ans1--;
if(i!=n-1 && s2[i-n]!=ss[i-n]) ans2--;
ans = min({ans,ans1,ans2});
}
}
return ans;
}
}; | /**
* @param {string} s
* @return {number}
*/
var minFlips = function(s) {
let length = s.length-1
let flipMap = {
'1': '0',
'0': '1'
}
s = s + s
let alt1 = '1'
let alt2 = '0'
let left = 0
let right = 0
let diff1 = 0
let diff2 = 0
let min = Infinity
while (right < s.length) {
if (right > 0) {
alt1 = flipMap[alt1]
alt2 = flipMap[alt2]
}
let current = s[right]
if (current !== alt1) diff1++
if (current !== alt2) diff2++
if (right-left === length) {
min = Math.min(diff1, diff2, min)
if ((length+1)%2 === 0) {
if (s[left] !== flipMap[alt1]) diff1--
if (s[left] !== flipMap[alt2]) diff2--
} else {
if (s[left] !== alt1) diff1--
if (s[left] !== alt2) diff2--
}
left++
}
right++
}
return min
}; | Minimum Number of Flips to Make the Binary String Alternating |
You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.
Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
Constraints:
n == nums.length
1 <= nums.length <= 1000
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2
| from itertools import accumulate
class Solution:
def rangeSum(self, nums, n, left, right):
acc = []
for i in range(n):
acc.extend(accumulate(nums[i:]))
acc.sort()
return sum(acc[left - 1:right]) % (10**9 + 7) | class Solution {
private static int mod=(int)1e9+7;
public int rangeSum(int[] nums, int n, int left, int right) {
PriorityQueue<int[]> pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]);
for(int i=0;i<n;i++) pq.add(new int[]{i,nums[i]});
int ans=0;
for(int i=1;i<=right;i++){
int[] k=pq.remove();
if(i>=left){
ans=(ans+k[1])%mod;
}
if(k[0]+1<n){
pq.add(new int[]{k[0]+1,k[1]+nums[k[0]+1]});
}
}
return ans;
}
} | class Solution
{
public:
int rangeSum(vector<int>& nums, int n, int left, int right)
{
const int m= 1e9+7; // To return ans % m
int ans=0; // Final Answer
int k=1; // For 1 based indexing
int size= (n*(n+1))/2; // We can form n(n+1)/2 subarrays for an array of size n
vector<int> subsum(size+1);
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=nums[j]; // Sum of the subarray
subsum[k++]=sum; // Inserting the prefix sum at the index
}
}
sort(subsum.begin(),subsum.end()); // Sorting the array
for(int i=left; i<=right; i++)
{
ans=(ans+subsum[i])%m; // ans modulo 10^9 +7
}
return ans;
}
}; | var rangeSum = function(nums, n, left, right) {
const sums = [];
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
sums.push(sum);
}
}
sums.sort((a, b) => a - b);
let ans = 0;
for (let i = left - 1; i < right; i++) {
ans += sums[i];
}
return ans % 1000000007;
}; | Range Sum of Sorted Subarray Sums |
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
Example 1:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i] and list2[i] consist of spaces ' ' and English letters.
All the stings of list1 are unique.
All the stings of list2 are unique.
| class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
hashmap1 = {}
hashmap2 = {}
common = {}
for i in range(len(list1)):
hashmap1[list1[i]] = i
for j in range(len(list2)):
hashmap2[list2[j]] = j
for i in hashmap1:
if i in hashmap2:
print(1)
common[i] = hashmap1[i] + hashmap2[i]
common = list(common.items())
answer =[]
minimum = float("inf")
for i in range(0,len(common)):
if common[i][1] < minimum:
minimum = common[i][1]
for i in range(len(common)):
if common[i][1] == minimum:
answer.append(common[i][0])
return answer
| class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
List<String> l1 = Arrays.asList(list1);
int least = Integer.MAX_VALUE;
List<String> returnArray = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < list2.length; i++) {
if (l1.contains(list2[i])) {
map.put(list2[i], l1.indexOf(list2[i]) + i);
}
}
for (Map.Entry<String, Integer> entry: map.entrySet()){
if (entry.getValue() <= least) least = entry.getValue();
}
for (Map.Entry<String, Integer> entry: map.entrySet()){
if (entry.getValue() == least) returnArray.add(entry.getKey());
}
if (returnArray.size() > 1) return returnArray.toArray(String[]::new);
return new String[]{returnArray.get(0)};
}
} | class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
vector<string>vc;
unordered_map<string,int>umap,umap1;
for(int i=0;i<list1.size();i++)
{
umap[list1[i]]=i;
}
for(int i=0;i<list2.size();i++)
{
umap1[list2[i]]=i;
}
int min=10000;
for(auto i:umap)
{
int k=0;
for(auto j :umap1)
{
if(i.first==j.first)
{
k=i.second+j.second;
if(min>k)
{vc.clear();
min=k;
vc.push_back(j.first);
}
else if(k==min)
{
vc.push_back(j.first);
}
}
}
}
return vc;
}
}; | var findRestaurant = function(list1, list2) {
let obj ={}
for(let i =0; i <list1.length; i ++){
if(list2.indexOf(list1[i]) !==-1){
const sum = i+ list2.indexOf(list1[i])
if(obj[sum]!==undefined)
{
obj[sum]['value'].push(list1[i])
}
else{
obj[sum]={}
obj[sum]['sum']=sum
obj[sum]['value']=[]
obj[sum]['value'].push(list1[i])
}
}
}
return Object.values(obj)[0]['value']
}; | Minimum Index Sum of Two Lists |
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.
Return the two integers in any order.
Example 1:
Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
Example 2:
Input: num = 123
Output: [5,25]
Example 3:
Input: num = 999
Output: [40,25]
Constraints:
1 <= num <= 10^9
| class Solution:
def closestDivisors(self, num: int) -> List[int]:
for i in range(int((num+2) ** (0.5)), 0, -1):
if not (num+1) % i: return [i, (num+1)//i]
if not (num+2) % i: return [i, (num+2)//i]
return [] | class Solution {
public int[] closestDivisors(int num) {
int ans[]=new int[2];
double a=Math.sqrt(num+1);
double b=Math.sqrt(num+2);
if(num==1){
ans[0]=1;
ans[1]=2;
return ans;
}
else if(a%1==0){
ans[0]=(int)a;
ans[1]=(int)b;
return ans;
}
else if(b%1==0){
ans[0]=(int)b;
ans[1]=(int)b;
return ans;
}
else{
int m=(int)Math.sqrt(num);
int diff1=Integer.MAX_VALUE;
int y=0,z=0,w=0,f=0;
for(int i=2;i<=m;i++){
if((num+1)%i==0){
y=i;
z=(num+1)/y;
int r=Math.abs(y-z);
if(r<diff1){
diff1=r;
}
}
}
int diff2=Integer.MAX_VALUE;
for(int i=2;i<=m;i++){
if((num+2)%i==0){
w=i;
f=(num+2)/w;
int r=Math.abs(w-f);
if(r<diff2){
diff2=r;
}
}
}
if(diff1<diff2){
ans[0]=y;
ans[1]=z;
return ans;
}
else{
ans[0]=w;
ans[1]=f;
return ans;
}
}
}
}``` | class Solution
{
public:
vector<int> findnumbers(int num)
{
int m=sqrt(num);
while(num%m!=0)
{
m--;
}
return {num/m,m};
}
vector<int> closestDivisors(int num)
{
vector<int> ans1=findnumbers(num+1);
vector<int> ans2=findnumbers(num+2);
if(abs(ans1[0]-ans1[1])<abs(ans2[0]-ans2[1]))
return ans1;
return ans2;
}
}; | /**
* @param {number} num
* @return {number[]}
*/
var closestDivisors = function(num) {
const n1 = num + 1;
const n2 = num + 2;
let minDiff = Infinity;
let result = [];
for(let i = Math.floor(Math.sqrt(n2)); i >= 1; i--) {
if(n1 % i === 0) {
const diff = Math.abs(i - (n1 / i));
if(diff < minDiff) {
minDiff = diff;
result = [i, n1 / i]
}
}
if(n2 % i === 0) {
const diff = Math.abs(i - (n2 / i));
if(diff < minDiff) {
minDiff = diff;
result = [i, n2 / i]
}
}
}
return result;
}; | Closest Divisors |
Given a string s, find the longest palindromic subsequence's length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
1 <= s.length <= 1000
s consists only of lowercase English letters.
| class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[0 for x in range(n)] for x in range(n)]
for i in range(n): dp[i][i] = 1 # Single length strings are palindrome
for chainLength in range(2, n+1):
for i in range(0, n-chainLength+1): # Discarding the lower triangle
j = i + chainLength - 1
if s[i] == s[j]:
if chainLength == 2: dp[i][j] = 2
else: dp[i][j] = dp[i+1][j-1] + 2
else: dp[i][j] = max(dp[i+1][j], dp[i][j-1])
return dp[0][n-1] | class Solution {
public int longestPalindromeSubseq(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
String s2 = sb.toString();
return longestCommonSubsequence(s,s2);
}
public int longestCommonSubsequence(String text1, String text2) {
int [][]dp = new int[text1.length()+1][text2.length()+1];
for(int i= text1.length()-1;i>=0;i--){
for(int j = text2.length()-1;j>=0;j--){
char ch1 = text1.charAt(i);
char ch2 = text2.charAt(j);
if(ch1==ch2) // diagnal
dp[i][j]= 1+dp[i+1][j+1];
else// right,down considering not matchning char from s1 and skipping s2
//considering not matchning char from s2 and skipping s1
dp[i][j] = Math.max(dp[i][j+1],dp[i+1][j]);
}
}
return dp[0][0];
}
} | class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
int dp[n][n];
memset(dp, 0, sizeof(dp));
for(int i = 0; i < n; i++){
dp[i][i] = 1;
}
int res = 1;
for(int j = 1; j < n; j++){
for(int r = 0, c = j ; r < n && c < n; r++, c++){
if(s[r] == s[c]){
dp[r][c] = 2+dp[r+1][c-1];
}
else{
dp[r][c] = max(dp[r][c-1],dp[r+1][c]);
}
}
}
return dp[0][n-1];
}
}; | var longestPalindromeSubseq = function(s) {
const { length } = s;
const dp = Array(length).fill('').map(() => Array(length).fill(0));
for (let start = 0; start < length; start++) {
const str = s[start];
dp[start][start] = 1;
for (let end = start - 1; end >= 0; end--) {
dp[start][end] = str === s[end]
? dp[start - 1][end + 1] + 2
: Math.max(dp[start - 1][end], dp[start][end + 1])
}
}
return dp[length - 1][0];
}; | Longest Palindromic Subsequence |
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:
0 <= n < 109
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
| class Solution:
def bitwiseComplement(self, n: int) -> int:
cnt=0
ans=0
if n==0:
return 1
while n>0:
if n&1:
cnt+=1
else:
ans =ans +(2**cnt)
cnt+=1
n=n>>1
return ans | class Solution {
public int bitwiseComplement(int n) {
String bin = Integer.toBinaryString(n);
String res = "";
for(char c :bin.toCharArray())
{
if( c == '1')
res += "0";
else
res += "1";
}
return Integer.parseInt(res, 2);
}
} | class Solution {
public:
int bitwiseComplement(int num) {
//base case
if(num == 0) return 1;
unsigned mask = ~0;
while( mask & num ) mask = mask << 1;
return ~num ^ mask;
}
}; | var bitwiseComplement = function(n) {
let xor = 0b1;
let copy = Math.floor(n / 2);
while (copy > 0) {
xor = (xor << 1) + 1
copy = Math.floor(copy / 2);
}
return n ^ xor;
}; | Complement of Base 10 Integer |
You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".
Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Example 1:
Input: s = "letsleetcode", k = 2
Output: "let"
Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
"let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2
Output: "b"
Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2
Output: ""
Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s consists of lowercase English letters.
| class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
n = len(s)
max_chunk_sz = n // k
d = collections.Counter(s)
chars = sorted([c for c in d if d[c] >= k], reverse=True)
if not chars:
return ''
old_cand = chars
for m in range(2, max_chunk_sz+1):
new_cand = []
for t in self.get_next_level(old_cand, chars):
if self.find(s, t*k):
new_cand.append(t)
if len(new_cand) == 0:
break
old_cand = new_cand
return old_cand[0]
def get_next_level(self, cand, chars):
for s in cand:
for ch in chars:
yield s + ch
def find(self, s, t):
# find subsequence t in s
j = 0
for i in range(len(s)):
if s[i] == t[j]:
j += 1
if j == len(t):
return True
return False | class Solution {
char[] A;
public String longestSubsequenceRepeatedK(String s, int k) {
A = s.toCharArray();
Queue<String> queue = new ArrayDeque<>();
queue.offer("");
String ans = "";
int[] count = new int[26];
BitSet bit = new BitSet();
for (char ch : A) if (++count[ch-'a'] >= k){
bit.set(ch-'a');
}
while(!queue.isEmpty()){
String sb = queue.poll();
for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i+1)){
String res = sb+(char)(i+'a');
if (check(k, res)){
ans = res;
queue.offer(res);
}
}
}
return ans;
}
private boolean check(int k, String s){
int cnt = 0;
for (char ch : A){
if (s.charAt(cnt%s.length()) == ch && ++cnt >= k * s.length()){
return true;
}
}
return false;
}
} | class Solution {
public:
int Alpha=26;
bool find(string &s,string &p,int k)
{
int j=0;
int n=s.size();
int count=0;
for(int i=0;i<n;i++)
{
if(s[i]==p[j])
{
j++;
if(j==p.size())
{
count++;
j=0;
}
if(count==k)
{
return true;
}
}
}
return false;
}
string longestSubsequenceRepeatedK(string s, int k)
{
queue<string>q;
q.push("");
string ans="";
while(q.size())
{
auto temp=q.front();
q.pop();
for(int i=0;i<Alpha;i++)
{
string curr=temp+char('a'+i);
if(find(s,curr,k))
{
ans=curr;
q.push(curr);
}
}
}
return ans;
}
}; | // Idea comes from:
// https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1471930/Python-Answer-is-not-so-long-explained
var longestSubsequenceRepeatedK = function(s, k) {
const freq = {};
for (const c of s) {
if (!freq[c]) freq[c] = 0;
freq[c]++;
}
// Find hot string
let hot = "";
for (const [c, cnt] of Object.entries(freq)) {
const repeat = Math.floor(cnt / k);
hot += c.repeat(repeat);
}
// Find all subset and permutation of hot string
let targets = new Set();
const subsets = getSubset(hot);
for (const subset of subsets) {
const permutations = getPermutation(subset);
for (const per of permutations) targets.add(per);
}
// Sort targets by length and lexico
targets = [...targets].sort((a, b) => {
const delta = b.length - a.length;
if (delta) return delta;
return b.localeCompare(a);
});
// Filter s and check subsequence
s = [...s].filter(c => hot.includes(c)).join("");
for (const tar of targets) {
if (isSubsequence(s, tar.repeat(k))) return tar;
}
return "";
};
function getSubset(str) {
const res = [""];
for (const c of str) {
res.push(...res.map((curStr) => curStr + c));
}
return [...new Set(res)];
};
function getPermutation(str) {
let res = [""];
for (const c of str) {
const resT = [];
for (const cur of res) {
for (let i = 0; i <= cur.length; i++) {
const curT = cur.substring(0, i) + c + cur.substring(i);
resT.push(curT);
}
}
res = resT;
}
return [...new Set(res)];
};
function isSubsequence(s, t) {
let i = 0;
for (let j = 0; j < s.length; j++) {
if (t[i] === s[j]) {
i++;
if (i === t.length) return true;
}
}
return false;
} | Longest Subsequence Repeated k Times |
Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.
Example 1:
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
Example 2:
Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.
Example 3:
Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= 105
| from collections import Counter
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if k > len(s):
return False
h = Counter(s)
countOdd = 0
for value in h.values():
if value % 2:
countOdd += 1
if countOdd > k:
return False
return True | class Solution {
public boolean canConstruct(String s, int k) {
if(k==s.length())
{
return true;
}
else if(k>s.length())
{
return false;
}
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++)
{
if(map.containsKey(s.charAt(i)))
{
int count=map.get(s.charAt(i));
map.put(s.charAt(i),count+1);
}
else
{
map.put(s.charAt(i),1);
}
}
int odd=0;
for(Map.Entry<Character,Integer>ele:map.entrySet())
{
if((ele.getValue()%2)==1)
{
odd++;
}
}
return (odd<=k);
}
} | class Solution {
public:
bool canConstruct(string s, int k) {
if(s.size() < k) return false;
unordered_map<char, int> m;
for(char c : s) m[c]++;
int oddFr = 0;
for(auto i : m) if(i.second % 2) oddFr++;
return oddFr <= k;
}
}; | var canConstruct = function(s, k) {
if(s.length < k) return false;
// all even all even
// all even max k odd
const freq = {};
for(let c of s) {
freq[c] = (freq[c] || 0) + 1;
}
let oddCount = 0;
const freqOfNums = Object.values(freq);
for(let cnt of freqOfNums) {
if(cnt & 1) oddCount++;
}
return oddCount <= k;
}; | Construct K Palindrome Strings |
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.
Example 1:
Input: nums = [-4,-2,1,4,8]
Output: 1
Explanation:
The distance from -4 to 0 is |-4| = 4.
The distance from -2 to 0 is |-2| = 2.
The distance from 1 to 0 is |1| = 1.
The distance from 4 to 0 is |4| = 4.
The distance from 8 to 0 is |8| = 8.
Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1]
Output: 1
Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000
-105 <= nums[i] <= 105
| class Solution:
def findClosestNumber1(self, nums: List[int]) -> int:
return min(nums, key=lambda x: (abs(x), -x))
def findClosestNumber2(self, nums: List[int]) -> int:
return min(nums, key=lambda x: abs(x - .1))
def findClosestNumber3(self, nums: List[int]) -> int:
return max((-abs(x), x) for x in nums)[1]
def findClosestNumber4(self, nums: List[int]) -> int:
return -min(zip(map(abs, nums), map(neg, nums)))[1]
def findClosestNumber5(self, nums: List[int]) -> int:
a = min(map(abs, nums))
return a if a in nums else -a
def findClosestNumber6(self, nums: List[int]) -> int:
a = abs(min(nums, key=abs))
return a if a in nums else -a
def findClosestNumber7(self, nums: List[int]) -> int:
x = min(nums, key=abs)
return x if x >= 0 or -x not in nums else -x
def findClosestNumber8(self, nums: List[int]) -> int:
return min(sorted(nums, reverse=True), key=abs)
def findClosestNumber9(self, nums: List[int]) -> int:
a = abs(nums[0])
for x in nums:
if x < 0:
x = -x
if x < a:
a = x
return a if a in nums else -a
def findClosestNumberA(self, nums: List[int]) -> int:
pos = 999999
neg = -pos
for x in nums:
if x < 0:
if x > neg:
neg = x
elif x < pos:
pos = x
return pos if pos <= -neg else neg
def findClosestNumberB(self, nums: List[int]) -> int:
pos = 999999
neg = -pos
for x in nums:
if x < pos and neg < x:
if x < 0:
neg = x
else:
pos = x
return pos if pos <= -neg else neg
def findClosestNumberC(self, nums: List[int]) -> int:
pos = 999999
neg = -pos
for x in nums:
if neg < x and x < pos:
if x < 0:
neg = x
else:
pos = x
return pos if pos <= -neg else neg
def findClosestNumberD(self, nums: List[int]) -> int:
pos = 999999
neg = -pos
for x in nums:
if neg < x < pos:
if x < 0:
neg = x
else:
pos = x
return pos if pos <= -neg else neg
def findClosestNumber(self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]) -> int:
name = 'findClosestNumber'
solutions = [getattr(self, s)
for s in dir(self)
if s.startswith(name)
and s != name]
expect = dummy = object()
from time import perf_counter as time
for i in range(10):
shuffle(solutions)
for solution in solutions:
start = time()
result = solution(nums)
end = time()
if expect is dummy:
expect = result
assert result == expect
timess[solution.__name__][i] += end - start
testcase[0] += 1
if testcase[0] == 224:
for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):
print(name, *(f'{t*1e3:6.2f} ms' for t in sorted(times)[:3]))
return
return result
| // If absolute of n is less than min, update the closest_num
// If absolute of n is same of as min, update the bigger closest_num
class Solution {
public int findClosestNumber(int[] nums) {
int min = Integer.MAX_VALUE, closest_num = 0;
for(int n : nums) {
if(min > Math.abs(n)) {
min = Math.abs(n);
closest_num = n;
} else if(min == Math.abs(n) && closest_num < n) {
closest_num = n;
}
}
return closest_num;
}
} | class Solution {
public:
int findClosestNumber(vector<int>& nums) {
// setting the ans to maximum value of int
int ans = INT_MAX ;
for(int i : nums){
// checking if each value of nums is less than the max value
if(abs(i) < abs(ans)){
ans = i ; //check for the lesser value
}
else if(abs(i) == abs(ans)){
ans = max (ans,i) ; // return the maximum in cases there are multiple answers
}
}
return ans ;
}
}; | //Solution 1
var findClosestNumber = function(nums) {
let pos = Infinity;
let neg = -Infinity;
for(let i = 0; i < nums.length; i++) {
if( nums[i] > 0 ){
if( pos > nums[i] )
pos = nums[i];
} else {
if( neg < nums[i] )
neg = nums[i];
}
}
if( -neg < pos ) {
return neg;
}
return pos;
};
//Solution 2
var findClosestNumber = function(nums) {
let result = nums[0];
for(let i=1; i<nums.length; i++) {
let mod = Math.abs(nums[i]);
if( Math.abs(result)>mod ) {
result = nums[i]
}
if( Math.abs(result) == mod ) {
if( result<nums[i] ) {
result = nums[i];
}
}
}
return result;
}; | Find Closest Number to Zero |
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.
After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.
However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.
Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
Example 1:
Input: dist = [1,3,2], speed = 4, hoursBefore = 2
Output: 1
Explanation:
Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.
Example 2:
Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10
Output: 2
Explanation:
Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.
Example 3:
Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10
Output: -1
Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.
Constraints:
n == dist.length
1 <= n <= 1000
1 <= dist[i] <= 105
1 <= speed <= 106
1 <= hoursBefore <= 107
| from math import *
class Solution:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
n=len(dist)
# Error Range 10^-9 can be ignored in ceil, so we will subtract this value before taking ceil
e=1e-9
mat=[[0 for i in range(n)]for j in range(n)]
mat[0][0]=dist[0]/speed
# Initialization
# Values where 0 skips are considered
for i in range(1,n):
mat[i][0]=ceil(mat[i-1][0]-e)+dist[i]/speed
for i in range(1,n):
for j in range(1,i):
mat[i][j]=min(ceil(mat[i-1][j]-e),mat[i-1][j-1])+dist[i]/speed
mat[i][i]=mat[i-1][i-1]+dist[i]/speed
for i in range(n):
if mat[-1][i]<=hoursBefore:
return i
return -1 | class Solution {
public int minSkips(int[] dist, int speed, int hoursBefore) {
int N = dist.length, INF = (int)1e9;
int[] dp = new int[N];
Arrays.fill(dp, INF);
dp[0]=0; // before we start, we have a time of 0 for 0 cost
for (int i = 0 ; i<N; i++){
for (int j = i; j >= 0; j--){ // j (cost) is at most i (num of element-1) so we start from there.
dp[j]=Math.min(j==0?INF:dp[j-1]+dist[i], ceil(dp[j], speed)+dist[i]);
}
}
for (int i = 0; i < N; i++){ // find the min cost (i) such that the min time is no greater than hoursBefore
if (ceil(dp[i],speed)/speed<=hoursBefore){
return i;
}
}
return -1;
}
private int ceil(int n, int s){
return n+(s-n%s)%s;
}
} | class Solution {
public:
vector<int>D;
long long s, last;
long long memo[1010][1010];
long long dfs_with_minimum_time_with_k_skip(int idx, int k) {
if (idx < 0 ) return 0;
long long &ret = memo[idx][k];
if (ret != -1 ) return ret;
long long d = dfs_with_minimum_time_with_k_skip(idx - 1, k) + D[idx];
if (d % s) d = ((d/s) + 1)*s;
ret = d;
if (k > 0 ) ret = min(ret, dfs_with_minimum_time_with_k_skip(idx - 1, k - 1) + D[idx]);
return ret;
}
int minSkips(vector<int>& dist, int speed, int hoursBefore) {
int n = dist.size();
D = dist, s = speed;
int lo = 0, hi = n;
long long d = 0, H = hoursBefore;
H *=s;
last = dist[n-1];
for (int dd : dist) d += dd;
memset(memo, -1, sizeof(memo));
if (d /s > hoursBefore) return -1;
while (lo < hi) {
int mid = (lo + hi) / 2;
long long h = dfs_with_minimum_time_with_k_skip(n-2, mid) + last; // we should start from second last since it is not required to rest on last road
if (h <= H ) hi = mid;
else lo = mid + 1;
}
return lo == D.size() ? -1 : lo;
}
}; | var minSkips = function(dist, speed, hoursBefore) {
// calculates the time needed to rest
const getRestTime = (timeFinished) => {
if (timeFinished === Infinity) return 0;
return (speed - (timeFinished % speed)) % speed;
}
// dp is a n x n matrix with
// dp[destinationIndex][numRestsSkipped] = timeTaken
//
// destinationIndex: the index of the destination being observed
// numRestsSkipped: number of rests taken
// timeTaken: minimum time taken to travel to destination taking numRests number of rests
const dp = [...dist].map(() => new Array(dist.length).fill(Infinity));
// start with the first stop
dp[0][0] = dist[0] + getRestTime(dist[0]) // took a rest at the first destination
dp[0][1] = dist[0]; // did not take a rest at the first destination
for (let distIdx = 1; distIdx < dist.length; distIdx++) {
const distance = dist[distIdx];
let timeToDestWithoutrest = dp[distIdx - 1][0] + distance;
dp[distIdx][0] = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);
for (let numRestsSkipped = 1; numRestsSkipped <= distIdx + 1; numRestsSkipped++) {
// calculate the time if taking a rest here
timeToDestWithoutrest = dp[distIdx - 1][numRestsSkipped] + distance;
const didRestTimeToDest = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);
// calculate the time without resting here
const didntRestTimeToDest = dp[distIdx - 1][numRestsSkipped - 1] + distance
// store the best time in the dp
dp[distIdx][numRestsSkipped] = Math.min(dp[distIdx][numRestsSkipped],
didRestTimeToDest,
didntRestTimeToDest);
}
}
// find the minimum number of rests visiting all the destinations
const speedHours = speed * hoursBefore;
for (let numRests = 0; numRests < dist.length; numRests++) {
if (dp[dist.length - 1][numRests] <= speedHours) {
return numRests;
}
}
return -1;
}; | Minimum Skips to Arrive at Meeting On Time |
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
Example 1:
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Example 2:
Input: paragraph = "a.", banned = []
Output: "a"
Constraints:
1 <= paragraph.length <= 1000
paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.
| class Solution:
import string
from collections import Counter
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
#sunday morning hangover solution haha
#calling this twice seems unnecesary but whatevs
#replace "," with " " (apparently translate() is much quicker than replace)
para = paragraph.translate(str.maketrans(","," "))
#strip out rest of punctuation and make it lower case
para = para.translate(str.maketrans(' ', ' ', string.punctuation)).lower()
#split on the sapces
para = para.split()
#staple counter function
para_count = Counter(para)
#loop thru banned words, if they're in para_count pop the off
for word in banned:
if word in para_count:
para_count.pop(word)
#return val from most common
return para_count.most_common(1)[0][0] | class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
HashMap<String, Integer> hm = new HashMap<>();
String[] words = paragraph.replaceAll("[!?',;.]"," ").toLowerCase().split("\\s+");
for(int i=0; i<words.length; i++)
{
if(hm.containsKey(words[i]))
hm.replace(words[i], hm.get(words[i]), hm.get(words[i])+1);
else
hm.put(words[i], 1);
}
for(int i=0; i< banned.length; i++)
if(hm.containsKey(banned[i]))
hm.remove(banned[i]);
return Collections.max(hm.entrySet(), Map.Entry.comparingByValue()).getKey();
}
} | class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
string temp;
vector<string> words;
for(char c:paragraph){
if(isalpha(c) && !isspace(c)) temp+=tolower(c);
else{
if(temp.length()) words.push_back(temp);
temp="";
}
}
if(temp.length()) words.push_back(temp);
map<string,int> mp;
for(string i:words) mp[i]++;
for(string i:banned) mp[i]=0;
string ans;
int maxUsedFreq=0;
for(auto i:mp){
if(i.second>maxUsedFreq){
ans=i.first;
maxUsedFreq=i.second;
}
}
return ans;
}
}; | var mostCommonWord = function(paragraph, banned) {
paragraph = new Map(Object.entries(
paragraph
.toLowerCase()
.match(/\b[a-z]+\b/gi)
.reduce((acc, cur) => ((acc[cur] = (acc[cur] || 0) + 1), acc), {}))
.sort((a, b) => b[1] - a[1])
);
for (let i = 0; i < banned.length; i++) paragraph.delete(banned[i]);
return paragraph.entries().next().value[0];
}; | Most Common Word |
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.
You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.
Return the total number of seconds that Ashe is poisoned.
Example 1:
Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Example 2:
Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
Constraints:
1 <= timeSeries.length <= 104
0 <= timeSeries[i], duration <= 107
timeSeries is sorted in non-decreasing order.
| class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
"""
timeDur = (timeSeries[0], timeSeries[0] + duration - 1)
i = 1
total = 0
while i < len(timeSeries):
if timeSeries[i] > timeDur[1]:
total += (timeDur[1] - timeDur[0] + 1)
else:
total += (timeSeries[i] - timeDur[0])
timeDur = (timeSeries[i], timeSeries[i] + duration - 1)
i += 1
total += (timeDur[1] - timeDur[0] + 1)
return total
"""
# Between two interval, Ashe can be poisoned only for max duration time,
# if time differece is less than duranton, then we that value
total = 0
for i in range(len(timeSeries)-1):
total += min(duration, timeSeries[i+1] - timeSeries[i])
return total + duration
| // Teemo Attacking
// https://leetcode.com/problems/teemo-attacking/
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int sum = 0;
for (int i = 0; i < timeSeries.length; i++) {
if (i == 0) {
sum += duration;
} else {
sum += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);
}
}
return sum;
}
} | class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int ans=0;
int n=timeSeries.size();
for(int i=0;i<n;i++){
ans+=min(duration,(i==n-1?duration:timeSeries[i+1]-timeSeries[i]));
}
return ans;
}
}; | var findPoisonedDuration = function(timeSeries, duration) {
let totalTime=duration
for(let i=0;i+1<timeSeries.length;i++){
let diff=timeSeries[i+1]-timeSeries[i]
totalTime+= diff>duration ? duration : diff
}
return totalTime
}; | Teemo Attacking |
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Constraints:
The number of nodes in the tree is in the range [2, 100].
1 <= Node.val <= 100
Each node has a unique value.
x != y
x and y are exist in the tree.
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
ans = False
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
def dfs(node, depth):
if self.ans or not node: return 0
if node.val == x or node.val == y: return depth
l = dfs(node.left, depth+1)
r = dfs(node.right, depth+1)
if not (l and r): return l or r
if l == r and l != depth + 1: self.ans = True
return 0
dfs(root, 0)
return self.ans | class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
Set<TreeNode> parentSet = new HashSet<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
TreeNode parent = q.remove();
for (TreeNode child : new TreeNode[]{parent.left, parent.right}) {
if(child != null) {
q.add(child);
if (child.val == x || child.val == y)
parentSet.add(parent);
}
}
}
if (parentSet.size() > 0)
return parentSet.size() == 2; //if same parent -> set size wil be 1
}
return false;
}
} | class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
if(root -> left == NULL || root -> right == NULL) return false;
//to store node with parent
queue<pair<TreeNode*, TreeNode*> > q;
//push root
q.push({root, NULL});
//push NULL for level seperation
q.push({NULL, NULL});
//boolean val to know if we found x or y yet during traversal of tree
pair<bool, TreeNode*> foundx = {false, NULL}, foundy = {false, NULL};
//start the level order traversal
while(!q.empty()){
TreeNode* top = q.front().first;
TreeNode* parent = q.front().second;
q.pop();
//when a level is completely traversed
if(top == NULL){
//if we found both x and y and if their parent are not same we found cousins
if(foundx.first && foundy.first && foundx.second != foundy.second) return true;
//if one of them found when other not, or when both were found and their parent were equal
if(foundx.first || foundy.first) return false;
//push another NULL for further level seperation, if there are any.
if(!q.empty()) q.push({NULL, NULL});
}
else{
//find x and y
if(top -> val == x) foundx = {true, parent};
if(top -> val == y) foundy = {true, parent};
//push current node's childs with parent as current node.
if(top -> left) q.push({top -> left, top});
if(top -> right) q.push({top -> right, top});
}
}
return false;
}
}; | var isCousins = function(root, x, y) {
let xHeight = 1;
let xParent = null;
let yHeight = 1;
let yParent = null;
const helper = (node, depth, parent) => {
if(node === null)
return null;
helper(node.left, depth + 1, node);
helper(node.right, depth + 1, node);
let val = node.val;
if(val === x) {
xHeight = depth;
xParent = parent;
}
if(val === y) {
yHeight = depth;
yParent = parent;
}
}
helper(root, 0);
return xHeight === yHeight && xParent !== yParent ? true : false;
}; | Cousins in Binary Tree |
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
An array A is a zigzag array if either:
Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...
Return the minimum number of moves to transform the given array nums into a zigzag array.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.
Example 2:
Input: nums = [9,6,1,6,2]
Output: 4
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
| class Solution:
def solve(self,arr,n,x):
idx = 1
ans = 0
while idx < n:
if idx == 0: idx += 1
if idx % 2 == x:
if arr[idx-1] >= arr[idx]:
ans += arr[idx-1] - arr[idx] + 1
arr[idx-1] = arr[idx] - 1
idx = idx-1
else:
idx = idx+1
else:
if arr[idx-1] <= arr[idx]:
ans += arr[idx] - arr[idx - 1] + 1
arr[idx] = arr[idx-1] - 1
idx += 1
return ans
def movesToMakeZigzag(self, nums: List[int]) -> int:
ans1 = self.solve([x for x in nums],len(nums),0)
ans2 = self.solve([x for x in nums],len(nums),1)
return min(ans1,ans2) | class Solution {
/*
firstly, check elements in odd indices are greater than its neighbours.
if not, decrease its neigbours and update the cost.
do same thing for even indices, because there can be two combinations as indicated in question.
*/
private int calculateCost(int[] nums, int start){
int res = 0;
int n = nums.length;
int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.
for(int i=start;i<n;i+=2){
int prev = (i==0) ? Integer.MIN_VALUE : arr[i-1];
int cur = arr[i];
int next = (i == n-1) ? Integer.MIN_VALUE : arr[i+1];
if(prev < cur && next < cur)
continue;
if(prev >= cur){
res += prev-cur +1;
arr[i-1] = cur-1;
}
if(next >= cur){
res += next-cur +1;
arr[i+1] = cur-1;
}
}
return res;
}
public int movesToMakeZigzag(int[] nums) {
return Math.min(calculateCost(nums, 0), calculateCost(nums,1));
}
} | class Solution {
public:
int movesToMakeZigzag(vector<int>& nums) {
int oddSum = 0, evenSum = 0;
int n = nums.size();
for(int i=0; i<n; i++){
if(i%2 == 0){
int left = i==0?INT_MAX:nums[i-1];
int right = i==n-1?INT_MAX:nums[i+1];
evenSum += max(nums[i]-min(left,right)+1,0);
}else{
int left = i==0?INT_MAX:nums[i-1];
int right = i==n-1?INT_MAX:nums[i+1];
oddSum += max(nums[i]-min(left,right)+1,0);
}
}
return min(evenSum,oddSum);
}
}; | var movesToMakeZigzag = function(nums) {
const n = nums.length;
let lastEvenRight = Number.MIN_SAFE_INTEGER;
let evenMoves = 0;
let lastOddRight = nums[0];
let oddMoves = 0;
for (let i = 0; i < n; i++) {
const currNum = nums[i];
const nextNum = i < n - 1 ? nums[i + 1] : Number.MIN_SAFE_INTEGER;
if (i % 2 === 0) {
if (lastEvenRight >= currNum) evenMoves += lastEvenRight - currNum + 1;
if (currNum <= nextNum) {
evenMoves += nextNum - currNum + 1;
}
lastEvenRight = Math.min(currNum - 1, nextNum);
}
else {
if (lastOddRight >= currNum) oddMoves += lastOddRight - currNum + 1;
if (currNum <= nextNum) {
oddMoves += nextNum - currNum + 1;
}
lastOddRight = Math.min(currNum - 1, nextNum);
}
}
return Math.min(oddMoves, evenMoves);
}; | Decrease Elements To Make Array Zigzag |
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Example 1:
Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2:
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Constraints:
The number of nodes in the tree is in the range [1, 3 * 104].
-1000 <= Node.val <= 1000
| class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.res=root.val
def solving(root):
if not root:
return 0
current=root.val
sleft,sright=float('-inf'),float('-inf')
if root.left:
sleft=solving(root.left)
if(sleft>=0):
current+=sleft
if root.right:
sright=solving(root.right)
if(sright>=0):
current+=sright
if(current>self.res):
self.res=current
return max(root.val, root.val+sleft, root.val+sright)
solving(root)
return self.res | class Solution {
int[] ans = new int[1];
public int maxPathSum(TreeNode root) {
ans[0]=root.val; //Handle edge case
dfs(root);
return ans[0];
}
public int dfs(TreeNode root){
if(root==null)
return 0;
int left=Math.max(0,dfs(root.left)); //Check on the left subtree and if returned negative take 0
int right=Math.max(0,dfs(root.right)); //Check on the right subtree and if returned negative take 0
int maxInTheNode=root.val+left+right; //Calculating the max while including the root its left and right child.
ans[0]=Math.max(ans[0],maxInTheNode); //Keeping max globally
return root.val+Math.max(left,right); //Since only one split is allowed returning the one split that returns max value
}
} | class Solution {
public:
int rec(TreeNode* root,int& res ){
if(root==nullptr) return 0;
// maximum value from left
int l = rec(root->left,res);
//maximum value from right
int r = rec(root->right,res);
//check if path can go through this node ,if yes upadte the result value
res = max(res,root->val+l+r);
// return the maximum non-negative path value
return max({l+root->val,r+root->val,0});
}
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
int x = rec(root,res);
return res;
}
}; | var maxPathSum = function(root) {
let res = -Infinity;
function solve(root){
if(!root){
return 0;
}
let left = solve(root.left);
let right = solve(root.right);
//ignore the values with negative sum
let leftVal = Math.max(left, 0);
let rightVal = Math.max(right,0);
let localMax = leftVal + rightVal + root.val;
res = Math.max(localMax,res);
return Math.max(leftVal, rightVal) + root.val;
}
solve(root);
return res;
}; | Binary Tree Maximum Path Sum |
You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Constraints:
1 <= arr.length <= 2000
0 <= arr[i] <= 108
| class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
sortedArr = sorted(arr)
posMap = defaultdict(list)
for i in range(len(sortedArr)):
posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position
idx = len(arr) - 1
cnt = 0
for i in range(len(arr) - 1, -1, -1):
idx = min(idx, posMap[arr[i]][-1]) # the smallest position need to move arr[i] to correct position
posMap[arr[i]].pop()
if i == idx:
cnt += 1
idx -= 1
return cnt | /*
1. Generate Right min
2. Generate Left Max
3. Count chunks
Pos -->. 0 1 2 3 4 5 6 7
Input --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70
<------------> <--> <-------> <------->
Left Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75
Right Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max
1. At pos 2 , left_max 30 is smaller than right_min 40 at pos 3
2. That means , all the elements in the right side of 30 are bigger than all the elements of left side of 30 , including 30
3. Hence we can break it at pos 2 into a chunk and sort this whole sub-array( 0 - 2 )
*/
class Solution {
public int maxChunksToSorted(int[] arr) {
// 1. Generate Right min
int[] min_from_right = new int[arr.length+1] ;
min_from_right[arr.length] = Integer.MAX_VALUE ;
for(int i=arr.length-1 ; i>=0 ; i--){
min_from_right[i] = Math.min(arr[i] , min_from_right[i+1]);
}
// 2. Generate Left Max and Count chunks
int chunk_count = 0 ;
int max_cur = Integer.MIN_VALUE ;
for(int i=0 ; i<arr.length ; i++){
max_cur = Math.max(max_cur , arr[i]);
if(max_cur <= min_from_right[i+1]){
chunk_count++ ;
}
}
return chunk_count ;
}
} | class BIT {
public:
BIT(int capacity) : nodes(capacity + 1, 0) {}
BIT(const vector<int>& nums) : nodes(nums.size() + 1, 0) {
for (int i = 0; i < nums.size(); ++i) {
update(i + 1, nums[i]);
}
}
void update(int idx, int val) {
for (int i = idx; i < nodes.size(); i += i & -i) {
nodes[i] += val;
}
}
int query(int idx) {
int ans = 0;
for (int i = idx; i > 0; i -= i & -i) {
ans += nodes[i];
}
return ans;
}
private:
vector<int> nodes;
};
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int n = arr.size();
BIT bit(n);
unordered_map<int, int> h;
vector<int> sorted = arr;
sort(sorted.begin(), sorted.end());
for (int i = 0; i < n; ++i) {
if (i == 0 || sorted[i - 1] != sorted[i]) h[sorted[i]] = i + 1;
}
int ans = 0;
for (int i = 0; i < n; ++i) {
bit.update(h[arr[i]], 1);
++h[arr[i]];
if (bit.query(i + 1) == i + 1) ans += 1;
}
return ans;
}
}; | var maxChunksToSorted = function(arr) {
var rmin = new Array(arr.length).fill(0);
rmin[arr.length] = Number.MAX_SAFE_INTEGER;
for(var i=arr.length-1; i>=0; i--) {
rmin[i] = Math.min(arr[i], rmin[i+1]);
}
var lmax = Number.MIN_SAFE_INTEGER;
var count = 0;
for(var i=0; i<arr.length; i++) {
lmax = Math.max(arr[i], lmax);
if(lmax <= rmin[i+1]) {
count++;
}
}
return count;
};`` | Max Chunks To Make Sorted II |
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
answer[i] % answer[j] == 0, or
answer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
Example 1:
Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.
Example 2:
Input: nums = [1,2,4,8]
Output: [1,2,4,8]
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 109
All the integers in nums are unique.
| class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
dp = [1 for i in range(n)]
hashh = [i for i in range(n)]
ans_ind = 0
for i in range(1, n):
for j in range(0,i):
if nums[i]%nums[j] == 0 and dp[j]+1 > dp[i]:
dp[i] = dp[j]+1
hashh[i] = j
# print(dp)
# print(hashh)
out = []
maxi = dp[0]
for i in range(len(nums)):
if dp[i] > maxi:
ans_ind = i
maxi = dp[i]
while(hashh[ans_ind]!=ans_ind):
out.append(nums[ans_ind])
ans_ind = hashh[ans_ind]
out.append(nums[ans_ind])
return(out)
| class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int N = nums.length;
List<Integer> ans =new ArrayList<Integer>();
int []dp =new int[N];
Arrays.fill(dp,1);
int []hash =new int[N];
for(int i=0;i<N;i++){
hash[i]=i;
}
int lastindex=0;
int maxi =1;
for(int i=0;i<N;i++){
for(int j=0;j<i;j++){
if(nums[i]%nums[j] == 0 && dp[j]+1 >dp[i]){
dp[i] = dp[j]+1;
hash[i] = j;
}
if(dp[i] > maxi){
maxi = dp[i];
lastindex = i;
}
}
}//for ends
ans.add(nums[lastindex]);
while(hash[lastindex] != lastindex){
lastindex = hash[lastindex];
ans.add(nums[lastindex]);
}
return ans;
}
} | class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<int> ans;
for(int i = 0; i < n; i++)
{
vector<int> tmp;
tmp.push_back(nums[i]);
// Checking the prev one
int j = i - 1;
while(j >= 0)
{
if(tmp.back() % nums[j] == 0)
tmp.push_back(nums[j]);
j--;
}
// Reversing the order to make it in increasing order
reverse(tmp.begin(), tmp.end());
// Checking the forward one
j = i + 1;
while(j < n)
{
if(nums[j] % tmp.back() == 0)
tmp.push_back(nums[j]);
j++;
}
// updating the ans
if(ans.size() < tmp.size())
ans = tmp;
}
return ans;
}
}; | /** https://leetcode.com/problems/largest-divisible-subset/
* @param {number[]} nums
* @return {number[]}
*/
var largestDivisibleSubset = function(nums) {
// Memo
this.memo = new Map();
// Sort the array so we can do dynamic programming from last number
// We want to start from last number because it will be the largest number, the largest number will yield the largest subset because it can be divided many times
nums.sort((a, b) => a - b);
let out = [];
// Perform dynamic programming on every numbers start from the last number
for (let i = nums.length - 1; i >= 0; i--) {
let curr = dp(nums, i);
// Update the subset output if the current subset is larger
if (curr.length > out.length) {
out = curr;
}
}
return out;
};
var dp = function(nums, currIdx) {
// Return from memo
if (this.memo.has(currIdx) === true) {
return this.memo.get(currIdx);
}
let currSubset = [];
// Look up all numbers before `currIdx`
for (let i = currIdx - 1; i >= 0; i--) {
// Check if the number at `currIdx` can be divided by number at `i`
if (nums[currIdx] % nums[i] === 0) {
// If they can be divided, perform dynamic programming on `i` to get the subset at `i`
let prevSubset = dp(nums, i);
// If the subset at `i` is longer than current subset, update current subset
if (prevSubset.length > currSubset.length) {
currSubset = prevSubset;
}
}
}
// Create the output which include number at `currIdx`
let out = [...currSubset, nums[currIdx]];
// Set memo
this.memo.set(currIdx, out);
return out;
}; | Largest Divisible Subset |
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 3:
Input: nums = [1,2,3]
Output: 3
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
| class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
def helper(nums):
one, two = 0, 0
for i in nums:
temp = max(i + one, two)
one = two
two = temp
return two
return max(helper(nums[:-1]), helper(nums[1:])) | class Solution {
public int rob(int[] nums) {
if(nums.length==1){
return nums[0];
}
int[] t = new int[nums.length];
for(int i = 0 ; i < t.length;i++){
t[i] = -1;
}
int[] k = new int[nums.length];
for(int i = 0 ; i < k.length;i++){
k[i] = -1;
}
return Math.max(helper(nums,0,0,t),helper(nums,1,1,k));
}
static int helper(int[] nums, int i,int start , int[] t){
if(start==0 && i==nums.length-2){
return nums[i];
}
if(start==1 && i==nums.length-1){
return nums[i];
}
if(start==0 && i>=nums.length-1){
return 0;
}
if(start==1 && i>=nums.length){
return 0;
}
if(t[i] != -1){
return t[i];
}
int pick = nums[i]+helper(nums,i+2,start,t);
int notpick = helper(nums,i+1,start,t);
t[i] = Math.max(pick,notpick);
return t[i];
}
} | class Solution {
public:
int rob(vector<int>& nums)
{
int n = nums.size();
if(n == 1)
{
return nums[0];
}
//dp[n][2][1]
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(2, vector<int>(2, -1)));
int maxm = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
{
maxm = max(maxm, dp_fun(dp, i, j, k, nums));
}
}
}
return maxm;
}
int dp_fun(vector<vector<vector<int>>> &dp, int ind, int num, int last, vector<int> &ar)
{
int n = ar.size();
if(dp[ind][num][last] == -1)
{
if(ind == 0)
{
if(last == 1)
{
dp[ind][num][last] = 0;
}
else
{
if(num == 1)
{
dp[ind][num][last] = ar[ind];
}
else
{
dp[ind][num][last] = 0;
}
}
}
else if (ind == n-1)
{
if(num == 0)
{
dp[ind][num][last] = 0;
}
else
{
if(last == 0)
{
dp[ind][num][last] = dp_fun(dp, ind-1, 1, 0, ar);
}
else
{
dp[ind][num][last] = ar[ind] + dp_fun(dp, ind-1, 0, 1, ar);
}
}
}
else
{
if(num == 1)
{
dp[ind][num][last] = max(ar[ind] + dp_fun(dp, ind-1, 0, last, ar), dp_fun(dp, ind-1, 1, last, ar));
}
else
{
dp[ind][num][last] = dp_fun(dp, ind-1, 1, last, ar);
}
}
}
return dp[ind][num][last];
}
}; | var rob = function(nums) {
let dp = []
dp[0] = [0,0]
dp[1] = [nums[0],0]
for(let i=2; i<=nums.length;i++){
let val = nums[i-1]
let rob = dp[i-2][0] + val
let dont = dp[i-1][0]
let noFirst = dp[i-2][1] + val
let best = (rob>=dont)?rob:dont
if(dp[i-1][1]>noFirst) noFirst=dp[i-1][1]
if(i!=nums.length){
dp[i] = [best,noFirst]
}else{
dp[i] = [dont,noFirst]
}
}
return (dp[nums.length][0]>=dp[nums.length][1]) ? dp[nums.length][0]:dp[nums.length][1]
}; | House Robber II |
Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.
Example 2:
Input: points = [[1,0],[0,0],[0,1]]
Output: 0.50000
Constraints:
3 <= points.length <= 50
-50 <= xi, yi <= 50
All the given points are unique.
| from itertools import combinations
class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
maxA = 0
for p1, p2, p3 in combinations(points, 3):
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y1 - y2))
if A > maxA: maxA = A
return maxA | class Solution {
public double largestTriangleArea(int[][] points) {
double ans = 0;
int n = points.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
for(int k=j+1;k<n;k++){
ans = Math.max(ans,0.5*Math.abs(points[i][0]*(points[j][1] - points[k][1]) + points[j][0]*( points[k][1] - points[i][1]) + points[k][0]*(points[i][1] - points[j][1])));
}
}
}
return ans;
}
} | class Solution {
public:
double largestTriangleArea(vector<vector<int>>& points) {
double ans = 0.00000;
for(int i = 0; i<points.size(); ++i)
for(int j = 0; j<points.size(); ++j)
if(i!=j)
for(int k = 0; k<points.size(); ++k)
if(k!=i and k!=j)
{
//For triangle formed by 3 points a,b and c: the area will be = 1/2 * [(xa*yb + xb*yc + xc*ya) - (ya*xb + yb*xc + yc*xa)]
ans = max(ans, 0.50000 * (points[i][0]*points[j][1] + points[j][0]*points[k][1] + points[k][0]*points[i][1] - points[i][1]*points[j][0] - points[j][1]*points[k][0] - points[k][1]*points[i][0]));
}
return ans;
}
}; | var largestTriangleArea = function(points) {
const n = points.length;
let maxArea = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (k = j + 1; k < n; k++) {
const area = calcArea(points[i], points[j], points[k]);
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
};
function calcArea(coordA, coordB, coordC){
const [xCoordA, yCoordA] = coordA;
const [xCoordB, yCoordB] = coordB;
const [xCoordC, yCoordC] = coordC;
const sideA = xCoordA * (yCoordB - yCoordC);
const sideB = xCoordB * (yCoordC - yCoordA);
const sideC = xCoordC * (yCoordA - yCoordB);
return Math.abs((sideA + sideB + sideC) / 2);
} | Largest Triangle Area |
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.
Example 1:
Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: equation = "x=x"
Output: "Infinite solutions"
Example 3:
Input: equation = "2x=x"
Output: "x=0"
Constraints:
3 <= equation.length <= 1000
equation has exactly one '='.
equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.
| def solveEquation(self, equation: str) -> str:
""" O(N)TS """
x, y, p = 0, 0, 1
for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation):
g = i.group()
if g == '=':
p = -1
elif g[-1] == 'x':
x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))
else:
y += -p * int(g)
if x == 0 == y:
return 'Infinite solutions'
elif x == 0:
return "No solution"
return f'x={y // x}' | class Solution {
public int[] simplifyEqn(String eqn){
int prevSign = 1;
int sumX = 0;
int sumNums = 0;
for(int i=0;i<eqn.length();){
int coEff = 0;
int j = i;
while(j<eqn.length() && Character.isDigit(eqn.charAt(j))){
coEff = coEff*10 + (eqn.charAt(j)-'0');
j++;
}
if(j<eqn.length() && eqn.charAt(j)=='x'){
if(i==j)
coEff = 1;
sumX += prevSign*coEff;
j++;
}
else{
sumNums += prevSign*coEff;
}
if(j<eqn.length() && eqn.charAt(j)=='+')
prevSign = 1;
else if(j<eqn.length() && eqn.charAt(j)=='-')
prevSign = -1;
i=++j;
}
return new int[] {sumX, sumNums};
}
public String solveEquation(String equation) {
String[] leftNRight = equation.split("=");
String left = leftNRight[0], right = leftNRight[1];
int[] leftEqn = simplifyEqn(left);
int[] rightEqn = simplifyEqn(right);
int x = leftEqn[0]-rightEqn[0];
int num = rightEqn[1]-leftEqn[1];
if(x==0)
if(num==0)
return "Infinite solutions";
else
return "No solution";
return "x="+num/x;
}
} | def solveEquation(self, equation: str) -> str:
""" O(N)TS """
x, y, p = 0, 0, 1
for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation):
g = i.group()
if g == '=':
p = -1
elif g[-1] == 'x':
x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))
else:
y += -p * int(g)
if x == 0 == y:
return 'Infinite solutions'
elif x == 0:
return "No solution"
return f'x={y // x}' | def solveEquation(self, equation: str) -> str:
""" O(N)TS """
x, y, p = 0, 0, 1
for i in re.finditer(r"=|[+-]?\d*x|[+-]?\d+", equation):
g = i.group()
if g == '=':
p = -1
elif g[-1] == 'x':
x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))
else:
y += -p * int(g)
if x == 0 == y:
return 'Infinite solutions'
elif x == 0:
return "No solution"
return f'x={y // x}' | Solve the Equation |
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
Note that an integer point is a point that has integer coordinates.
Implement the Solution class:
Solution(int[][] rects) Initializes the object with the given rectangles rects.
int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.
Example 1:
Input
["Solution", "pick", "pick", "pick", "pick", "pick"]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
Output
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]
Explanation
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]
Constraints:
1 <= rects.length <= 100
rects[i].length == 4
-109 <= ai < xi <= 109
-109 <= bi < yi <= 109
xi - ai <= 2000
yi - bi <= 2000
All the rectangles do not overlap.
At most 104 calls will be made to pick.
| class Solution:
"""
1 <= rects.length <= 100
rects[i].length == 4
-10^9 <= ai < xi <= 10^9
-10^9 <= bi < yi <= 10^9
xi - ai <= 2000
yi - bi <= 2000
All the rectangles do not overlap.
At most 10^4 calls will be made to pick.
"""
def __init__(self, rects: List[List[int]]):
self.rects = rects
self.n_range = list(range(len(self.rects)))
self.weights = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]
def pick(self) -> List[int]:
rect = self.rects[choices(self.n_range, self.weights, k=1)[0]]
return [randint(rect[0], rect[2]), randint(rect[1], rect[3])]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick() | class Solution {
int[][] rects;
TreeMap<Integer, Integer> weightedRectIndex = new TreeMap<>();
int nPoints = 0;
Random rng = new Random();
public Solution(int[][] rects) {
this.rects = rects;
int index = 0;
for (int[] rect : rects) {
// inserts cumulative weight key pointing to rectangle index
weightedRectIndex.put(nPoints, index++);
nPoints += width(rect) * height(rect);
}
}
public int[] pick() {
// generates random point within total weight
int point = rng.nextInt(nPoints);
// finds appropriate rectangle
var entry = weightedRectIndex.floorEntry(point);
// find point within the current rectangle
int rectPoint = point - entry.getKey();
int[] rect = rects[entry.getValue()];
return new int[]{
rect[0] + rectPoint % width(rect),
rect[1] + rectPoint / width(rect)};
}
private int width(int[] rect) {
return rect[2] - rect[0] + 1;
}
private int height(int[] rect) {
return rect[3] - rect[1] + 1;
}
} | class Solution {
public:
vector<int> prefix_sum;
vector<vector<int>> rects_vec;
int total = 0;
Solution(vector<vector<int>>& rects) {
int cur = 0;
for (int i = 0; i < rects.size(); ++i) {
cur += (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1);
prefix_sum.push_back(cur);
}
rects_vec = rects;
total = cur;
}
vector<int> pick() {
int l = 0, r = prefix_sum.size() - 1, mid = 0;
int rand_num = rand();
int target = (rand_num % total) + 1;
while (l <= r) {
mid = l + (r - l) / 2;
if (prefix_sum[mid] < target) l = mid + 1;
else r = mid - 1;
}
return {rand_num % (rects_vec[l][2] - rects_vec[l][0] + 1) + rects_vec[l][0],
rand_num % (rects_vec[l][3] - rects_vec[l][1] + 1) + rects_vec[l][1]};
}
}; | /**
/**
* @param {number[][]} rects
*/
var Solution = function(rects) {
this.rects = rects;
this.map = {};
this.sum = 0;
// we put in the map the number of points that belong to each rect
for(let i in rects) {
const rect = rects[i];
// the number of points can be picked in this rectangle
this.sum += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1);
this.map[this.sum] = i;
}
this.keys = Object.keys(this.map);
};
/**
* @return {number[]}
*/
Solution.prototype.pick = function() {
// random point pick between [1, this.sum]
const randomPointPick = Math.floor(Math.random() * this.sum) + 1;
// we look for the randomPointPick in the keys of the map
let pointInMap;
// the keys exists in map
if(this.map[randomPointPick]) pointInMap = randomPointPick;
// the key is the first in the map (we do this check before doing binary search because its out of boundery)
else if(randomPointPick < this.keys[0]) pointInMap = this.keys[0];
let high = this.keys.length;
let low = 1;
// binary search to find the closest key that bigger than randomPointPick
while(low <= high && !pointInMap) {
const mid = Math.floor((low + (high-low)/2));
if(randomPointPick > this.keys[mid-1] && randomPointPick < this.keys[mid]) {
pointInMap = this.keys[mid];
break;
} else if (randomPointPick > this.keys[mid]){
low = mid+1;
} else {
high = mid-1;
}
}
// we have the point, now we can get which rect belong to that point
const pointInRects = this.map[pointInMap];
const chosen = this.rects[pointInRects];
const rightX = chosen[2];
const leftX = chosen[0];
const topY = chosen[3];
const bottomY = chosen[1];
const pickX = Math.floor(Math.random() * (rightX-leftX+1)) + leftX;
const pickY = Math.floor(Math.random() * (topY-bottomY+1)) + bottomY;
return [pickX, pickY]
};
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(rects)
* var param_1 = obj.pick()
*/ | Random Point in Non-overlapping Rectangles |
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
All the visited cells of the path are 0.
All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
Example 1:
Input: grid = [[0,1],[1,0]]
Output: 2
Example 2:
Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] is 0 or 1
| '''
from collections import deque
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
L=len(grid)
def generate_next_state(i,j):
return [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]
def valid_state(states):
res=[]
for (i,j) in states:
if i>L-1:continue
if i<0:continue
if j<0:continue
if j>L-1:continue
if grid[i][j]==0:
res.append((i,j))
return res
queue=deque([(0,0)])
res=1
while queue:
for _ in range(len(queue)):
i,j=queue.popleft()
val=grid[i][j]
grid[i][j]=1
if not val:
if i==L-1 and j==L-1:
return res
next_state=valid_state(generate_next_state(i,j))
for (ki,kj) in next_state:
queue.append((ki,kj))
res+=1
return -1
''' | class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int m = grid.length, n = grid[0].length;
boolean [][] visited = new boolean [m][n];
int [] up = {0, 0, 1, -1, 1, 1, -1, -1};
int [] down = {-1, 1, 0, 0, -1, 1, -1, 1};
/*
if top-left is 1 or bottom-right is 1
we will return -1
*/
if(grid[0][0] == 1 || grid[m-1][n-1] == 1)
return -1;
ArrayDeque<int []> q = new ArrayDeque<>();
/*
we will add top-left to the deque
ans steps as 1
*/
q.add(new int[]{0,0,1});
while(q.size() > 0){
int [] tmp = q.removeFirst();
int x = tmp[0];
int y = tmp[1];
int steps = tmp[2];
visited[x][y] = true;
if(x == m-1 && y == n-1)
return steps;
for(int i = 0; i < 8; i++){
int x_new = x + up[i];
int y_new = y + down[i];
/*
we will traverse level wise using bfs
and those which can be directly reach via
current level will be considered as the same
level and we will return the level of
bottom-right as result
*/
if(x_new >= 0 && x_new < m && y_new >= 0 && y_new < n){
if(visited[x_new][y_new] == false && grid[x_new][y_new] == 0){
q.add(new int[]{x_new,y_new,steps+1});
visited[x_new][y_new] = true;
}
}
}
}
return -1;
}
} | class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int m = grid.size(),n = grid[0].size();
if(grid[0][0]!=0 || grid[m-1][n-1]!=0) return -1;
vector<vector<int>> dist(m,vector<int>(n,INT_MAX));
int ans = INT_MAX;
queue<pair<int,int>> q;
dist[0][0]=1;
q.push({0,0});
int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
while(!q.empty()){
auto curr = q.front();
q.pop();
for(int i = 0;i<8;i++){
int newi = curr.first + dir[i][0];
int newj = curr.second + dir[i][1];
if(newi>=0 && newi<m && newj>=0 && newj<n && grid[newi][newj]==0){
if(dist[newi][newj]>dist[curr.first][curr.second]+1){
dist[newi][newj] = dist[curr.first][curr.second]+1;
q.push({newi,newj});
}
}
}
}
return dist[m-1][n-1]==INT_MAX?-1:dist[m-1][n-1];
}
}; | /**
* @param {number[][]} grid
* @return {number}
*/
var shortestPathBinaryMatrix = function(grid) {
const n = grid.length
const directions = [
[-1, 0], [-1, 1], [0, 1], [1, 1],
[1, 0], [1, -1], [0, -1], [-1, -1]
]
const visited = []
const distance = []
const predecessor = []
const queue = []
for (let i = 0; i < n; i++ ) {
visited.push(Array.from({length: n}, (v, i) => false))
distance.push(Array.from({length: n}, (v, i) => 9999))
predecessor.push(Array.from({length: n}, (v, i) => null))
}
const startIndex = [0, 0]
if(grid[startIndex[0]][startIndex[1]] !== 0) {
return -1
}
queue.push(startIndex)
distance[startIndex[0]][startIndex[1]] = 1
while(queue.length > 0) {
const current = queue.shift()
visited[current[0]][current[1]] = true
if (current[0] === n-1 && current[1] === n-1) {
break
}
directions.forEach(dir => {
const x = current[0] + dir[0]
const y = current[1] + dir[1]
if (x < 0 || y < 0 || x >= n || y >= n) {
return
}
if (
grid[x][y] === 0 &&
visited[x][y] === false &&
distance[x][y] > distance[current[0]][current[1]] + 1
) {
distance[x][y] = distance[current[0]][current[1]] + 1
predecessor[x][y] = current
queue.push([x, y])
}
})
}
console.log(distance)
console.log(visited)
console.log(predecessor)
return distance[n-1][n-1] >= 999 ?
-1 : distance[n-1][n-1]
}; | Shortest Path in Binary Matrix |
You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.
Return the generated matrix.
Example 1:
Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
Explanation: The diagram above shows how the values are printed in the matrix.
Note that the remaining spaces in the matrix are filled with -1.
Example 2:
Input: m = 1, n = 4, head = [0,1,2]
Output: [[0,1,2,-1]]
Explanation: The diagram above shows how the values are printed from left to right in the matrix.
The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 105
1 <= m * n <= 105
The number of nodes in the list is in the range [1, m * n].
0 <= Node.val <= 1000
| class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
num = m * n
res = [[-1 for j in range(n)] for i in range(m)]
x, y = 0, 0
dx, dy = 1, 0
while head:
res[y][x] = head.val
if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m or res[y+dy][x+dx] != -1:
dx, dy = -dy, dx
x = x + dx
y = y + dy
head = head.next
return res | class Solution {
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] ans=new int[m][n];
for(int[] arr:ans){
Arrays.fill(arr,-1);
}
int rowBegin=0;
int rowEnd=m-1;
int columnBegin=0;
int columnEnd=n-1;
ListNode cur=head;
while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){
for(int i=columnBegin;i<=columnEnd && cur!=null;i++){
if(cur!=null){
ans[rowBegin][i]=cur.val;
}
cur=cur.next;
}
rowBegin++;
for(int i=rowBegin;i<=rowEnd && cur!=null;i++){
if(cur!=null){
ans[i][columnEnd]=cur.val;
}
cur=cur.next;
}
columnEnd--;
if(rowBegin<=rowEnd){
for(int i=columnEnd;i>=columnBegin && cur!=null;i--){
if(cur!=null){
ans[rowEnd][i]=cur.val;
}
cur=cur.next;
}
}
rowEnd--;
if(columnBegin<=columnEnd){
for(int i=rowEnd;i>=rowBegin && cur!=null;i--){
if(cur!=null){
ans[i][columnBegin]=cur.val;
}
cur=cur.next;
}
}
columnBegin++;
}
return ans;
}
} | class Solution {
public:
vector<vector<int>> spiralMatrix(int n, int m, ListNode* head)
{
// Create a matrix of n x m with values filled with -1.
vector<vector<int>> spiral(n, vector<int>(m, -1));
int i = 0, j = 0;
// Traverse the matrix in spiral form, and update with the values present in the head list.
// If head reacher NULL pointer break out from the loop, and return the spiral matrix.
while (head != NULL)
{
if (j < m)
{
while (head != NULL && j < m && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
j++;
}
if (head == NULL)
break;
i++;
j--;
}
if (i < n)
{
while (head != NULL && i < n && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
i++;
}
i--;
j--;
}
if (j >= 0)
{
while (head != NULL && j >= 0 && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
j--;
}
j++;
i--;
}
if (i >= 0)
{
while (head != NULL && i >= 0 && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
i--;
}
i++;
j++;
}
n--;
m++;
}
// Rest values are itself -1.
return spiral;
}
}; | var spiralMatrix = function(m, n, head) {
var matrix = new Array(m).fill().map(()=> new Array(n).fill(-1))
var row=0, col=0;
var direction="right";
while(head)
{
matrix[row][col]=head.val;
if(direction=="right")
{
if(col+1 == n || matrix[row][col+1] != -1)
{
direction="down"
row++;
}
else
col++
}
else if(direction=="down")
{
if(row+1 == m || matrix[row+1][col] != -1)
{
direction="left"
col--;
}
else
row++
}
else if(direction=="left")
{
if(col == 0 || matrix[row][col-1] != -1)
{
direction="up"
row--;
}
else
col--
}
else if(direction=="up")
{
if(row == 0 || matrix[row-1][col] != -1)
{
direction="right"
col++;
}
else
row--
}
head = head.next;
}
return matrix;
}; | Spiral Matrix IV |
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 104
s contains English letters (upper-case and lower-case), digits, and spaces ' '.
There is at least one word in s.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
| class Solution:
def split(self, s: str, delimiter=" ") -> List[str]:
start, end = 0, 0
res = []
for ch in s:
if ch == delimiter:
if start == end:
start += 1
else:
res.append(s[start:end])
start = end + 1
end += 1
if start != end:
res.append(s[start:end])
return res
def reverse_list(self, ll: List[str]) -> List[str]:
l, r = 0, len(ll) - 1
while l < r:
ll[l], ll[r] = ll[r], ll[l]
l += 1
r -= 1
return ll
def reverseWords(self, s: str) -> str:
# split first
splitted_str_list = self.split(s)
# reverse splitted list
reversed_str_list = self.reverse_list(splitted_str_list)
# join an return
return " ".join(reversed_str_list) | class Solution {
public String reverseWords(String s) {
String[] arr = s.replaceAll("\\s{2,}", " ").split(" ");
// splitting based on while spaces by replaceing spaces by single gap
int n = arr.length;
String temp = "";
for(int i =0;i<n/2;i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1]=temp;
}
String result ="";
for(int i =0;i<n-1;i++){
result+=arr[i]+" ";
}
result+=arr[n-1];
return result.trim();
}
} | class Solution {
public:
string reverseWords(string s) {
int i=0;
string res = "";
while(i<s.length())
{
while(i<s.length() && s[i]==' ')
i++;
if(i>=s.length())
break;
int j=i+1;
while(j<s.length() && s[j]!=' ')
j++;
string tmp = s.substr(i,j-i);
if(res.length()==0)
{
res = tmp;
}
else
{
res = tmp + " " + res;
}
i=j+1;
}
return res;
}
}; | var reverseWords = function(s) {
return s.split(" ").filter(i => i).reverse().join(" ");
}; | Reverse Words in a String |
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).
You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.
Return the maximum k you can choose such that p is still a subsequence of s after the removals.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Example 1:
Input: s = "abcacb", p = "ab", removable = [3,1,0]
Output: 2
Explanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".
"ab" is a subsequence of "accb".
If we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.
Hence, the maximum k is 2.
Example 2:
Input: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
Output: 1
Explanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".
"abcd" is a subsequence of "abcddddd".
Example 3:
Input: s = "abcab", p = "abc", removable = [0,1,2,3,4]
Output: 0
Explanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.
Constraints:
1 <= p.length <= s.length <= 105
0 <= removable.length < s.length
0 <= removable[i] < s.length
p is a subsequence of s.
s and p both consist of lowercase English letters.
The elements in removable are distinct.
| class Solution:
def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
def check(m):
i = j = 0
remove = set(removable[:m+1])
while i < len(s) and j < len(p):
if i in remove:
i += 1
continue
if s[i] == p[j]:
i += 1
j += 1
else:
i += 1
return j == len(p)
# search interval is [lo, hi)
lo, hi = 0, len(removable)+1
while lo < hi:
mid = (lo + hi) // 2
if check(mid):
lo = mid + 1
else:
hi = mid
return lo if lo < len(removable) else lo-1 | class Solution {
public int maximumRemovals(String s, String p, int[] removable) {
int left = 0, right = removable.length;
while (left < right) {
int middle = (right + left + 1) / 2;
String afterRemoval = remove(s, removable, middle);
if (isSubsequence(p, afterRemoval, p.length(), afterRemoval.length()))
left = middle;
else
right = middle - 1;
}
return left;
}
private String remove(String s, int[] removable, int k) {
char[] symbols = s.toCharArray();
for (int i = 0; i < k; i++) {
symbols[removable[i]] = Character.MIN_VALUE;
}
return String.valueOf(symbols);
}
private boolean isSubsequence(String subSequence, String word, int subSequenceChar, int wordChar) {
if (subSequenceChar == 0) return true;
if (wordChar == 0) return false;
if (subSequence.charAt(subSequenceChar - 1) == word.charAt(wordChar - 1))
return isSubsequence(subSequence, word, subSequenceChar - 1, wordChar - 1);
return isSubsequence(subSequence, word, subSequenceChar, wordChar - 1);
}
} | class Solution {
public:
bool isSubSequence(string str1, string str2){
int j = 0,m=str1.size(),n=str2.size();
for (int i = 0; i < n && j < m; i++)
if (str1[j] == str2[i])
j++;
return (j == m);
}
int maximumRemovals(string s, string p, vector<int>& removable) {
string copy=s;
int left = 0, right =removable.size();
while (left <= right) {
int mid = (left+right)/2;
for(int i=0;i<mid;i++) copy[removable[i]]='*';
if (isSubSequence(p,copy))
//if p is subsequence of string after mid number of removals then we should look for if it's possible to remove more characters
left = mid+1;
else {
//if p is not a subsequence of string it means that we have certainly removed more characters from string
//so we must decrease our size of removal characters and hence we add all characters we removed earlier.
for(int i=0;i<mid;i++) copy[removable[i]] = s[removable[i]];
right = mid-1;
}
}
return right;
}
}; | var maximumRemovals = function(s, p, removable) {
let arr = s.split('');
const stillFunctions = (k) => {
let result = [...arr];
for(let i = 0; i < k; i++) {
result[removable[i]] = '';
}
const isSubset = () => {
let idx = 0;
for(let c = 0; c < p.length; c++) {
if(idx > result.length) return false;
const next = result.indexOf(p[c], idx);
if(next === -1) {
return false;
}
idx = next + 1;
}
return true;
}
return isSubset();
}
let left = 0;
let right = removable.length;
while(left < right) {
// Need to round up the midpoint since we are returning operation LENGTH i.e. ops+1
const mid = Math.ceil((left+right) / 2);
if(!stillFunctions(mid)) {
right = mid -1;
} else {
left = mid;
}
}
return left;
}; | Maximum Number of Removable Characters |
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
Any student is eligible for an attendance award if they meet both of the following criteria:
The student was absent ('A') for strictly fewer than 2 days total.
The student was never late ('L') for 3 or more consecutive days.
Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.
Example 1:
Input: n = 2
Output: 8
Explanation: There are 8 records with length 2 that are eligible for an award:
"PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"
Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2).
Example 2:
Input: n = 1
Output: 3
Example 3:
Input: n = 10101
Output: 183236316
Constraints:
1 <= n <= 105
| class Solution:
def checkRecord(self, n: int) -> int:
if n == 1:
return 3
if n==2:
return 8
"""
Keep track of last 2 digits
ways to get ll = last combinations ending with p,l (l,l not allowed)
ways to get lp = last combinations ending with l,p + p,l
and so on
finally account for adding A by the usual loop.
"""
combos_l_l = 1
combos_l_p = 1
combos_p_l = 1
combos_p_p = 1
MOD = 1000000007
f = [0]*(n+1)
f[0] = 1
f[1] = 2
f[2] = 4
for i in range(2, n):
combos_l_l_new = combos_p_l
combos_l_p_new = combos_l_l + combos_p_l
combos_p_l_new = combos_l_p + combos_p_p
combos_p_p_new = combos_l_p + combos_p_p
combos_l_l, combos_l_p, combos_p_l, combos_p_p = combos_l_l_new%MOD, combos_l_p_new%MOD, combos_p_l_new%MOD, combos_p_p_new %MOD
f[i+1] = (combos_l_l + combos_l_p + combos_p_l + combos_p_p)%MOD
total = f[-1]
# print(f)
for i in range(1,n+1):
total += (f[i-1]*f[n-i])
return ( total ) % (MOD)
| class Solution {
int mod=1000000000+7;
public int checkRecord(int n) {
int[][][] cache=new int[n+1][2][3];
for(int i=0; i<=n; i++){
for(int j=0; j<2; j++){
for(int k=0; k<3; k++)cache[i][j][k]=-1;
}
}
return populate(n, 0, 1, 2, cache);
}
public int populate(int n, int ptr, int aCount, int lCount, int[][][] cache){
if(ptr>=n)return 1;
if(cache[ptr][aCount][lCount]!=-1)return cache[ptr][aCount][lCount];
long count=0;
// Late
if(lCount>0){
count=populate(n, ptr+1, aCount, lCount-1, cache)%mod;
}
// Present
count=(count+populate(n, ptr+1, aCount, 2, cache))%mod;
// Absent
if(aCount==1)count=(count+populate(n, ptr+1, aCount-1, 2, cache))%mod;
cache[ptr][aCount][lCount]=(int)(count%mod);
return cache[ptr][aCount][lCount];
}
} | class Solution {
public:
int mod = 1e9+7;
int dp[100001][10][10];
int recur(int abs,int late,int n){
if(abs > 1){
return 0;
}
if(late >= 3){
return 0;
}
if(n == 0){
return 1;
}
if(dp[n][late][abs] != -1) return dp[n][late][abs];
int ans = 0;
ans = (ans%mod + recur(abs+1,0,n-1)%mod)%mod;
ans = (ans%mod + recur(abs,late+1,n-1)%mod)%mod;
ans = (ans%mod + recur(abs,0,n-1)%mod)%mod;
//This dp is running from n to 0 and is cut off if
//absent is greater than 1 or late of consecutive is greater than
//equal to 3.
//Here in the first recursion i.e line 19 & line 23 late is made 0
//to signify that the consecutive lates are stopped.***
return dp[n][late][abs] = ans;
}
int checkRecord(int n) {
for(int i=0;i<=100000;i++){
for(int j=0;j<10;j++){
for(int k=0;k<10;k++){
dp[i][j][k] = -1;
}
}
}
return recur(0,0,n);
}
}; | /**
* @param {number} n
* @return {number}
*/
var checkRecord = function(n) {
/**
* P(n) = A(n - 1) + P(n - 1) + L(n - 1), n ≥ 2.
* L(n) = A(n - 1) + P(n - 1) + A(n - 2) + P(n - 2), n ≥ 3.
* A(n) = A(n - 1) + A(n - 2) + A(n - 3), n ≥ 4.
*/
const m = 1000000007;
const P = Array(n);
const A = Array(n);
const L = Array(n);
A[0] = 1;
L[0] = 1;
P[0] = 1;
A[1] = 2;
A[2] = 4;
L[1] = 3;
for (let i = 1; i < n; i++) {
P[i] = (A[i - 1] + L[i - 1] + P[i - 1]) % m;
if (i >= 3) A[i] = (A[i - 1] + A[i - 2] + A[i - 3]) % m;
if (i >= 2) L[i] = (A[i - 1] + P[i - 1] + A[i - 2] + P[i - 2]) % m;
}
return (P[n - 1] + A[n - 1] + L[n - 1]) % m;
}; | Student Attendance Record II |
Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
Example 1:
Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)
Constraints:
0 <= key <= 106
At most 104 calls will be made to add, remove, and contains.
| class MyHashSet:
def __init__(self):
self.hash_list = [0]*10000000
def add(self, key: int) -> None:
self.hash_list[key]+=1
def remove(self, key: int) -> None:
self.hash_list[key] = 0
def contains(self, key: int) -> bool:
if self.hash_list[key] > 0:
return True
return False | class MyHashSet {
ArrayList<LinkedList<Integer>> list;
int size = 100;
public MyHashSet() {
list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(new LinkedList<Integer>());
}
}
public int hash(int key) {
return key % list.size();
}
public int search(int key) {
int i = hash(key);
LinkedList<Integer> temp = list.get(i);
int ans = -1;
for (int j = 0; j < temp.size(); j++) {
if (key == temp.get(j)) {
return j;
}
}
return ans;
}
public void add(int key) {
if (search(key) == -1) {
int i = hash(key);
list.get(i).add(key);
}
}
public void remove(int key) {
if (search(key) != -1) {
int i = hash(key);
list.get(i).remove(Integer.valueOf(key));
}
}
public boolean contains(int key) {
return search(key) != -1;
}
} | class MyHashSet {
vector<int> v;
public:
MyHashSet() {
}
void add(int key) {
auto it = find(v.begin(), v.end(), key);
if(it == v.end()){
v.push_back(key);
}
}
void remove(int key) {
auto it = find(v.begin(), v.end(), key);
if(it != v.end()){
v.erase(it);
}
}
bool contains(int key) {
return find(v.begin(), v.end(), key) != v.end();
}
}; | var MyHashSet = function() {
// Really you should just
// Make your own object, but instead
// we have attached ourself to the
// `this` object which then becomes our hashmap.
// What you should instead do is this:
// this.hash_map = {}
// And then update our following functions
};
MyHashSet.prototype.add = function(key) {
// Constant Time
// Linear Space | To the size of the input key
// You can access objects using array notation
this[key] = null;
};
MyHashSet.prototype.remove = function(key) {
// Constant Time
// Constant Space
// You can access objects using array notation
// Here we use the delete keyword.
delete this[key]
};
MyHashSet.prototype.contains = function(key) {
// Constant Time
// Constant Space
// This just asks if the property exists
return this.hasOwnProperty(key)
}; | Design HashSet |
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.
For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
Return the minimum possible sum of new1 and new2.
Example 1:
Input: num = 2932
Output: 52
Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.
The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.
Example 2:
Input: num = 4009
Output: 13
Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc.
The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.
Constraints:
1000 <= num <= 9999
| class Solution:
def minimumSum(self, num: int) -> int:
s=list(str(num))
s.sort()
return int(s[0]+s[2])+int(s[1]+s[3]) | class Solution
{
public int minimumSum(int num)
{
int[] dig = new int[4]; // For each digit
int cur = 0;
while(num > 0) // Getting each digit
{
dig[cur++] = num % 10;
num /= 10;
}
Arrays.sort(dig); // Ascending order
int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit
int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit
return num1 + num2;
}
} | class Solution{
public:
int minimumSum(int num){
string s = to_string(num);
sort(s.begin(), s.end());
int res = (s[0] - '0' + s[1] - '0') * 10 + s[2] - '0' + s[3] - '0';
return res;
}
}; | var minimumSum = function(num) {
let numbers = []
for(let i = 0; i<4; i++){
numbers.push(~~num % 10)
num /= 10
}
const sorted = numbers.sort((a,b) => b - a)
return sorted[0] + sorted[1] + (10 *( sorted[2] + sorted[3]))
}; | Minimum Sum of Four Digit Number After Splitting Digits |
A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Example 2:
Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-106 <= arr[i] <= 106
| class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
check = arr[0] - arr[1]
for i in range(len(arr)-1):
if arr[i] - arr[i+1] != check:
return False
return True | class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
if(arr.length < 1)
return false;
Arrays.sort(arr);
int diff = arr[1]-arr[0];
for(int i=1;i<arr.length-1;i++){
if(arr[i+1]-arr[i]!=diff){
return false;
}
}
return true;
}
} | class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
sort(arr.begin() , arr.end());
int diff = arr[1] - arr[0];
for(int i=1;i<arr.size();i++){
if(diff != arr[i] - arr[i-1]){
return false;
}
}
return true;
}
}; | var canMakeArithmeticProgression = function(arr) {
arr.sort(function(a,b){return a-b});
var dif = arr[1] - arr[0];
for(var i=2;i<arr.length;i++){
if(arr[i]-arr[i-1] !== dif){
return false;
}
}
return true;
}; | Can Make Arithmetic Progression From Sequence |
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
Constraints:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of nums are unique.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
| class Solution:
def missingNumber(self, nums: List[int]) -> int:
# T.C = O(n) S.C = O(1)
actualsum = 0
currentsum = 0
i = 1
for num in nums:
currentsum += num
actualsum += i
i += 1
return actualsum - currentsum | // Approach 1: Find diff
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = (n * (n + 1)) / 2;
for (int num : nums)
expectedSum -= num;
return expectedSum;
}
}
// Approach 2: XOR
class Solution {
public int missingNumber(int[] nums) {
int xor1 = 0;
for (int i = 1; i <= nums.length; i++)
xor1 = xor1 ^ i;
int xor2 = 0;
for (int num : nums)
xor2 = xor2 ^ num;
return xor1 ^ xor2;
}
}
// Approach 3: Cyclic sort
class Solution {
public int missingNumber(int[] nums) {
int i = 0;
while (i < nums.length) {
if (nums[i] != i && nums[i] < nums.length)
swap(i, nums[i], nums);
else
i += 1;
}
for (int j = 0; j < nums.length; j++) {
if (nums[j] != j)
return j;
}
return nums.length;
}
private void swap(int i, int j, int[] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
} | class Solution {
public:
int missingNumber(vector<int>& nums) {
int n=nums.size();
long sum=n*(n+1)/2;
long temp=0;
for(int i=0;i<n;i++)
{
temp+=nums[i];
}
return sum-temp;
}
}; | var missingNumber = function(nums) {
return ((1 + nums.length)*nums.length/2) - nums.reduce((a,b) => a+b)
}; | Missing Number |
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
m == heights.length
n == heights[r].length
1 <= m, n <= 200
0 <= heights[r][c] <= 105
| class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
# Purpose: find the cells that allow rain flow into the ocean
# Method: DFS
# Intuition: start from each border, check cell and neb, if OK, append to res
# init: res, vis (pac, atl), ROW, COL
res = []
pac = set()
atl = set()
ROW = len(heights)
COL = len(heights[0])
# top and bottom row
for col in range(COL):
self.dfs(0, col, pac, heights[0][col], heights)
self.dfs(ROW-1, col, atl, heights[ROW-1][col], heights)
# left and right col
for row in range(ROW):
self.dfs(row, 0, pac, heights[row][0], heights)
self.dfs(row, COL-1, atl, heights[row][COL-1], heights)
# append to res
for row in range(ROW):
for col in range(COL):
if (row, col) in pac and (row, col) in atl:
res.append([row, col])
# return
return res
def dfs(self, row, col, vis, prev, heights):
# hard-code definition
try:
cur = heights[row][col]
except:
pass
# inbound, unvisited, increase from ocean
if (0<=row<len(heights) and 0<=col<len(heights[0])) \
and (cur >= prev) \
and ((row, col) not in vis):
# add to visited
vis.add((row, col))
# check nebs
self.dfs(row+1, col, vis, cur, heights)
self.dfs(row-1, col, vis, cur, heights)
self.dfs(row, col+1, vis, cur, heights)
self.dfs(row, col-1, vis, cur, heights) | class Solution {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
if (heights == null) return null;
if (heights.length == 0) return null;
if (heights[0].length == 0) return null;
/** */
boolean [][] po = new boolean[heights.length][heights[0].length];
boolean [][] ao = new boolean[heights.length][heights[0].length];
for (int i = 0; i < heights[0].length; i ++) {
dfs(heights, i, 0, 0, po); // top
dfs(heights, i, heights.length - 1, 0, ao); // bottom
}
for (int i = 0; i < heights.length; i ++) {
dfs(heights, 0, i, 0, po); // left
dfs(heights, heights[0].length - 1, i, 0, ao); // right
}
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < heights.length; i ++) {
for (int j = 0; j < heights[i].length; j ++) {
if (ao[i][j] && po[i][j]) {
ArrayList<Integer> ar = new ArrayList<>();
ar.add(i);
ar.add(j);
ans.add(ar);
}
}
}
return ans;
}
private void dfs(int[][] heights, int x, int y, int h, boolean[][] v) {
if (x < 0 || y < 0 || x >= heights[0].length || y >= heights.length) return;
if (v[y][x] || heights[y][x] < h) return;
v[y][x] = true;
/** left */
dfs(heights, x - 1, y, heights[y][x], v);
/** right */
dfs(heights, x + 1, y, heights[y][x], v);
/** up */
dfs(heights, x, y - 1, heights[y][x], v);
/** down */
dfs(heights, x, y + 1, heights[y][x], v);
}
} | class Solution {
public:
void dfs(vector<vector<int>>& heights,vector<vector<bool>>&v,int i,int j)
{
int m=heights.size();
int n=heights[0].size();
v[i][j]=true;
if(i-1>=0&&v[i-1][j]!=true&&heights[i-1][j]>=heights[i][j])
{
dfs(heights,v,i-1,j);
}
if(i+1<m&&v[i+1][j]!=true&&heights[i+1][j]>=heights[i][j])
{
dfs(heights,v,i+1,j);
}
if(j-1>=0&&v[i][j-1]!=true&&heights[i][j-1]>=heights[i][j])
{
dfs(heights,v,i,j-1);
}
if(j+1<n&&v[i][j+1]!=true&&heights[i][j+1]>=heights[i][j])
{
dfs(heights,v,i,j+1);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
int m=heights.size();
vector<vector<int>>ans;
if(m==0)
{
return ans;
}
int n=heights[0].size();
if(n==0)
{
return ans;
}
vector<vector<bool>>pa(m,vector<bool>(n));
vector<vector<bool>>at(m,vector<bool>(n));
for(int i=0;i<m;i++)
{
dfs(heights,pa,i,0);
dfs(heights,at,i,n-1);
}
for(int j=0;j<n;j++)
{
dfs(heights,pa,0,j);
dfs(heights,at,m-1,j);
}
for(int i=0;i<m;i++)
{
vector<int>p;
for(int j=0;j<n;j++)
{
if(pa[i][j]&&at[i][j])
{
p.push_back(i);
p.push_back(j);
ans.push_back(p);
p.clear();
}
}
}
return ans;
}
}; | `/**
* @param {number[][]} heights
* @return {number[][]}
*/
var pacificAtlantic = function(heights) {
let atlantic = new Set();
let pacific = new Set();
let rows = heights.length;
let cols = heights[0].length;
for (let c = 0; c < cols; c++) {
explore(heights, 0, c, pacific, heights[0][c]); // dfs from top row
explore(heights, rows - 1, c, atlantic, heights[rows - 1][c]); // dfs from bottom row
}
for (let r = 0; r < rows; r++) {
explore(heights, r, 0, pacific, heights[r][0]); // dfs from left most column
explore(heights, r, cols - 1, atlantic, heights[r][cols - 1]); // dfs from right most column
}
// check if water can flow to both atlantic and pacific ocean.
let res = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let pos = r + ',' + c;
if (atlantic.has(pos) && pacific.has(pos)) {
res.push([r, c]);
}
}
}
return res;
};
function explore(heights, r, c, visited, prevHeight) {
let rowInbound = 0 <= r && r < heights.length;
let colInbound = 0 <= c && c < heights[0].length;
if (!rowInbound || !colInbound) return;
// height must be higher than prev height. water can only flow downwards not upwards. duh.
// if it's the first value then it's just the same value so it's not less than so it will not return.
if (heights[r][c] < prevHeight) return;
let pos = r + ',' + c;
if (visited.has(pos)) return;
visited.add(pos)
explore(heights, r + 1, c, visited, heights[r][c]) // below
explore(heights, r - 1, c, visited, heights[r][c]) // above
explore(heights, r, c + 1, visited, heights[r][c]) // right
explore(heights, r, c - 1, visited, heights[r][c]) // left
}` | Pacific Atlantic Water Flow |
You are given a 0-indexed string num of length n consisting of digits.
Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.
Example 1:
Input: num = "1210"
Output: true
Explanation:
num[0] = '1'. The digit 0 occurs once in num.
num[1] = '2'. The digit 1 occurs twice in num.
num[2] = '1'. The digit 2 occurs once in num.
num[3] = '0'. The digit 3 occurs zero times in num.
The condition holds true for every index in "1210", so return true.
Example 2:
Input: num = "030"
Output: false
Explanation:
num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
num[2] = '0'. The digit 2 occurs zero times in num.
The indices 0 and 1 both violate the condition, so return false.
Constraints:
n == num.length
1 <= n <= 10
num consists of digits.
| from collections import Counter
class Solution:
def digitCount(self, num: str) -> bool:
d = Counter(num)
for i in range(len(num)):
if int(num[i])!=d.get(str(i), 0):
return False
return True | class Solution {
public boolean digitCount(String num) {
int[] freqArr = new int[10]; // n = 10 given in constraints;
for(char ch : num.toCharArray()){
freqArr[ch-'0']++;
}
for(int i=0;i<num.length();i++){
int freq = num.charAt(i)-'0'; //freq of each indexValue;
freqArr[i] = freqArr[i] - freq;
}
for(int i=0;i<10;i++){
if(freqArr[i]!=0){
return false;
}
}
return true;
}
} | class Solution {
public:
bool digitCount(string num) {
unordered_map<int,int> mpp;
int n= num.length();
for(auto it:num){
int x = it - '0';
mpp[x]++; // Store the frequency of the char as a number
}
for(int i=0;i<n;i++){
int x = num[i] - '0'; // get the char as number
if(mpp[i] != x) // f the number is not equal to its frequency we return false
return false;
}
return true;
}
}; | var digitCount = function(num) {
const res = [...num].filter((element, index) => {
const reg = new RegExp(index, "g");
const count = (num.match(reg) || []).length;
return Number(element) === count
})
return res.length === num.length
}; | Check if Number Has Equal Digit Count and Digit Value |
You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return the reformatted string or return an empty string if it is impossible to reformat the string.
Example 1:
Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.
Example 3:
Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.
| class Solution:
def reformat(self, s: str) -> str:
# Store the alphabets and the numerics from the string in a seperat arrays
alpha = []
num = []
# Initiate a res variable to store the resultant string
res = ''
for i in s:
if i.isalpha():
alpha.append(i)
else:
num.append(i)
# It's not possible to create a permutation if the absolute difference b/w len(alpha) and len(num) > 1.
if abs(len(alpha)-len(num)) > 1: return ''
# Use Zip to create list of tuples.
# For ex:- if alpha = ['a','b'] and num = ['1', '2'] then,
# zip(alpha, num) = [('a', '1'), ('b', '2')]
for ch, n in zip(alpha, num):
res += (ch+n)
if len(alpha) > len(num):
res += alpha[-1]
if len(num) > len(alpha):
res = num[-1] + res
return res | class Solution {
public String reformat(String s) {
List<Character> ch = new ArrayList<>();
List<Character> d = new ArrayList<>();
for(char c : s.toCharArray()){
if(c >= 'a' && c <= 'z')ch.add(c);
else d.add(c);
}
if(Math.abs(d.size() - ch.size()) > 1) return "";
StringBuilder str = new StringBuilder();
for(int i = 0; i < s.length(); i++){
if(!ch.isEmpty() || !d.isEmpty()){
if(ch.size() > d.size())
str.append(appender(ch,d));
else
str.append(appender(d,ch));
}
else{
break;
}
}
return new String(str);
}
public String appender(List<Character> first,List<Character> second){
StringBuilder str = new StringBuilder();
if(!first.isEmpty()){
str.append(first.get(0));
first.remove(0);
}
if(!second.isEmpty()){
str.append(second.get(0));
second.remove(0);
}
return new String(str);
}
} | class Solution {
public:
string reformat(string s) {
string dg,al;
for(auto&i:s)isdigit(i)?dg+=i:al+=i;
if(abs((int)size(dg)-(int)size(al))>1) return "";
int i=0,j=0,k=0;
string ans(size(s),' ');
bool cdg=size(dg)>size(al);
while(k<size(s)){
if(cdg)ans[k++]=dg[i++];
else ans[k++]=al[j++];
cdg=!cdg;
}
return ans;
}
}; | var reformat = function(s) {
let letter=[], digit=[];
for(let i=0; i<s.length; i++){
s[i]>=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]);
}
// impossible to reformat
if(Math.abs(letter.length-digit.length)>=2){return ""}
let i=0, output="";
while(i<letter.length && i<digit.length){
output=output+letter[i]+digit[i]; i++;
}
if(i<letter.length){output=output+letter[i]}; // add in the END
if(i<digit.length){output=digit[i]+output}; // add in the FRONT
return output;
}; | Reformat The String |
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
| class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = maxCount = 0
for i in range(len(nums)):
if nums[i] == 1:
count += 1
else:
maxCount = max(count, maxCount)
count = 0
return max(count, maxCount) | class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int new_max = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1)
{
max++;
}
else{
if(max>new_max){
new_max = max;
}
max = 0;
}
}
if(max<new_max)
return new_max;
else
return max;
}
} | class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums)
{
int curr_count = 0;
int max_count = 0;
int i = 0;
while(i < nums.size())
{
if(nums[i] == 1)
{
curr_count += 1;
if(max_count < curr_count)
max_count = curr_count;
}
else
curr_count = 0;
i++;
}
return max_count;
}
}; | var findMaxConsecutiveOnes = function(nums) {
let count =0
let max =0
for(let i=0; i<nums.length; i ++){
if(nums[i]==1){
count ++
}
if(nums[i]==0 || i==nums.length-1){
max = Math.max(count,max)
count = 0
}
}
return max
}; | Max Consecutive Ones |
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, or false otherwise.
Example 1:
Input: nums = [1,2,2,3]
Output: true
Example 2:
Input: nums = [6,5,4,4]
Output: true
Example 3:
Input: nums = [1,3,2]
Output: false
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
| class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
counter = 0
for i in range(len(nums) - 1):
if nums[i] >= nums[i + 1]:
counter += 1
if counter == len(nums) - 1:
return True
counter = 0
for i in range(len(nums) - 1):
if nums[i] <= nums[i + 1]:
counter += 1
if counter == len(nums) - 1:
return True
return False | class Solution {
public boolean isMonotonic(int[] nums) {
if(nums[0]<nums[nums.length-1]){
for(int i=0;i<nums.length-1;i++){
if(!(nums[i]<=nums[i+1])) return false;
}
}else{
for(int i=0;i<nums.length-1;i++){
if(!(nums[i]>=nums[i+1])) return false;
}
}
return true;
}
} | class Solution {
public:
bool isMonotonic(vector<int>& nums) {
auto i = find_if_not(begin(nums), end(nums), [&](int a) {return a == nums.front();});
auto j = find_if_not(rbegin(nums), rend(nums), [&](int a) {return a == nums.back();});
return is_sorted(--i, end(nums)) or is_sorted(--j, rend(nums));
}
}; | var isMonotonic = function(nums) {
let increasingCount = 0;
let decreasingCount = 0;
for(let i = 1; i < nums.length; i++){
if(nums[i] > nums[i-1]){
increasingCount++;
}else if(nums[i] < nums[i-1]){
decreasingCount++;
}
}
return !(increasingCount && decreasingCount);
}; | Monotonic Array |
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65
Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
Example 2:
Input: nums = [10,20,30,40,50]
Output: 150
Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
Example 3:
Input: nums = [12,17,15,13,10,11,12]
Output: 33
Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
| class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
count=nums[0]
final=nums[0]
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
count+=nums[i]
else:
count=nums[i]
final=max(final,count)
return final | class Solution {
public int maxAscendingSum(int[] nums) {
int res = nums[0],temp = nums[0];
for(int i = 1;i<nums.length;i++){
if(nums[i] > nums[i-1])
temp+=nums[i];
else
temp = nums[i];
res = Math.max(res,temp);
}
return res;
}
} | class Solution {
public:
int maxAscendingSum(vector<int>& nums) {
int max_sum = nums[0], curr = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i-1] < nums[i]) {
curr += nums[i];
}
else {
max_sum = max(max_sum, curr);
curr = nums[i];
}
}
return max(max_sum, curr);
}
}; | var maxAscendingSum = function(nums) {
const subarray = nums.reduce((acc, curr, index) => {
curr > nums[index - 1] ? acc[acc.length - 1] += curr : acc.push(curr);
return acc;
}, []);
return Math.max(...subarray);
}; | Maximum Ascending Subarray Sum |
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.
A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.
The product of a path is defined as the product of all the values in the path.
Return the maximum number of trailing zeros in the product of a cornered path found in grid.
Note:
Horizontal movement means moving in either the left or right direction.
Vertical movement means moving in either the up or down direction.
Example 1:
Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]
Output: 3
Explanation: The grid on the left shows a valid cornered path.
It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.
It can be shown that this is the maximum trailing zeros in the product of a cornered path.
The grid in the middle is not a cornered path as it has more than one turn.
The grid on the right is not a cornered path as it requires a return to a previously visited cell.
Example 2:
Input: grid = [[4,3,2],[7,6,1],[8,8,8]]
Output: 0
Explanation: The grid is shown in the figure above.
There are no cornered paths in the grid that result in a product with a trailing zero.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= grid[i][j] <= 1000
| import numpy as np
class Solution:
def maxTrailingZeros(self, grid: List[List[int]]) -> int:
A = np.array(grid)
def cumdivs(d):
D = sum(A % d**i == 0 for i in range(1, 10))
return D.cumsum(0) + D.cumsum(1) - D
return max(np.minimum(cumdivs(2), cumdivs(5)).max()
for _ in range(4)
if [A := np.rot90(A)]) | class Solution {
public int maxTrailingZeros(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][][] dph = new int[m][n][3];
int[][][] dpv = new int[m][n][3];
int hmax0 = 0;
int vmax0 = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int curr = grid[i][j];
int two = 0;
int five = 0;
if (j >= 1) {
two = dph[i][j-1][1];
five = dph[i][j-1][2];
}
while (curr > 0 && curr % 2 == 0) {
two++;
curr /= 2;
}
while (curr > 0 && curr % 5 == 0) {
five++;
curr /= 5;
}
dph[i][j][1] = two;
dph[i][j][2] = five;
dph[i][j][0] = Math.min(dph[i][j][1], dph[i][j][2]);
}
hmax0 = Math.max(hmax0, dph[i][n-1][0]);
}
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
int curr = grid[i][j];
int two = 0;
int five = 0;
if (i >= 1) {
two = dpv[i-1][j][1];
five = dpv[i-1][j][2];
}
while (curr > 0 && curr % 2 == 0) {
two++;
curr /= 2;
}
while (curr > 0 && curr % 5 == 0) {
five++;
curr /= 5;
}
dpv[i][j][1] = two;
dpv[i][j][2] = five;
dpv[i][j][0] = Math.min(dpv[i][j][1], dpv[i][j][2]);
}
vmax0 = Math.max(vmax0, dpv[m-1][j][0]);
}
int res = Math.max(vmax0, hmax0);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int otwo = dph[i][j][1];
int ofive = dph[i][j][2];
int res1 = 0;
if (i >= 1) {
int ntwo = otwo + dpv[i-1][j][1];
int nfive = ofive + dpv[i-1][j][2];
res1 = Math.min(ntwo, nfive);
}
int res2 = 0;
if (i < m - 1) {
int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];
int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];
res2 = Math.min(ntwo, nfive);
}
res = Math.max(res, res1);
res = Math.max(res, res2);
}
for (int j = n - 1; j >= 0; j--) {
int otwo = 0;
int ofive = 0;
if (j >= 1) {
otwo = dph[i][n-1][1] - dph[i][j-1][1];
ofive = dph[i][n-1][2] - dph[i][j-1][2];
} else {
otwo = dph[i][n-1][1];
ofive = dph[i][n-1][2];
}
int res1 = 0;
if (i >= 1) {
int ntwo = otwo + dpv[i-1][j][1];
int nfive = ofive + dpv[i-1][j][2];
res1 = Math.min(ntwo, nfive);
}
int res2 = 0;
if (i < m - 1) {
int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];
int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];
res2 = Math.min(ntwo, nfive);
}
res = Math.max(res, res1);
res = Math.max(res, res2);
}
}
return res;
}
} | array<int, 2> operator+(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] + r[0], l[1] + r[1] }; }
array<int, 2> operator-(const array<int, 2> &l, const array<int, 2> &r) { return { l[0] - r[0], l[1] - r[1] }; }
int pairs(const array<int, 2> &p) { return min(p[0], p[1]); }
class Solution {
public:
int factors(int i, int f) {
return i % f ? 0 : 1 + factors(i / f, f);
}
int maxTrailingZeros(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), res = 0;
vector<vector<array<int, 2>>> h(m, vector<array<int, 2>>(n + 1)), v(m + 1, vector<array<int, 2>>(n));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
array<int, 2> f25 = { factors(grid[i][j], 2), factors(grid[i][j], 5) };
v[i + 1][j] = v[i][j] + f25;
h[i][j + 1] = h[i][j] + f25;
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
auto v1 = v[i + 1][j], v2 = v[m][j] - v[i][j];
auto h1 = h[i][j], h2 = h[i][n] - h[i][j + 1];
res = max({res, pairs(v1 + h1), pairs(v1 + h2), pairs(v2 + h1), pairs(v2 + h2)});
}
return res;
}
}; | var maxTrailingZeros = function(grid) {
const m = grid.length;
const n = grid[0].length;
const postfixCols = [];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
const num = grid[i][j];
if (postfixCols[j] == null) postfixCols[j] = { 2: 0, 5: 0 };
postfixCols[j]["2"] += getCount(num, 2);
postfixCols[j]["5"] += getCount(num, 5);
}
}
const prefixCols = [];
for (let j = 0; j < n; ++j) {
prefixCols[j] = { 0: 0, 2: 0, 5: 0 };
}
let maxZeros = 0;
for (let i = 0; i < m; ++i) {
const postfixRow = { 0: 0, 2: 0, 5: 0 };
for (let j = n - 1; j >= 0; --j) {
const num = grid[i][j];
postfixRow["2"] += getCount(num, 2);
postfixRow["5"] += getCount(num, 5);
}
let prefixRow = { 0: 0, 2: 0, 5: 0 };
for (let j = 0; j < n; ++j) {
const num = grid[i][j];
const twoCount = getCount(num, 2);
const fiveCount = getCount(num, 5);
postfixRow["2"] -= twoCount;
postfixCols[j]["2"] -= twoCount;
postfixRow["5"] -= fiveCount;
postfixCols[j]["5"] -= fiveCount;
// down-right => prefixCol + postfixRow
const downRight = calculateTrailingZeros(prefixCols[j], postfixRow, num);
// down-left => prefixCol + prefixRow
const downLeft = calculateTrailingZeros(prefixCols[j], prefixRow, num);
// up-right => postfixCols + postfixRow
const upRight = calculateTrailingZeros(postfixCols[j], postfixRow, num);
// up-left => postfixCols + prefixRow
const upLeft = calculateTrailingZeros(postfixCols[j], prefixRow, num);
maxZeros = Math.max(maxZeros, downRight, downLeft, upRight, upLeft);
prefixRow["2"] += twoCount;
prefixCols[j]["2"] += twoCount;
prefixRow["5"] += fiveCount;
prefixCols[j]["5"] += fiveCount;
}
}
return maxZeros;
function calculateTrailingZeros(col, row, currNum) {
let twosCount = 0;
let fivesCount = 0;
let zerosCount = 0;
twosCount = row["2"] + col["2"];
fivesCount = row["5"] + col["5"];
twosCount += getCount(currNum, 2);
fivesCount += getCount(currNum, 5);
return Math.min(twosCount, fivesCount);
}
function getCount(num, divisor) {
let count = 0;
while (num % divisor === 0) {
++count;
num /= divisor;
}
return count;
}
}; | Maximum Trailing Zeros in a Cornered Path |
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: []
Example 3:
Input: root = [1,2], targetSum = 0
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
| class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
def dfs(v, path, pathsum):
if not v:
return
path.append(v.val)
pathsum += v.val
if not v.left and not v.right and pathsum == targetSum:
res.append(path[:])
dfs(v.left, path, pathsum)
dfs(v.right, path, pathsum)
path.pop()
dfs(root, [], 0)
return res | class Solution
{
public List<List<Integer>> pathSum(TreeNode root, int targetSum)
{
List<List<Integer>> ans = new ArrayList<>();
pathSum(root, targetSum, new ArrayList<>(), ans);
return ans;
}
public void pathSum(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> ans)
{
if(root == null)
return;
path.add(root.val);
if(root.left == null && root.right == null && targetSum == root.val)//leaf node that completes path
{
ans.add(new ArrayList(path));// we use new ArrayList because if we don't the originaly List is added which is mutable, if we add a copy that's not mutable.
}
else
{
pathSum(root.left, targetSum-root.val, path, ans);
pathSum(root.right, targetSum-root.val, path, ans);
}
path.remove(path.size()-1); //removal of redundant nodes
}
} | /**
* 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:
vector<vector<int>> v;
void helper(vector<int>& t, int target, TreeNode* root){
if(root==NULL){
return;
}
if(root->left==NULL&&root->right==NULL&&target==root->val){
t.push_back(root->val);
v.push_back(t);
t.pop_back();
return;
}
target=target-root->val;
t.push_back(root->val);
helper(t,target,root->left);
helper(t,target,root->right);
t.pop_back();
//cout<<root->val<<" "<<target<<endl;
return;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> t;
helper(t,targetSum,root);
return v;
}
}; | var pathSum = function(root, targetSum) {
const paths = [];
function dfs(root, sum, curr = []) {
if (!root) return;
const newCurr = [...curr, root.val];
if (!root.left && !root.right && sum === root.val) return paths.push(newCurr);
dfs(root.left, sum - root.val, newCurr);
dfs(root.right, sum - root.val, newCurr);
}
dfs(root, targetSum);
return paths;
}; | Path Sum II |
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
Constraints:
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
| class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
deltas = [x-y for x, y in zip(gas, cost)]
n = len(deltas)
deltas = deltas + deltas
cursum, curi = 0, 0
maxsum, maxi = 0, 0
for i, delta in enumerate(deltas):
cursum = max(0, cursum + delta)
if cursum == 0:
curi = i+1
if cursum > maxsum:
maxi = curi
maxsum = cursum
cursum = 0
for i in range(n):
cursum += deltas[(maxi+i)%n]
if cursum < 0: return -1
return maxi | class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// *Upvote will be appreciated*
int totalFuel = 0;
int totalCost = 0;
int n = gas.length;
for(int i = 0; i < n; i++) {
totalFuel += gas[i];
}
for(int i = 0; i < n; i++) {
totalCost += cost[i];
}
// if totalfuel < totalCost then It is not possible to tavel
if(totalFuel < totalCost) {
return -1;
}
// It is greather then There may be an Answer
int start = 0;
int currFuel = 0;
for(int i = 0; i < n; i++) {
currFuel += (gas[i]-cost[i]);
if(currFuel < 0) { // It Current Fuel is less than 0 mean we can't star from that index
start = i+1; // so we start from next index
currFuel = 0;
}
}
return start;
}
} | class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int start = -1;
int sum = 0 , gastillnow = 0;
for(int i = 0 ; i < 2*n ; i++){
if(start == i%n){
return i%n;
}
if(gas[i%n] + gastillnow >= cost[i%n]){ // we can start from this index
if(start==-1) start = i;
gastillnow += gas[i%n]-cost[i%n];
}else if(gastillnow + gas[i%n] < cost[i%n]){ // previous start index was wrong we have to start from another
start = -1;
gastillnow = 0;
}
}
return -1;
}
}; | var canCompleteCircuit = function(gas, cost) {
const len = gas.length;
// scan forward from the current index
const scan = (i) => {
let numTries = 0;
let tank = 0;
let c = 0;
while (numTries <= len) {
tank -= c;
if (tank < 0) return -1;
// if we made it back around, and we have gas, return the index, we made it!
if (numTries === len && tank >= 0) {
return i;
}
tank += gas[i];
c = cost[i];
i++;
if (i === len) i = 0; // if we hit the end, bounce back to zero
numTries++;
}
return -1;
}
for (let i = 0; i < len; i++) {
if (!gas[i]) continue; // no gas / zero gas so let's just move on
let index = scan(i);
if (~index) return index; // if it's not -1, return it
}
return -1;
}; | Gas Station |
Given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
Example 1:
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
Example 2:
Input: s = "Hello"
Output: 1
Constraints:
0 <= s.length <= 300
s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
The only space character in s is ' '.
| class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | class Solution {
public int countSegments(String s) {
int length = 0;
boolean flag = false;
for(Character c : s.toCharArray()) {
if(c == ' ' && flag) {
length++;
flag = !flag;
} else if(c != ' ') {
flag = true;
}
}
return flag ? length + 1 : length;
}
} | class Solution {
public:
int countSegments(string s) {
if(s=="")
return 0;
int res=0,flag=0;
for(int i=0;i<size(s);i++){
if(s[i]!=' '){
i++;
while(i<size(s) and s[i]!=' '){
i++;
}
res++;
}
}
return res;
}
}; | /**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
return s.trim() ? s.trim().split(/\s+/).length : 0
}; | Number of Segments in a String |
Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.
Return true if it is possible. Otherwise, return false.
Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/ | class Solution(object):
def isPossibleDivide(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if len(nums) % k != 0:
return False
freq = collections.defaultdict(int)
for v in nums:
freq[v] += 1
nums.sort()
while sum(freq.values()) > 0:
# smallest number in sorted nums with freq > 0 to start a sequence [v, v+1, v+2 ... , v+k-1]
for v in nums:
if freq[v] > 0:
for i in range(k):
if freq[v+i] <= 0:
return False
else:
freq[v+i] -= 1
return True | class Solution {
public boolean isPossibleDivide(int[] nums, int k) {
if (nums.length % k != 0) return false;
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
int count = countMap.getOrDefault(num, 0);
countMap.put(num , count + 1);
}
Arrays.sort(nums);
for (int num : nums) {
if (!countMap.containsKey(num)) continue;
int count = countMap.get(num);
if (count == 1) countMap.remove(num);
else countMap.put(num, count - 1);
for (int i = 1; i < k; i++) {
int next = num + i;
if (!countMap.containsKey(next)) return false;
count = countMap.get(next);
if (count == 1) countMap.remove(next);
else countMap.put(next, count - 1);
}
}
return true;
}
} | class Solution {
public:
bool isPossibleDivide(vector<int>& nums, int k) {
if(nums.size() % k) return false;
map<int, int> m;
for(int i : nums) m[i]++;
int n = m.size();
while(n) {
int a = m.begin() -> first;
m[a]--;
if(!m[a]) m.erase(a), n--;
for(int i=1; i<k; i++) {
if(m.find(a + i) == m.end()) return false;
m[a + i]--;
if(!m[a + i]) m.erase(a + i), n--;
}
}
return true;
}
}; | var isPossibleDivide = function(nums, k) {
if(nums.length % k) {
return false;
}
nums.sort((a, b) => a - b);
let numberOfArrays = nums.length / k, index = 0, dp = Array(numberOfArrays).fill(null).map(() => []);
dp[0].push(nums[0]);
for(let i = 1; i < nums.length; i++) {
if(nums[i] === nums[i - 1]) {
if(index === numberOfArrays - 1) {
return false;
}
index++;
}
else {
index = 0;
while(dp[index].length === k) {
index++;
}
}
if(dp[index].length && dp[index].at(-1) + 1 != nums[i]) {
return false;
}
dp[index].push(nums[i])
}
return true;
}; | Divide Array in Sets of K Consecutive Numbers |
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Constraints:
1 <= words.length <= 500
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
k is in the range [1, The number of unique words[i]]
Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?
| import heapq
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
li = {}
for i in words:
if i in li:
li[i]+=1
else:
li[i]=1
heap = []
for i in li:
heap.append([-li[i],i])
heapq.heapify(heap)
ans = []
for i in range(k):
ans.append(heapq.heappop(heap)[1])
return ans | class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> map=new LinkedHashMap<>();
for(String word:words)
map.put(word,map.getOrDefault(word,0)+1);
PriorityQueue<Pair<String,Integer>> queue=new PriorityQueue<>(new Comparator<Pair<String,Integer>>(){
@Override
public int compare(Pair<String,Integer> a,Pair<String,Integer> b){
if(a.getValue()!=b.getValue()) return b.getValue()-a.getValue();
return a.getKey().compareTo(b.getKey());
}
});
map.forEach((key,val)->{
queue.add(new Pair(key,val));
});
List<String> list=new ArrayList<>();
while(k>0){
list.add(queue.poll().getKey());
k--;
}
return list;
}
} | class Solution {
public:
bool static comp(pair<string, int> a, pair<string, int> b){
if(a.second > b.second) return true;
else if(a.second < b.second) return false;
else{
return a.first < b.first;
}
}
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> m;
for(auto i : words){
m[i]++;
}
vector<pair<string, int>> v;
for(auto i : m){
v.push_back(i);
}
sort(v.begin(), v.end(), comp);
vector<string> ans;
for(int i=0; i<k; i++){
ans.push_back(v[i].first);
}
return ans;
}
}; | var topKFrequent = function(words, k) {
let map=new Map()
let res=[]
for(let i of words){
if(map.has(i)){
map.set(i,map.get(i)+1)
}else{
map.set(i,1)
}
}
res=[...map.keys()].sort((a,b)=>{
if(map.get(a)===map.get(b)){
return b < a ? 1:-1
}
return map.get(b)-map.get(a)
}).slice(0,k)
return res
}; | Top K Frequent Words |
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.
Return true if any cycle of the same value exists in grid, otherwise, return false.
Example 1:
Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:
Example 2:
Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:
Example 3:
Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid consists only of lowercase English letters.
| class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
def getNeighbours(row,col,char):
neighbours = []
if row > 0 and grid[row-1][col] == char and not visited[row-1][col]:
neighbours.append([row-1,col])
if col > 0 and grid[row][col-1] == char and not visited[row][col-1]:
neighbours.append([row,col-1])
if row < len(grid)-1 and grid[row+1][col] == char and not visited[row+1][col]:
neighbours.append([row+1,col])
if col < len(grid[0])-1 and grid[row][col+1] == char and not visited[row][col+1]:
neighbours.append([row,col+1])
return neighbours
def dfs(row,col,char,cyclePresent):
if visited[row][col] or cyclePresent:
cyclePresent = True
return cyclePresent
visited[row][col] = True
neighbours = getNeighbours(row,col,char)
for r,c in neighbours:
cyclePresent = dfs(r,c,char,cyclePresent)
return cyclePresent
visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
cyclePresent = False
for row in range(len(grid)):
for col in range(len(grid[0])):
if cyclePresent:
return True
if visited[row][col]:
continue
cyclePresent = dfs(row,col,grid[row][col],cyclePresent)
return cyclePresent | class Solution {
public boolean containsCycle(char[][] grid) {
int rows = grid.length, cols = grid[0].length;
// Create a boolean array of same dimensions to keep track of visited cells
boolean[][] visited = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {
return true;
}
}
}
return false;
}
public boolean dfs(
char[][] grid,
boolean[][] visited,
int i,
int j,
int prevI,
int prevJ,
char c
) {
// Check for out of bounds
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;
// Check whether the current char matches the previous char
if (grid[i][j] != c) return false;
// If we stumble upon the same cell, we're guaranteed to have found a cycle!
if (visited[i][j]) {
return true;
}
// Mark the cell as visited
visited[i][j] = true;
// We want to search in the south direction ONLY IF we didn't come from north
// Do the same for all four directions
boolean south = i - prevI != -1;
boolean north = i - prevI != 1;
boolean east = j - prevJ != -1;
boolean west = j - prevJ != 1;
return
(south && dfs(grid, visited, i + 1, j, i, j, c)) ||
(north && dfs(grid, visited, i - 1, j, i, j, c)) ||
(east && dfs(grid, visited, i, j + 1, i, j, c)) ||
(west && dfs(grid, visited, i, j - 1, i, j, c));
}
} | class Solution {
public:
int dx[4]={-1,1,0,0};
int dy[4]={0,0,1,-1};
bool solve(vector<vector<char>>& grid,int i,int j,int m,int n,int x,int y,vector<vector<int>>&vis,char startChar){
vis[i][j]=1;
for(int k=0;k<4;k++){
int xx=i+dx[k];
int yy=j+dy[k];
if(xx>=0 && yy>=0 && xx<m && yy<n && grid[xx][yy]==startChar && !(x == xx && y == yy)){
if(vis[xx][yy] || solve(grid, xx , yy , m , n, i, j,vis,startChar))
return true;
}
}
return false;
}
bool containsCycle(vector<vector<char>>& grid) {
int m=grid.size();
int n=grid[0].size();
vector<vector<int>>vis(m,vector<int>(n,0));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(!vis[i][j] && solve(grid,i,j,m,n,-1,-1,vis,grid[i][j])){
return true;
}
}
}
return false;
}
}; | /**
* @param {character[][]} grid
* @return {boolean}
*/
var containsCycle = function(grid) {
const m = grid.length;
const n = grid[0].length;
const visited = [...Array(m)].map(i => Array(n).fill(0));
const dir = [[-1,0],[1,0],[0,-1],[0,1]];
const dfs = (x,y,lx,ly) => {
visited[x][y] = 1;
for (const [a, b] of dir) {
const nx = x + a;
const ny = y + b;
if (nx < 0 || nx > m - 1 || ny < 0 || ny > n - 1)
continue;
if (visited[nx][ny] === 1 && (nx !== lx || ny !== ly) && grid[x][y] === grid[nx][ny]) { // !!! grid[nx][ny] === grid[x][y]
return true;
}
if (visited[nx][ny] === 0 && grid[x][y] === grid[nx][ny]) {
if (dfs(nx,ny,x,y))
return true;
}
}
return false;
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (visited[i][j] === 0 && dfs(i,j,-1,-1)) // !!!
return true;
}
}
return false;
}; | Detect Cycles in 2D Grid |
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).
The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.
Return the minimum total space wasted if you can resize the array at most k times.
Note: The array can have any size at the start and does not count towards the number of resizing operations.
Example 1:
Input: nums = [10,20], k = 0
Output: 10
Explanation: size = [20,20].
We can set the initial size to be 20.
The total wasted space is (20 - 10) + (20 - 20) = 10.
Example 2:
Input: nums = [10,20,30], k = 1
Output: 10
Explanation: size = [20,20,30].
We can set the initial size to be 20 and resize to 30 at time 2.
The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.
Example 3:
Input: nums = [10,20,15,30,20], k = 2
Output: 15
Explanation: size = [10,20,20,30,30].
We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.
The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 106
0 <= k <= nums.length - 1
| class Solution:
def minSpaceWastedKResizing(self, A: List[int], K: int) -> int:
def waste(i, j, h):
sumI = sums[i-1] if i > 0 else 0
return (j-i+1)*h - sums[j] + sumI
def dp(i, k):
if i <= k:
return 0
if k < 0:
return MAX
if (i, k) in memoize:
return memoize[(i, k)]
_max = A[i]
r = MAX
for j in range(i-1, -2, -1):
r = min(r, dp(j, k-1) + waste(j+1, i, _max))
_max = max(_max, A[j])
memoize[(i, k)] = r
return r
sums = list(accumulate(A))
n = len(A)
MAX = 10**6*200
memoize = {}
return dp(n-1, K) | class Solution {
// dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times
int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 }
public int minSpaceWastedKResizing(int[] nums, int k) {
int dp[][]=new int[nums.length+1][k+1];
memeset(dp, -1);
return f(dp, 0, k, nums);
}
int f(int dp[][], int idx, int k, int nums[])
{
if(idx==nums.length)
return 0;
if(k==-1)
return INF;
if(dp[idx][k] != -1)
return dp[idx][k];
int ans=INF, max=nums[idx], sum=0;
for(int j=idx; j<nums.length; ++j)
{
max=Math.max(max, nums[j]);
sum+=nums[j];
/**
total waste in between [idx...j] would be
summation of (max-nums[idx] + max-nums[idx+1]....max-nums[j])
length would be (j-idx+1) and these summation would be
(j-idx+1) * max upto j - (nums[idx]+nums[idx+1]....+nums[j]
as i have made one partition in between [idx...j] then remainig (k-1) partitions would be in between [j+1....n-1]
and that value will be calculated by the recursion and we have to take the minimum answer from all these combinations
and to avoid tle we are using memozization
**/
int total_waste_upto_j=(j-idx+1)*max - sum;
ans=Math.min(ans, total_waste_upto_j + f(dp, j+1, k-1, nums));
}
return dp[idx][k]=ans;
}
void memeset(int dp[][], int val)
{
for(int x[]: dp)
Arrays.fill(x, val);
}
}
// tc: O(n^2 * k) there will be total (n*k) states because for each k there are n possibilities and for each n there will be loop running n times
// so in total there will be O(n^2 * k) [because k<n]
// sc: O(n*k) | class Solution {
public:
int dp[205][205];
#define maxi pow(10,8)
#define ll long long
int dfs(vector<int>& nums, int idx, int k)
{
int n = nums.size();
if(idx==n) return 0;
if(k<0) return maxi;
if(dp[idx][k]!=-1) return dp[idx][k];
ll sum = 0, mx = 0, ans = maxi;
for(int i=idx; i<n; i++)
{
sum += nums[i];
mx = max(mx,(ll)nums[i]);
ans = min(ans,mx*(i-idx+1)-sum + dfs(nums,i+1,k-1));
}
return dp[idx][k] = ans;
}
int minSpaceWastedKResizing(vector<int>& nums, int k) {
memset(dp,-1,sizeof(dp));
return dfs(nums,0,k);
}
}; | var minSpaceWastedKResizing = function(nums, k) {
var prefixSum = []; // prefix is index 1 based
var rangeMax = []; // index 0 based
var sum = 0;
prefixSum[0] = 0;
for (var i = 0; i < nums.length; i++) {
sum += nums[i];
prefixSum[i + 1] = sum;
}
for (var i = 0; i < nums.length; i++) {
var max = -Infinity;
rangeMax[i] = [];
for (var j = i; j < nums.length; j++) {
max = Math.max(nums[j], max);
rangeMax[i][j] = max;
}
}
var f = []; // f[i][j] is resize i times to get minimun with index j - 1 to get minimum space.
f[0] = [];
for (var i = 0; i <= k; i++) {
f[i] = [];
f[i][0] = 0;
}
for (var j = 1; j <= nums.length; j++) {
f[0][j] = rangeMax[0][j - 1] * j - prefixSum[j];
}
for (var i = 1; i <= k; i++) {
for (var j = 1; j <= nums.length; j++) {
f[i][j] = Infinity;
for (var m = 1; m <= j; m++) {
f[i][j] = Math.min(f[i][j], f[i - 1][m - 1] + rangeMax[m - 1][j - 1] * (j - m + 1) - (prefixSum[j] - prefixSum[m - 1]));
}
}
}
return f[k][nums.length];
}; | Minimum Total Space Wasted With K Resizing Operations |
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.
Return this maximum sum.
Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.
Example 1:
Input: events = [[1,3,2],[4,5,2],[2,4,3]]
Output: 4
Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
Example 2:
Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
Explanation: Choose event 2 for a sum of 5.
Example 3:
Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.
Constraints:
2 <= events.length <= 105
events[i].length == 3
1 <= startTimei <= endTimei <= 109
1 <= valuei <= 106
| class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
events.sort()
heap = []
res2,res1 = 0,0
for s,e,p in events:
while heap and heap[0][0]<s:
res1 = max(res1,heapq.heappop(heap)[1])
res2 = max(res2,res1+p)
heapq.heappush(heap,(e,p))
return res2 | class Solution {
public int maxTwoEvents(int[][] events) {
Arrays.sort(events, (a, b) -> a[0] - b[0]);
int onRight = 0, maxOne = 0, n = events.length;
int[] rightMax = new int[n+1];
for (int i = n - 1; i >= 0; i--) {
int start = events[i][0], end = events[i][1], val = events[i][2];
maxOne = Math.max(val, maxOne);
rightMax[i] = Math.max(rightMax[i+1], val);
}
int two = 0;
for (int i = 0; i < n; i++) {
int start = events[i][0], end = events[i][1], val = events[i][2];
int idx = binarySearch(end, events);
if (idx < n) {
two = Math.max(rightMax[idx] + val, two);
}
}
return Math.max(two, maxOne);
}
public int binarySearch(int end, int[][] arr) {
int left = 0, right = arr.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid][0] > end) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
} | #define ipair pair<int,int>
class Solution {
public:
int maxTwoEvents(vector<vector<int>>& events) {
//sort based on smaller start time
sort(events.begin(), events.end());
int mx = 0, ans = 0, n = events.size();
priority_queue<ipair, vector<ipair>, greater<>> pq;
// pq conatins {event_endtime , even_value}
// for every event check the max-value of earlier events whose
// deadline is less than start time of curr event
for(int i=0; i<n; i++)
{
while(!pq.empty() && pq.top().first < events[i][0])
mx = max(mx, pq.top().second), pq.pop();
ans = max(ans, mx+events[i][2]);
pq.push({events[i][1], events[i][2]});
}
return ans;
}
}; | var maxTwoEvents = function(events) {
const n = events.length;
events.sort((a, b) => a[0] - b[0]);
const minHeap = new MinPriorityQueue({ priority: x => x[1] });
let maxVal = 0;
let maxSum = 0;
for (let i = 0; i < n; ++i) {
const [currStart, currEnd, currVal] = events[i];
while (!minHeap.isEmpty()) {
const topElement = minHeap.front().element;
const [topIdx, topEnd] = topElement;
if (topEnd < currStart) {
maxVal = Math.max(maxVal, events[topIdx][2]);
minHeap.dequeue();
}
else {
break;
}
}
const sum = maxVal + currVal;
maxSum = Math.max(maxSum, sum);
minHeap.enqueue([i, currEnd]);
}
return maxSum;
}; | Two Best Non-Overlapping Events |
We are playing the Guessing Game. The game will work as follows:
I pick a number between 1 and n.
You guess a number.
If you guess the right number, you win the game.
If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.
Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game.
Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
Example 1:
Input: n = 10
Output: 16
Explanation: The winning strategy is as follows:
- The range is [1,10]. Guess 7.
- If this is my number, your total is $0. Otherwise, you pay $7.
- If my number is higher, the range is [8,10]. Guess 9.
- If this is my number, your total is $7. Otherwise, you pay $9.
- If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
- If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
- If my number is lower, the range is [1,6]. Guess 3.
- If this is my number, your total is $7. Otherwise, you pay $3.
- If my number is higher, the range is [4,6]. Guess 5.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
- If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
- If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
- If my number is lower, the range is [1,2]. Guess 1.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
Example 2:
Input: n = 1
Output: 0
Explanation: There is only one possible number, so you can guess 1 and not have to pay anything.
Example 3:
Input: n = 2
Output: 1
Explanation: There are two possible numbers, 1 and 2.
- Guess 1.
- If this is my number, your total is $0. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $1.
The worst case is that you pay $1.
Constraints:
1 <= n <= 200
| class Solution:
def getMoneyAmount(self, n):
# For an interval [l,r], we choose a num, which if incorrect still
# allows us to know whether the secret# is in either [l,num-1] or
# [num+1,r]. So, the worst-case (w-c) cost is
#
# num + max(w-c cost in [l,num-1], w-c cost in [num+1,r])
#
# We do this by recursion and binary search, starting with [1,n].
@lru_cache(None) # <-- we cache function results to avoid recomputing them
def dp(l = 1, r = n)-> int:
if r-l < 1: return 0 # <-- base case for the recursion; one number in [l,r]
ans = 1000 # <-- the answer for n = 200 is 952
for choice in range((l+r)//2,r):
ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r)))
return ans
return dp() | class Solution {
public int getMoneyAmount(int n) {
int dp[][]=new int[n+1][n+1];
for(int a[]:dp){
Arrays.fill(a,-1);
}
return solve(1,n,dp);
}
static int solve(int start,int end,int[][] dp){
if(start>=end) return 0;
if(dp[start][end]!=-1) return dp[start][end];
int min=Integer.MAX_VALUE;
for(int i=start;i<=end;i++){
min=Math.min(min,i+Math.max(solve(start,i-1,dp),solve(i+1,end,dp)));
}
dp[start][end]=min;
return min;
}
} | class Solution {
public:
vector<vector<int>> dp;
int solve(int start, int end)
{
if(start>= end)
return 0;
if(dp[start][end] != -1)
return dp[start][end];
int ans = 0;
int result = INT_MAX;
for(int i=start; i<=end; i++)
{
int left = solve(start,i-1);
int right = solve(i+1,end);
ans = max(left,right) + i; // this line gurantee to include the money that is needed to win higher values
result = min(ans,result);
}
return dp[start][end] = result;
}
int getMoneyAmount(int n) {
int ans = 0;
dp = vector<vector<int>>(n+1,vector<int>(n+1,-1));
return solve(1,n);
}
}; | /** https://leetcode.com/problems/guess-number-higher-or-lower-ii/
* @param {number} n
* @return {number}
*/
var getMoneyAmount = function(n) {
// Memo
this.memo = new Map();
return dp(n, 0, n);
};
var dp = function(n, start, end) {
let key = `${start}_${end}`;
// Base, there is only 1 node on this side of the leg, which mean our guess is always correct and it cost nothing so return 0
if (end - start < 2) {
return 0;
}
// Base, there are only 2 nodes on this side of the leg, which mean we only need to pick cheapest guess
if (end - start === 2) {
// The `start` will always be smaller so pick `start`, add 1 to account for 0 index
return start + 1;
}
// Return from memo
if (this.memo.has(key) === true) {
return this.memo.get(key);
}
// Minimum cost
let minCost = Infinity;
// Try to arrange the tree's left and right leg and find the cost of each leg
for (let i = start; i < end; i++) {
let left = dp(n, start, i);
let right = dp(n, i + 1, end);
// Cost of current guess, add 1 to account for 0 index
let curr = i + 1;
// Update cost of current guess, which is the max of left or right leg
curr = Math.max(left + curr, right + curr);
// Then update the minimum cost for entire tree
minCost = Math.min(minCost, curr);
}
// Set memo
this.memo.set(key, minCost);
return minCost;
}; | Guess Number Higher or Lower II |
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n, return the value of Tn.
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
Constraints:
0 <= n <= 37
The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
| class Solution:
def tribonacci(self, n: int, q={}) -> int:
if n<3:
q[0]=0 #Initialize first 3 values
q[1]=1
q[2]=1
if n not in q: #Have faith that last 3 calls will give the answer :)
q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci(n-3,q)
return q[n] | class Solution {
public int tribonacci(int n) {
if(n==0)
return 0;
if(n==1)
return 1;
if(n==2)
return 1;
int p1=1;
int p2=1;
int p3=0;
int cur=0;
for(int i=3;i<=n;i++)
{
cur=p1+p2+p3;
p3=p2;
p2=p1;
p1=cur;
}
return cur;
}
} | class Solution {
public:
int tribonacci(int n) {
if(n<2)
return n;
int prev3 = 0;
int prev2 = 1;
int prev1 = 1;
for(int i = 3; i<= n ; i++)
{
int ans = prev1+ prev2+prev3;
prev3 = prev2;
prev2 = prev1;
prev1 = ans;
}
return prev1;
}
}; | // Recursive and Memoiztion approach
var tribonacci = function(n, cache = {}) {
if(n in cache) return cache[n]
//Start of Base Cases
if(n == 0) return 0
if (n == 1 || n == 2) return 1;
// End Of Base Cases
// Caching the result
cache[n] = tribonacci(n - 1, cache) + tribonacci(n - 2, cache) + tribonacci(n - 3, cache);
return cache[n];
};
// Tabulation Approach
var tribonacci = function(n) {
// Create the Table;
const table = Array(n + 1).fill(0);
table[1] = 1;
for(let i =0;i<=n;i++){
//Iterate over the table and increase the values respectively
table[i+1] += table[i]
table[i+2] += table[i]
table[i+3] += table[i]
}
return table[n]
}; | N-th Tribonacci Number |
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
[4,5,6,7,0,1,4] if it was rotated 4 times.
[0,1,4,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [1,3,5]
Output: 1
Example 2:
Input: nums = [2,2,2,0,1]
Output: 0
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums is sorted and rotated between 1 and n times.
Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?
| class Solution:
def findMin(self, nums: List[int]) -> int:
return min(nums)
| class Solution {
public int findMin(int[] nums) {
int l = 0;
int h = nums.length - 1;
while (l < h) {
while (l < h && nums[l] == nums[l + 1])
++l;
while (l < h && nums[h] == nums[h - 1])
--h;
int mid = l + (h - l) / 2;
if (nums[mid] > nums[h]) { // smaller elements are in the right side
l = mid + 1;
} else {
h = mid;
}
}
return nums[l];
}
} | class Solution {
public:
int findMin(vector<int>& nums) {
int l=0,h=nums.size()-1;
while(l<h){
int m=l+(h-l)/2;
if(nums[m]<nums[h]) h=m;
else if(nums[m]>nums[h]) l=m+1;
else h--;
}
return nums[h];
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var findMin = function(nums) {
let min = Infinity;
let l = 0;
let r = nums.length - 1;
while (l <= r) {
const m = Math.floor((l + r) / 2);
// Eliminate dupes ......................... only difference from #153
while (l < m && nums[l] === nums[m]) l++;
while (r > m && nums[r] === nums[m]) r--;
// .........................................
// locate the sorted side, the opposite side has the break point
// min should be on the side that has the break point, so continue search on that side
if (nums[l] <= nums[m]) {
// left side is sorted (or l & m are the same index)
// brake is on right side
min = Math.min(min, nums[l]);
l = m + 1;
} else {
// right side is sorted
// break is on left side
min = Math.min(min, nums[m]);
r = m - 1;
}
}
return min;
}; | Find Minimum in Rotated Sorted Array II |
Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning.
Test cases are generated such that partitioning exists.
Example 1:
Input: nums = [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: nums = [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Constraints:
2 <= nums.length <= 105
0 <= nums[i] <= 106
There is at least one valid answer for the given input.
| class Solution:
def partitionDisjoint(self, nums: List[int]) -> int:
prefix = [nums[0] for _ in range(len(nums))]
suffix = [nums[-1] for _ in range(len(nums))]
for i in range(1, len(nums)):
prefix[i] = max(prefix[i-1], nums[i-1])
for i in range(len(nums)-2, -1, -1):
suffix[i] = min(suffix[i+1], nums[i+1])
for i in range(0, len(nums)-1):
if prefix[i] <= suffix[i]:
return i+1 | class Solution {
public int partitionDisjoint(int[] nums) {
int mts = nums[0]; // max till scan
int mtp = nums[0]; // max till partition
int idx = 0;
for(int i=1; i<nums.length; i++) {
int val = nums[i];
if(val < mtp) {
idx = i;
mtp = mts;
}
mts = Math.max(mts, val);
}
return idx + 1;
}
} | class Solution {
public:
vector<int> tree;
void build(vector<int> &nums) {
int n=nums.size();
for(int i=0 ; i<nums.size(); i++) tree[i+n]=nums[i];
for(int i=n-1 ; i>0 ; i--) tree[i] = min(tree[i<<1],tree[i<<1|1]);
}
int query(int l, int r, int n) {
l+=n,r+=n;
int ans = INT_MAX;
while(l<r) {
if(l&1) ans = min(ans,tree[l++]);
if(r&1) ans = min(ans,tree[--r]);
l>>=1; r>>=1;
}
return ans;
}
int partitionDisjoint(vector<int>& nums) {
int n=nums.size();
int mx=-1 ;
tree.resize(2*n,INT_MAX); build(nums);
for(int left=0; left<n ; left++) {
mx = max(mx,nums[left]);
if(query(left+1,n,n) >= mx) return left+1;
}
return n;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var partitionDisjoint = function(nums) {
let n = nums.length;
let leftMax = Array(n).fill(0), rightMin = Array(n).fill(0);
let left = 0, right = n- 1;
for(let i = 0, j = n - 1;i<n, j>=0 ;i++,j--){
leftMax[i] = Math.max(nums[i], !i ? -Infinity : leftMax[i-1]);
rightMin[j] = Math.min(nums[j], j === n - 1 ? Infinity : rightMin[j+1]);
}
for(let i = 0;i<n-1;i++){
if(leftMax[i] <= rightMin[i+1]){
return i + 1;
}
}
}; | Partition Array into Disjoint Intervals |
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first. Initially, M = 1.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
The game continues until all the stones have been taken.
Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
Example 1:
Input: piles = [2,7,9,4,4]
Output: 10
Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.
Example 2:
Input: piles = [1,2,3,4,5,100]
Output: 104
Constraints:
1 <= piles.length <= 100
1 <= piles[i] <= 104
| class Solution:
def stoneGameII(self, piles: List[int]) -> int:
n = len(piles)
dp = {}
def recursion(index,M):
# if we reached to the end we cannot score any value
if index == n:
return 0
# we search if we have solved the same case earlier
if (index,M) in dp:
return dp[(index,M)]
# total remaining score is the sum of array from index to the end
total = sum(piles[index:])
# if we can take the complete array it is the best choice
if index + 2*M >= n :return total
# my_score is the score we are getting as the player who is playing
my_score = 0
for x in range(index,index+2*M):
# opponent score will be calculated by next recursion
opponent_score = recursion(x+1,max(M,x-index+1))
# my_score is the remaining value of total - opponent_score
my_score = max(my_score,total - opponent_score)
# this is memoization part
dp[(index,M)] = my_score
# return the score
return my_score
return recursion(0,1) | class Solution {
public int stoneGameII(int[] piles) {
Map<String, Integer> memo = new HashMap<>();
int diff = stoneGame(piles,1,0,0,memo);
int totalSum = 0;
for(int ele: piles)
totalSum+=ele;
return (diff+totalSum)/2;
}
public int stoneGame(int[] piles, int M, int index, int turn,Map<String, Integer> memo )
{
if(index >= piles.length)
return 0;
if(memo.containsKey(index+"-"+M+"-"+turn))
return memo.get(index+"-"+M+"-"+turn);
int score=0,maxScore=Integer.MIN_VALUE;
// Alice's turn
if(turn == 0)
{
for(int X=1;X<=2*M && index+X-1<piles.length;X++)
{
score += piles[index+X-1];
maxScore= Math.max(maxScore,stoneGame(piles,Math.max(X,M),index+X,1,memo)+score);
}
memo.put(index+"-"+M+"-"+turn,maxScore);
return maxScore;
}
// Bob's turn
int minScore=Integer.MAX_VALUE;
for(int X=1;X<=2*M && index+X-1<piles.length;X++)
{
score += piles[index+X-1];
minScore = Math.min(minScore, stoneGame(piles,Math.max(X,M),index+X,0,memo) - score ) ;
}
memo.put(index+"-"+M+"-"+turn,minScore);
return minScore;
}
} | class Solution {
public:
int dp[103][103][2];
int rec(int i,int m,int p,vector<int>& piles){
if(i==piles.size()) return 0;
if(dp[i][m][p]!=-1) return dp[i][m][p];
int cnt = 0,ans=INT_MIN,n=piles.size();
for(int j=i;j<min(n,i+2*m);j++){
cnt += piles[j];
ans =max(ans, cnt - rec(j+1,max(j-i+1,m),1-p,piles));
}
return dp[i][m][p] = ans;
}
int stoneGameII(vector<int>& piles) {
int sum = 0;
memset(dp,-1,sizeof(dp));
for(auto i:piles) sum += i;
return (sum + rec(0,1,0,piles))/2;
}
}; | var stoneGameII = function(piles) {
const length = piles.length;
const dp = [...Array(length + 1).fill(null)].map((_) =>
Array(length + 1).fill(0)
);
const sufsum = new Array(length + 1).fill(0);
for (let i = length - 1; i >= 0; i--) {
sufsum[i] = sufsum[i + 1] + piles[i];
}
for (let i = 0; i <= length; i++) {
dp[i][length] = sufsum[i];
}
for (let i = length - 1; i >= 0; i--) {
for (let j = length - 1; j >= 1; j--) {
for (let X = 1; X <= 2 * j && i + X <= length; X++) {
dp[i][j] = Math.max(dp[i][j], sufsum[i] - dp[i + X][Math.max(j, X)]);
}
}
}
return dp[0][1];
}; | Stone Game II |
You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.
For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is not the concatenation of any permutation of words.
Return the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.
The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"] which is a permutation of words.
The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"] which is a permutation of words.
The output order does not matter. Returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Explanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.
There is no substring of length 16 is s that is equal to the concatenation of any permutation of words.
We return an empty array.
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Explanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.
The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"] which is a permutation of words.
The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"] which is a permutation of words.
The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"] which is a permutation of words.
Constraints:
1 <= s.length <= 104
1 <= words.length <= 5000
1 <= words[i].length <= 30
s and words[i] consist of lowercase English letters.
| class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
req={}
for i in words:
req[i]=1+req.get(i,0)
l=0
r=len(words)*len(words[0])
ans=[]
while r<len(s)+1:
i=0
curr={}
left, right= l, l+len(words[0])
while right<l+len(words)*len(words[0])+1:
x=s[left:right]
# print(x)
if x in req.keys():
curr[x]= 1+ curr.get(x,0)
left=right
right=right+len(words[0])
if req==curr:
ans.append(l)
l=l+1
r=r+1
return ans | class Solution {
public List<Integer> findSubstring(String s, String[] words) {
HashMap<String, Integer> input = new HashMap<>();
int ID = 1;
HashMap<Integer, Integer> count = new HashMap<>();
for(String word: words) {
if(!input.containsKey(word))
input.put(word, ID++);
int id = input.get(word);
count.put(id,count.getOrDefault(id,0)+1);
}
int len = s.length();
int wordLen = words[0].length();
int numWords = words.length;
int windowLen = wordLen*numWords;
int lastIndex = s.length()-windowLen;
int curWordId[] = new int[len];
String cur = " "+s.substring(0,wordLen-1);
//Change to int array
for(int i = 0; i< (len-wordLen+1); i++) {
cur = cur.substring(1, cur.length())+s.charAt(i+wordLen-1);
if(input.containsKey(cur)){
curWordId[i] = input.get(cur);
} else {
curWordId[i] = -1;
}
}
List<Integer> res = new ArrayList<>();
//compare using int make it faster 30 times in each comparison
for(int i = 0; i<= lastIndex; i++) {
HashMap<Integer, Integer> winMap = new HashMap<>();
for(int j = 0; j < windowLen && curWordId[i] != -1; j+=wordLen) {
int candidate = curWordId[j+i];
if(!count.containsKey(candidate))
break;
else{
winMap.put(candidate, winMap.getOrDefault(candidate, 0)+1);
}
if(winMap.get(candidate) > count.get(candidate))
break;
if(j == (windowLen - wordLen) && winMap.size() == count.size()){
res.add(i);
}
}
}
return res;
}
} | class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int n = words[0].length();
int slen = s.length();
int len = slen - n*words.size();
vector<int> ans;
if( len < 0) return ans;
string t;
unordered_map<string, int> mp;
for(auto i = 0; i < words.size(); ++i) ++mp[words[i]];
for(int i = 0; i<= len; ++i){
t = s.substr(i, n);
if(mp.find(t) != mp.end()){
unordered_map<string, int> smp;
++smp[t];
int flag = 1;
for(int j = i+n, k = 1; k < words.size() && j+n <= slen; ++k, j = j + n){
t = s.substr(j, n);
if(mp.find(t) != mp.end()) ++smp[t];
else {
flag = 0;
break;
}
}
if(flag && smp == mp) ans.push_back(i);
}
}
return ans;
}
}; | var findSubstring = function(s, words) {
let res = [];
let wordLength = words[0].length;
let wordCount = words.length;
let len = wordCount * wordLength; //Length of sliding window
let map = {}
for (let word of words) map[word] = map[word] + 1 || 1; //Hash word freq
for (let i = 0; i < s.length - len + 1; i++) {
let sub = s.slice(i, i + len); //Generate substring of sliding window length
if (isConcat(sub, map, wordLength)) res.push(i)
}
return res;
};
function isConcat(sub,map,wordLength){
let seen = {};
for (let i = 0; i < sub.length; i+=wordLength) {
let word = sub.slice(i,i + wordLength);
seen[word] = seen[word] + 1 || 1
}
for(let key in map){
if(map[key] !== seen[key]) return false; //Word freq must match between map and seen
}
return true;
}``` | Substring with Concatenation of All Words |
A string s is called happy if it satisfies the following conditions:
s only contains the letters 'a', 'b', and 'c'.
s does not contain any of "aaa", "bbb", or "ccc" as a substring.
s contains at most a occurrences of the letter 'a'.
s contains at most b occurrences of the letter 'b'.
s contains at most c occurrences of the letter 'c'.
Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100
a + b + c > 0
| class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pq = []
if a > 0: heapq.heappush(pq,(-a,'a'))
if b > 0: heapq.heappush(pq,(-b,'b'))
if c > 0: heapq.heappush(pq,(-c,'c'))
ans = ''
while pq:
c, ch = heapq.heappop(pq)
if len(ans)>1 and ans[-1] == ans[-2] == ch:
if not pq: break
c2, ch2 = heapq.heappop(pq)
ans += ch2
c2 += 1
if c2: heapq.heappush(pq,(c2,ch2))
else:
ans += ch
c += 1
if c: heapq.heappush(pq,(c,ch))
return ans | /*
The idea behid this problem
1. Here we start by taking the size as the sum of a, b, c.
2. Then we use 3 variables A, B, C to count the occurance of a, b, c.
3. Now we iterate until the size, and
-> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.
4. Finally return the string.
*/
class Solution {
public String longestDiverseString(int a, int b, int c) {
int totalSize = a + b + c;
int A = 0;
int B = 0;
int C = 0;
StringBuilder sb = new StringBuilder();
for (int i=0; i<totalSize; i++) {
// checks a is largest and its count still < 2 or B and C =2 and there are still a that can be added
if ((a>=b && a>=c && A<2) || (B==2 && a>0) || (C==2 && a>0)) {
sb.append("a");
a -= 1;
A += 1;
B = 0;
C = 0;
}
// check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be added
else if ((b>=a && b>=c && B<2) || (A==2 && b>0) || (C==2 && b>0)) {
sb.append("b");
b -= 1;
B += 1;
A = 0;
C = 0;
}
// checks c is largest and its count still < 2 or B and A = 2 and there are still c that can be added
else if ((c>=a && c>=b && C<2) || (A==2 && c>0) || (B==2 && c>0)) {
sb.append("c");
c -= 1;
C += 1;
A = 0;
B = 0;
}
}
return sb.toString();
}
} | class Solution {
public:
#define f first
#define s second
string longestDiverseString(int a, int b, int c) {
priority_queue<pair<int,char>> pq;
if(a>0)pq.push({a,'a'});
if(b>0)pq.push({b,'b'});
if(c>0)pq.push({c,'c'});
string ans = "";
while(!pq.empty()){
auto t = pq.top(); pq.pop();
int c = t.f;
char ch = t.s;
if(ans.size() > 1 && ans[ans.size()-1]==ch && ch == ans[ans.size()-2]) {
if(pq.empty())break;
auto t = pq.top(); pq.pop();
int c2 = t.f;
char ch2 = t.s;
ans += ch2;
c2-=1;
if(c2)pq.push({c2,ch2});
}else{
ans += ch;
c-=1;
}
if(c)pq.push({c,ch});
}
return ans;
}
}; | var longestDiverseString = function(a, b, c) {
let str = '', aCount = 0, bCount = 0, cCount = 0;
let len = a + b + c;
for(let i = 0; i < len; i++) {
if (a >= b && a >= c && aCount != 2 || bCount == 2 && a > 0 || cCount == 2 && a > 0) {
adjustCounts('a', aCount+1, 0, 0);
a--;
} else if (b >= a && b >= c && bCount != 2 || aCount == 2 && b > 0 || cCount == 2 && b > 0) {
adjustCounts('b', 0, bCount+1, 0);
b--;
} else if (c >= a && c >= b && cCount != 2 || bCount == 2 && c > 0|| aCount == 2 && c > 0) {
adjustCounts('c', 0, 0 , cCount+1);
c--;
}
}
function adjustCounts(letter, newA, newB, newC){
aCount = newA;
bCount = newB;
cCount = newC;
str += letter;
}
return str;
}; | Longest Happy String |
You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.
You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.
The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.
Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.
Note:
A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:
x1 < x2, or
x1 == x2 and y1 < y2.
⌊val⌋ is the greatest integer less than or equal to val (the floor function).
Example 1:
Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2
Output: [2,1]
Explanation: At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
Example 2:
Input: towers = [[23,11,21]], radius = 9
Output: [23,11]
Explanation: Since there is only one tower, the network quality is highest right at the tower's location.
Example 3:
Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2
Output: [1,2]
Explanation: Coordinate (1, 2) has the highest network quality.
Constraints:
1 <= towers.length <= 50
towers[i].length == 3
0 <= xi, yi, qi <= 50
1 <= radius <= 50
| class Solution:
def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:
return max(
(
(sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius),
[x, y]) for x in range(51) for y in range(51)
),
key=lambda x: (x[0], -x[1][0], -x[1][1])
)[1] | class Solution {
public int[] bestCoordinate(int[][] towers, int radius) {
int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0;
int[] res = new int[2];
for(int[] t : towers) {
minX = Math.min(minX, t[0]);
maxX = Math.max(maxX, t[0]);
minY = Math.min(minY, t[1]);
maxY = Math.max(maxY, t[1]);
}
for(int i = minX; i <= maxX; i++) {
for(int j = minY; j <= maxY; j++) {
int sum = 0;
for(int[] t : towers) {
int d = (t[0] - i) *(t[0] - i) + (t[1] - j) *(t[1] - j);
if(d <= radius * radius) {
sum += t[2] /(1+ Math.sqrt(d));
}
}
if(sum > max) {
max = sum;
res = new int[]{i,j};
}
}
}
return res;
}
} | class Solution {
public:
vector<int> bestCoordinate(vector<vector<int>>& towers, int radius) {
int n = towers.size();
int sum;
int ans = 0;
pair<int,int> ansCoor;
// Calculate for every 'x's and 'y's
for(int x = 0; x <= 50; x++){
for(int y = 0; y <= 50; y++){
sum = 0;
for(const auto it : towers){
int xa = it[0];
int ya = it[1];
int qa = it[2];
// get the distance between the two points
int distance = pow(x - xa, 2) + pow(y - ya, 2);
if(distance > radius * radius) {
continue;
}
// increment the quality value
sum += (int)(qa / (1 + sqrt(distance)));
}
// store the maximum ans
if(sum > ans){
ans = sum;
ansCoor = {x,y};
}
}
}
return vector<int>{{ansCoor.first, ansCoor.second}};
}
}; | var bestCoordinate = function(towers, radius) {
const n = towers.length;
const grid = [];
for (let i = 0; i <= 50; i++) {
grid[i] = new Array(51).fill(0);
}
for (let i = 0; i < n; i++) {
const [x1, y1, quality1] = towers[i];
for (let x2 = 0; x2 <= 50; x2++) {
for (let y2 = 0; y2 <= 50; y2++) {
const dist = Math.sqrt((x1 - x2)**2 + (y1 - y2)**2);
if (dist > radius) continue;
const network = Math.floor(quality1 / (1 + dist));
grid[x2][y2] += network;
}
}
}
let maxX = 0;
let maxY = 0;
let maxVal = grid[0][0];
for (let i = 0; i <= 50; i++) {
for (let j = 0; j <= 50; j++) {
const val = grid[i][j];
if (val > maxVal) {
maxVal = val;
maxX = i;
maxY = j;
}
else if (val === maxVal) {
if (i < maxX || (i === maxX && j < maxY)) {
maxVal = val;
maxX = i;
maxY = j;
}
}
}
}
return [maxX, maxY];
}; | Coordinate With Maximum Network Quality |
Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
Example 1:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
Example 2:
Input: s = "10"
Output: 1
Explanation: "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
Example 3:
Input: s = "1"
Output: 0
Constraints:
1 <= s.length <= 500
s consists of characters '0' or '1'
s[0] == '1'
| class Solution:
def numSteps(self, s: str) -> int:
size = len(s)
if size == 1:
return 0
one_group = s.split('0')
zero_group = s.split('1')
if size - len(zero_group[-1]) == 1:
return size - 1
else:
return size + len(one_group) - len(zero_group[-1]) | class Solution
{
public int numSteps(String s)
{
int countSteps = 0;
int carry = 0;
for(int i = s.length()-1;i>=1;i--)
{
int rightMostBit = s.charAt(i)-'0';
if((rightMostBit+carry) == 1)
{
carry=1;
countSteps += 2;
}
else
{
countSteps++;
}
}
return countSteps+carry;
}
} | class Solution {
public:
int numSteps(string s) {
int n=0;
bool carry = false;
int steps = 0;
if(s == "1") return 0;
while(s.length() > 0){
int i = s.length()-1;
if(carry){
if(s[i] == '1'){
carry = true; s[i] = '0';
}else{
s[i] = '1'; carry = false;
}
}
if(s[i] == '0'){ s.pop_back(); steps++;}
else{carry = true; s.pop_back(); steps += 2;}
if(s == "1"){
if(carry) steps++;
break;
}
}
return steps;
}
}; | var numSteps = function(s) {
let res = 0;
s = s.split("");
while(s.length>1){
if(s[s.length-1]==="0") s.pop();
else plusone(s);
res++;
}
return res;
};
var plusone = function(p) {
p.unshift("0");
let i = p.length-1;
p[i] = 1+(+p[i]);
while(p[i]===2){
p[i-1] = 1+(+p[i-1]);
i--;
p[i+1] = "0";
}
if(p[0]==="0") p.shift();
return p;
}; | Number of Steps to Reduce a Number in Binary Representation to One |
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.
-x for x < 0.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:
Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.length
n == points[r].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= points[r][c] <= 105
| class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
m, n = len(points), len(points[0])
for i in range(m - 1):
for j in range(1, n):
points[i][j] = max(points[i][j], points[i][j - 1] - 1)
for j in range(n - 2, -1, -1):
points[i][j] = max(points[i][j], points[i][j + 1] - 1)
for j in range(n):
points[i + 1][j] += points[i][j]
return max(points[m - 1]) | /*
-> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get
added to next values from next row.
-> conditions to update values in frame
* we will keep only those values which will contribute maximum in next row addition
e.g-->
points --->[[1,2,3]
[1,5,1]
[3,1,1]]
for 1st iteration frame <--- [1,2,3] rest of two loops will not affect frame so in
2nd itreration frame <--------[2,7,4] <-------- [1,2,3] + [1,5,1]
now we have to update frame so it can give max values for next row addition
0 1 2
[2,7,4]
\
[2,7,4] check left to right--> just check value at index 0 can contribute more than curr_sum at index 1 but to do so it has to give up (1-0) a penalty,here 7 can contribute more than 2-1=1 in next sum.
2 7 4 now check for index 2,where (7-1)>4
\
2 7 6
now do in reverse,can 6 contribute more than 7 no ( 7 >(6-1) )
can 7 contibute more than 2 yes (2<(7-1)),so now frame will be
6 7 6 now we can cal optimal-frame for rest of the matrix.
+ 3 1 1
-------------------
9 8 7 check left to right--> can 9 can contibute 8>(9-1) no; can 8 can contibute for index 2 no simlier for right to left
*/
class Solution {
public long maxPoints(int[][] points) {
long[] frame = new long[points[0].length];
for (int i = 0; i < points.length; i++) {
for (int j = 0; j <frame.length; j ++) frame[j] += points[i][j];
for (int j = 1; j < frame.length; j ++) frame[j] = Math.max(frame[j], frame[j - 1] - 1);
for (int j=frame.length-2;j>=0;j--) frame[j] = Math.max(frame[j], frame[j + 1] - 1);
for(long k:frame) System.out.println(k);
}
long ans = 0;
for (int i = 0; i < frame.length; i ++) {
ans = Math.max(ans, frame[i]);
}
return ans;
}
} | class Solution {
public:
long long maxPoints(vector<vector<int>>& points) {
vector<vector<long long>> dp(points.size(), vector<long long>(points[0].size(), -1));
for (int i = 0; i < points[0].size(); ++i) {
dp[0][i] = points[0][i];
}
for (int i = 1; i < points.size(); ++i) {
for (int j = 0; j < points[i].size(); ++j) {
for (int k = 0; k < points[i].size(); ++k) {
dp[i][j] = max(dp[i][j], dp[i - 1][k] - abs(k - j) + points[i][j]);
}
}
}
long long max_ans = -1;
for (const auto v : dp.back()) {
max_ans = max(max_ans, v);
}
return max_ans;
}
}; | var maxPoints = function(points) {
let prev = points[0];
let curr = Array(points[0].length);
for(let i = 1; i<points.length; i++){
// from left to right;
for(let j = 0, maxAdd=0; j<points[0].length;j++){
maxAdd = Math.max(maxAdd-1, prev[j]);
curr[j] = points[i][j] + maxAdd;
}
for(let j = points[0].length-1, maxAdd = 0; j>=0; j--){
maxAdd = Math.max(maxAdd-1, prev[j]);
curr[j] = Math.max(curr[j], points[i][j] + maxAdd)
}
prev = curr;
curr = Array(points[0].length)
}
return Math.max(...prev)
}; | Maximum Number of Points with Cost |
An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.
Example 1:
Input: n = 10
Output: 9
Example 2:
Input: n = 1234
Output: 1234
Example 3:
Input: n = 332
Output: 299
Constraints:
0 <= n <= 109
| class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
num = list(str(n))
for i in range(len(num)-1):
# Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return
# However, there is the case that num[i-1]==num[i], which will make num[i]-1<num[i-1]
# So, traverse back to find the num that its num[i-1] != num[i](to make sure num[i-1]<=num[i]-1), then do step1 and return
if num[i] > num[i+1]:
while i >= 1 and num[i-1] == num[i]:
i -= 1
num[i] = chr(ord(num[i])-1)
return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))
return n | class Solution {
public int monotoneIncreasingDigits(int n) {
int position;
int digitInTheNextPosition;
while ((position = getThePositionNotSatisfied(n)) != -1) {
digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;
n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);
n -= n % Math.pow(10, position);
n += Math.pow(10, position) - 1;
}
return n;
}
public int getThePositionNotSatisfied(int n) {
int k = 10;
int position = 0;
while (n > 0) {
if (k < n % 10) {
return position;
} else {
k = n % 10;
n /= 10;
position++;
}
}
return -1;
}
} | class Solution {
public:
int monotoneIncreasingDigits(int n) {
if(n < 10) return n;
string s = to_string(n);
for(int i = s.size() - 2; i >= 0; i--) {
if(s[i] > s[i+1]) {
s[i]--;
for(int j = i + 1; j < s.size(); j++) s[j] = '9';
}
}
int ans = stoi(s);
return ans;
}
}; | var monotoneIncreasingDigits = function(n) {
let arr = String(n).split('');
for (let i=arr.length-2; i>=0; i--) {
if (arr[i]>arr[i+1]) {
arr[i]--;
for(let j=i+1; j<arr.length; j++) arr[j]='9';
}
}
return Number(arr.join(''));
}; | Monotone Increasing Digits |
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
| class Codec:
def serialize(self, root):
if not root: return 'N'
left = self.serialize(root.left)
right = self.serialize(root.right)
return ','.join([str(root.val), left, right])
def deserialize(self, data):
data = data.split(',')
root = self.buildTree(data)
return root
def buildTree(self, data):
val = data.pop(0)
if val == 'N': return None
node = TreeNode(val)
node.left = self.buildTree(data)
node.right = self.buildTree(data)
return node | public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
String data="";
Queue<TreeNode> q=new LinkedList<>();
if(root!=null)
q.add(root);
else
return "";
data=Integer.toString(root.val)+"e";
while(!q.isEmpty())
{
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode node=q.poll();
if(node.left!=null)
{
data=data+Integer.toString(node.left.val)+"e";
q.add(node.left);
}
else
data=data+"N"+"e";
if(node.right!=null)
{
data=data+Integer.toString(node.right.val)+"e";
q.add(node.right);
}
else
data=data+"N"+"e";
}
}
return data;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.length()==0)
return null;
int i=0;
String s="";
while(data.charAt(i)!='e')
s=s+data.charAt(i++);
int d=Integer.parseInt(s);
TreeNode root=new TreeNode(d);
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
while(i<data.length() && !q.isEmpty())
{
int size=q.size();
for(int j=0;j<size;j++)
{
s="";
i++;
TreeNode node=q.poll();
while(data.charAt(i)!='e')
s=s+data.charAt(i++);
if(s.equals("N"))
node.left=null;
else
{
TreeNode l=new TreeNode(Integer.parseInt(s));
node.left=l;
q.add(l);
}
s="";
i++;
while(data.charAt(i)!='e')
s=s+data.charAt(i++);
if(s.equals("N"))
node.right=null;
else
{
TreeNode r=new TreeNode(Integer.parseInt(s));
node.right=r;
q.add(r);
}
}
}
return root;
}
} | TreeNode* ans;
class Codec {
public:
string serialize(TreeNode* root) {
ans = root;
return "";
}
TreeNode* deserialize(string data) {
return ans;
}
}; | var serialize = function (root) {
if (!root) return "";
let res = [];
function getNode(node) {
if (!node) {
res.push("null");
} else {
res.push(node.val);
getNode(node.left);
getNode(node.right);
}
}
getNode(root);
return res.join(",");
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function (data) {
if (data === "") return null;
const arr = data.split(",");
function buildTree(array) {
const nodeVal = array.shift();
if (nodeVal === "null") return null;
const node = new TreeNode(nodeVal);
node.left = buildTree(array); //build left first
node.right = buildTree(array); //build right with updated array.
return node;
}
return buildTree(arr);
}; | Serialize and Deserialize Binary Tree |
An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
Concatenate the elements of the sequence to get the encoded string: "ab121p".
Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.
Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
Example 1:
Input: s1 = "internationalization", s2 = "i18n"
Output: true
Explanation: It is possible that "internationalization" was the original string.
- "internationalization"
-> Split: ["internationalization"]
-> Do not replace any element
-> Concatenate: "internationalization", which is s1.
- "internationalization"
-> Split: ["i", "nternationalizatio", "n"]
-> Replace: ["i", "18", "n"]
-> Concatenate: "i18n", which is s2
Example 2:
Input: s1 = "l123e", s2 = "44"
Output: true
Explanation: It is possible that "leetcode" was the original string.
- "leetcode"
-> Split: ["l", "e", "et", "cod", "e"]
-> Replace: ["l", "1", "2", "3", "e"]
-> Concatenate: "l123e", which is s1.
- "leetcode"
-> Split: ["leet", "code"]
-> Replace: ["4", "4"]
-> Concatenate: "44", which is s2.
Example 3:
Input: s1 = "a5b", s2 = "c5b"
Output: false
Explanation: It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.
Constraints:
1 <= s1.length, s2.length <= 40
s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
The number of consecutive digits in s1 and s2 does not exceed 3.
| from functools import lru_cache
class Solution:
def possiblyEquals(self, s1: str, s2: str) -> bool:
def getValidPrefixLength(s,start):
end = start
while end < len(s) and s[end].isdigit(): end += 1
return end
@lru_cache(None)
def possibleLengths(s):
"""Return all possible lengths represented by numeric string s."""
ans = {int(s)}
for i in range(1, len(s)):
# add all lengths by splitting numeric string s at i
ans |= {x+y for x in possibleLengths(s[:i]) for y in possibleLengths(s[i:])}
return ans
@lru_cache(None)
def dp(i, j, diff):
"""Return True if s1[i:] matches s2[j:] with given differences."""
# If both have reached end return true if none of them are leading
if i == len(s1) and j == len(s2): return diff == 0
# s1 has not reached end and s1 starts with a digit
if i < len(s1) and s1[i].isdigit():
i2 = getValidPrefixLength(s1,i)
for L in possibleLengths(s1[i:i2]):
# substract since lead of s2 decreases by L
if dp(i2, j, diff-L): return True
# s2 has not reached end and s2 starts with a digit
elif j < len(s2) and s2[j].isdigit():
j2 = getValidPrefixLength(s2,j)
for L in possibleLengths(s2[j:j2]):
# add since lead of s2 increase by L
if dp(i, j2, diff+L): return True
# if none of them have integer prefix or a lead over the other
elif diff == 0:
# if only one of them has reached end or current alphabets are not the same
if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False
# skip same alphabets
return dp(i+1, j+1, 0)
# if none of them have integer prefix & s2 lead over s1
elif diff > 0:
# no s1 to balance s2's lead
if i == len(s1): return False
# move s1 pointer forward and reduce diff
return dp(i+1, j, diff-1)
# if none of them have integer prefix & s1 lead over s2
else:
# no s2 to balance s1's lead
if j == len(s2): return False
# move s2 pointer forward and increase diff
return dp(i, j+1, diff+1)
# start with starts of both s1 and s2 with no lead by any of them
return dp(0, 0, 0) | /**
Cases:
diff > 0 meaning we need to pick more chars in s1
diff < 0 meaning we need to pick more chars in s2
-1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999
1. s1[i] == s2[j] and diff = 0
increment i+1 and j+1
2. if s1[i] is not digit and diff > 0 then increment i i+1, diff
3. if s2[j] is not digit and diff < 0 then increment j j+1, diff
4. if s1[i] is digit then get digit value and decrement diff val as we have covered such chars in the s1 string
and increment i i+1, diff-val
5. if s2[j] is digit then get digit value and increment diff val as we need to cover such chars in the s2 string and
increment j, j+1, diff+val
01234
s1 = l123e
s2 = 44
i: 0
j: 0
diff: 0
// Wildcard matching on s2[j]
val = 4, diff = 0+4 j = 1
i: 0
j: 1
diff: 4
// Literal matching on s1[i]
increment ith pointer as ith is a literal and we can move on to next char in s1 and decrement diff
i: 1
j: 1
diff: 3
// Wildcard matching on s1[i]
val = 1 diff = 3-1 = 2 increment i
i: 2
j: 1
diff: 2
// Wildcard matching on s1[i]
val = 2 diff = 2-2 = 0 increment i
i: 3
j: 1
diff: 0
// Wildcard matching on s1[i]
val=3 diff = 0-3 = -3, increment i
i: 4
j: 1
diff: -3
// Wildcard matching on s2[j]
val = 4 diff = -3+4 =1 increment j
i: 4
j: 2
diff: 1
// Literal matching on s1[i]
decrement i-1 and increment i
i=5
j=2
diff==0 return true
dp[4][2][1] = true
return true
return dp[4][1][1000-3] = true
return dp[3][1][0] = true
i: 2
j: 1
diff: 2
return dp[2][1][2] = true
return true
i: 0
j: 1
diff: 4
return dp[0][1][4] = true
return true
*/
class Solution {
//112ms
public boolean possiblyEquals(String s1, String s2) {
return helper(s1.toCharArray(), s2.toCharArray(), 0, 0, 0, new Boolean[s1.length()+1][s2.length()+1][2001]);
}
boolean helper(char[] s1, char[] s2, int i, int j, int diff, Boolean[][][] dp) {
if(i == s1.length && j == s2.length) {
return diff == 0;
}
if(dp[i][j][diff+1000] != null)
return dp[i][j][diff+1000];
// if both i and j are at the same location and chars are same then simply increment both pointers
if(i < s1.length && j < s2.length && diff == 0 && s1[i] == s2[j]) {
if(helper(s1, s2, i+1, j+1, diff, dp)) {
return dp[i][j][diff+1000] = true;
}
}
// if s1[i] is literal and diff > 0 then increment i and decrement diff by 1
if(i < s1.length && !Character.isDigit(s1[i]) && diff > 0 && helper(s1, s2, i+1, j, diff-1, dp)) {
return dp[i][j][diff+1000] = true;
}
// if s2[j] is literal and diff < 0 then increment j and increment diff by 1
// as we are done with the current jth char
if(j < s2.length && !Character.isDigit(s2[j]) && diff < 0 && helper(s1, s2, i, j+1, diff+1, dp)) {
return dp[i][j][diff+1000] = true;
}
// wildcard matching in s1
// if s1 contains l123
// then need to check with val as 1 then val as 12 and val as 123
for(int k = i, val = 0; k < i + 4 && k < s1.length && Character.isDigit(s1[k]); k++) {
val = val * 10 + s1[k] -'0';
if(helper(s1, s2, k+1, j, diff-val, dp)) {
return dp[i][j][diff+1000] = true;
}
}
// wildcard matching in s2
// if s2 contains l123
// then need to check with val as 1 then val as 12 and val as 123
for(int k = j, val = 0; k < j + 4 && k < s2.length && Character.isDigit(s2[k]); k++) {
val = val * 10 + s2[k] -'0';
if(helper(s1, s2, i, k+1, diff+val, dp)) {
return dp[i][j][diff+1000] = true;
}
}
return dp[i][j][diff+1000] = false;
}
} | class Solution {
public:
bool memo[50][50][2000];
bool comp_seqs(string& s1, string& s2, int i1, int i2, int diff){
// check true condition
if(i1 == s1.size() && i2 == s2.size())
return diff == 0;
// add 1000 to 'diff' be in range [0, 2000)
bool& ret = memo[i1][i2][diff+1000];
if(ret)
return false; // immediately return
ret = true; // check visited
// diff > 0 or diff < 0 checking to ensure the diff always be in range (-1000, 1000)
// in the case that s1[i1] is a digit
if(diff >= 0 && i1 < s1.size() && s1[i1] <= '9'){
int num1 = 0;
for(int i=0; i<min(3, (int)s1.size()-i1); i++){ // loop maximum 3 consecutive digits
if(s1[i1 + i] > '9')
break;
num1 = num1*10 + s1[i1 + i] - '0';
if(comp_seqs(s1, s2, i1+i+1, i2, diff-num1))
return true;
}
}else if(diff <= 0 && i2 < s2.size() && s2[i2] <= '9'){ // in the case that s2[i2] is a digit
int num2 = 0;
for(int i=0; i<min(3, (int)s2.size()-i2); i++){
if(s2[i2 + i] > '9')
break;
num2 = num2*10 + s2[i2 + i] - '0';
if(comp_seqs(s1, s2, i1, i2+i+1, diff+num2))
return true;
}
}else if(diff == 0){
if(i1 >= s1.size() || i2 >= s2.size() || s1[i1] != s2[i2]) // reject infeasible cases
return false;
return comp_seqs(s1, s2, i1+1, i2+1, 0);
}else if(diff > 0){
if(i1 >= s1.size()) // reject infeasible cases
return false;
return comp_seqs(s1, s2, i1+1, i2, diff - 1);
}else{
if(i2 >= s2.size()) // reject infeasible cases
return false;
return comp_seqs(s1, s2, i1, i2+1, diff + 1);
}
return false;
}
bool possiblyEquals(string s1, string s2) {
return comp_seqs(s1, s2, 0, 0, 0);
}
}; | var possiblyEquals = function(s1, s2) {
// Memo array, note that we do not need to memoize true results as these bubble up
const dp = Array.from({length: s1.length+1}, () =>
Array.from({length: s2.length+1},
() => ([])));
const backtrack = (p1, p2, count) => {
if(p1 === s1.length && p2 === s2.length) return count === 0;
// Optimization: Exit early if we have already visited here and know that it's false
if(dp[p1][p2][count] !== undefined) return dp[p1][p2][count];
let c1 = s1[p1];
let c2 = s2[p2];
// Case 1: string matches exactly
if(p1 < s1.length && p2 < s2.length &&
c1 === c2 && count === 0 &&
backtrack(p1+1, p2+1, count)) return true;
// Case 2: we can delete a character
if(p1 < s1.length && isNaN(c1) && count < 0 &&
backtrack(p1+1, p2, count+1)) return true;
if(p2 < s2.length && isNaN(c2) && count > 0 &&
backtrack(p1, p2+1, count-1)) return true;
// Case 3: we can start stacking numbers to delete
let num = 0;
for(let i = 0; i < 3 && p1+i < s1.length; i++) {
let c1 = s1[p1+i];
if(isNaN(c1)) break;
num = num * 10 + parseInt(c1);
if(backtrack(p1+i+1, p2, count + num)) return true;
}
num = 0;
for(let i = 0; i < 3 && p2+i < s2.length; i++) {
let c2 = s2[p2+i];
if(isNaN(c2)) break;
num = num * 10 + parseInt(c2);
if(backtrack(p1, p2+i+1, count - num)) return true;
}
dp[p1][p2][count] = false;
return false;
}
return backtrack(0,0,0);
}; | Check if an Original String Exists Given Two Encoded Strings |
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
Example 2:
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
Constraints:
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
| class Solution(object):
def getConcatenation(self, nums):
return nums * 2 | class Solution {
public int[] getConcatenation(int[] nums) {
int[] ans = new int[2 * nums.length];
for(int i = 0; i < nums.length; i++){
ans[i] = ans[i + nums.length] = nums[i];
}
return ans;
}
} | class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
for(int i=0;i<n;i++)
{
nums.push_back(nums[i]);
}
return nums;
}
}; | var getConcatenation = function(nums) {
//spread the nums array twice and return it
return [...nums,...nums]
}; | Concatenation of Array |
You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.
The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.
You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.
Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.
Example 1:
Input: bombs = [[2,1,3],[6,1,4]]
Output: 2
Explanation:
The above figure shows the positions and ranges of the 2 bombs.
If we detonate the left bomb, the right bomb will not be affected.
But if we detonate the right bomb, both bombs will be detonated.
So the maximum bombs that can be detonated is max(1, 2) = 2.
Example 2:
Input: bombs = [[1,1,5],[10,10,5]]
Output: 1
Explanation:
Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.
Example 3:
Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]
Output: 5
Explanation:
The best bomb to detonate is bomb 0 because:
- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.
- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.
- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.
Thus all 5 bombs are detonated.
Constraints:
1 <= bombs.length <= 100
bombs[i].length == 3
1 <= xi, yi, ri <= 105
| class Solution(object):
def maximumDetonation(self, bombs):
def count(i):
dq, ret = [i], [i]
while len(dq) > 0:
i = dq.pop()
for j in adj[i]:
if j not in ret and j not in dq:
dq.append(j)
ret.append(j)
return len(ret)
adj = collections.defaultdict(list)
for i in range(len(bombs)):
for j in range(i + 1, len(bombs)):
if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:
adj[i].append(j)
if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:
adj[j].append(i)
ret = 0
for i in range(len(bombs)):
ret = max(ret, count(i))
return ret | class Solution {
/*
Make directed graph
u -> v means, v is in the range of u
check from which node maximum nodes can be reached and return the number of nodes reached
*/
public int maximumDetonation(int[][] bombs) {
Map<Integer, List<Integer>> graph = new HashMap<>();
int n = bombs.length;
for(int i = 0; i< n; i++){
graph.put(i, new ArrayList<>());
for(int j = 0; j< n; j++){
if(i == j) continue;
if(inRange(bombs[i], bombs[j]))
graph.get(i).add(j);
}
}
int max = 0;
for(int i = 0; i< n; i++){
max = Math.max(max, dfs(i, graph, new HashSet<>()));
}
return max;
}
private boolean inRange(int[] u, int[] v){
// (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border
// (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle
// (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle
return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);
}
private int dfs(int node, Map<Integer, List<Integer>> graph, Set<Integer> visited){
if(visited.contains(node)) return 0;
visited.add(node);
int res = 0;
for(int neigh: graph.get(node)){
res += dfs(neigh, graph, visited);
}
return res + 1;
}
} | class Solution {
public:
double eucDis(int x1,int y1,int x2,int y2)
{
double temp=pow(x1-x2,2)+pow(y1-y2,2);
return sqrt(temp);
}
void dfs(int node,vector<int>&vis,vector<int>graph[],int &c)
{
c++;
vis[node]=1;
for(auto i:graph[node])
{
if(!vis[i])
{
dfs(i,vis,graph,c);
}
}
}
int maximumDetonation(vector<vector<int>>& bombs) {
int n=bombs.size();
vector<int>graph[n+1];
int i,j;
for(i=0;i<n;i++)
{
bombs[i].push_back(i);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
continue;
double dis1=eucDis(bombs[i][0],bombs[i][1],bombs[j][0],
bombs[j][1]);
if(dis1<=bombs[i][2])
{
int node1=bombs[i][3];
int node2=bombs[j][3];
graph[node1].push_back(node2);
}
}
}
int maxi=1;
for(i=0;i<n;i++)
{
int c=0;
if(graph[i].empty())
continue;
vector<int>vis(n+1,0);
dfs(i,vis,graph,c);
maxi=max(maxi,c);
}
return maxi;
}
}; | /**
* @param {number[][]} bombs
* @return {number}
*/
var maximumDetonation = function(bombs) {
if(bombs.length <= 1) return bombs.length;
let adj = {}, maxSize = 0;
const checkIfInsideRange = (x, y, center_x, center_y, radius) =>{
return ( (x-center_x)**2 + (y-center_y)**2 <= radius**2 )
}
//CREATE ADJACENCY MATRIX
for(let i = 0;i<bombs.length;i++){
for(let j = i+1;j<bombs.length;j++){
if(!adj[i]) adj[i] = [];
if(!adj[j]) adj[j] = [];
let bombOne = bombs[i];
let bombTwo = bombs[j];
let fir = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombOne[2]);
if(fir) adj[i].push(j);
let sec = checkIfInsideRange(bombOne[0], bombOne[1], bombTwo[0], bombTwo[1], bombTwo[2]);
if(sec) adj[j].push(i);
}
}
//DEPTH FIRST SEARCH TO FIND ALL BOMBS TRIGGERED BY NODE
const dfs = (node, visited)=>{
let detonated = 1;
visited[node] = true;
let childs = adj[node] || []
for(let child of childs){
if(visited[child]) continue;
detonated += dfs(child, visited)
}
maxSize = Math.max(maxSize, detonated)
return detonated;
}
for(let i = 0 ;i<bombs.length;i++){
dfs(i, {})
}
return maxSize
}; | Detonate the Maximum Bombs |
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.
Return the number of hills and valleys in nums.
Example 1:
Input: nums = [2,4,1,1,6,5]
Output: 3
Explanation:
At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.
At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill.
At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.
At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.
At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.
At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley.
There are 3 hills and valleys so we return 3.
Example 2:
Input: nums = [6,6,5,5,4,1]
Output: 0
Explanation:
At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.
At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.
At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.
At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.
At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.
At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.
There are 0 hills and valleys so we return 0.
Constraints:
3 <= nums.length <= 100
1 <= nums[i] <= 100
| class Solution:
def countHillValley(self, nums: List[int]) -> int:
c = 0
i = 1
while i <len(nums)-1:
j = i+1
while j < len(nums)-1 and nums[j] == nums[i]:
j += 1
if (nums[i-1] > nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):
c += 1
i = j
return c | class Solution {
public int countHillValley(int[] nums) {
int result = 0;
// Get head start. Find first index for which nums[index] != nums[index-1]
int start = 1;
while(start < nums.length && nums[start] == nums[start-1])
start++;
int prev = start-1; //index of prev different value num
for(int i=start; i<nums.length-1; i++) {
if(nums[i] == nums[i+1]) //If numbers are same, simply ignore them
continue;
else {
if(nums[i] > nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number
result++;
if(nums[i] < nums[prev] && nums[i] < nums[i+1])
result++;
prev = i; // Now your current number will become prev number.
}
}
return result;
}
} | class Solution {
public:
int countHillValley(vector<int>& nums) {
// taking a new vector
vector<int>v;
v.push_back(nums[0]);
//pushing unique elements into new vector
for(int i=1;i<nums.size();i++){
if(nums[i]!=nums[i-1]){
v.push_back(nums[i]);
}
}
int c=0;
//checking for valley or hill
for(int i=1;i<v.size()-1;i++){
if(v[i]>v[i-1] and v[i]>v[i+1] or v[i]<v[i-1] and v[i]<v[i+1]){
c++;
}
}
return c;
}
}; | var countHillValley = function(nums) {
let previous;
let count = 0;
for (let i=0; i<nums.length; i++) {
if (previous === undefined) {
previous = i;
continue;
}
if (nums[i-1] === nums[i]) {
continue;
}
let nextCheck = i + 1;
while(nums[nextCheck] === nums[i]) {
nextCheck++;
}
if(nums[i] > nums[previous] && nums[i] > nums[nextCheck]) {
count++;
}
if(nums[i] < nums[previous] && nums[i] < nums[nextCheck]) {
count++;
}
previous = i;
i = nextCheck - 1;
}
return count;
}; | Count Hills and Valleys in an Array |
You are given a string s. Reorder the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.
Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Example 2:
Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters.
| from collections import Counter
class Solution:
def sortString(self, s: str) -> str:
counter = Counter(s)
alphabets = "abcdefghijklmnopqrstuvwxyz"
rev_alphabets = alphabets[::-1]
total = len(s)
res = []
while total > 0:
for c in alphabets:
if counter[c]:
res.append(c)
counter[c] -= 1
total -= 1
for c in rev_alphabets:
if counter[c]:
res.append(c)
counter[c] -= 1
total -= 1
return "".join(res) | class Solution {
public String sortString(String s) {
StringBuilder result = new StringBuilder();
int[] freq = new int[26];
for(char c: s.toCharArray()){
freq[c-'a']++;
}
int remaining = s.length();
while(remaining!=0){
for(int i=0;i<26&&remaining!=0;i++){
if(freq[i]!=0){
freq[i]--;
result.append((char)(i+'a'));
remaining--;
}
}
for(int i=25;i>=0&&remaining!=0;i--){
if(freq[i]!=0){
freq[i]--;
result.append((char)(i+'a'));
remaining--;
}
}
}
return result.toString();
}
} | class Solution {
public:
string sortString(string s) {
int count [26]={0};
for(int i =0 ;i< s.size();i++){
char ch = s[i];
count[ch-'a']++;
}
string res ;
while(res.size()!=s.size()){
for(int i = 0 ;i<26;i++){
if(count[i] >0) {
char ch = i+'a';
res += ch;
count[i]--;
}
}
for(int i = 25 ;i>=0 ;i--){
if(count[i] >0){
char ch= i+'a';
res += ch;
count[i]--;
}
}
}
return res ;
}
}; | /**
* @param {string} s
* @return {string}
*/
var sortString = function(s) {
const counts = [...s].reduce((acc, cur) => (acc[cur.charCodeAt() - 97] += 1, acc), new Array(26).fill(0));
const result = [];
const pick = (code) => {
if (counts[code]) {
result.push(String.fromCharCode(code + 97));
counts[code] -= 1;
}
}
while (result.length < s.length) {
for (let i = 0; i < counts.length; i++) pick(i);
for (let i = 0; i < counts.length; i++) pick(counts.length - 1 - i);
}
return result.join('');
}; | Increasing Decreasing String |
Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example 1:
Input: nums = [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
Constraints:
1 <= nums.length <= 104
-109 <= nums[i] <= 109
| class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
count=0
for i in range(len(nums)):
a=nums[i]
c=1
for j in range(i+1, len(nums)):
if nums[j]>a:
a=nums[j]
c+=1
else:
break
count=max(count, c)
return count | class Solution {
public int findLengthOfLCIS(int[] nums) {
int count = 1;
int maxCount = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
count++;
} else {
maxCount = Math.max(count, maxCount);
count = 1;
}
}
maxCount = Math.max(count, maxCount);
return maxCount;
}
} | class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int maxLength = 1;
int currLength = 1;
int i = 0;
int j = 1;
while(j<nums.size()){
if(nums[j] > nums[i]){
currLength++;
i++;
j++;
if(currLength > maxLength) maxLength = currLength;
} else{
currLength = 1;
i = j;
j++;
}
}
return maxLength;
}
}; | var findLengthOfLCIS = function(nums) {
let res = 0;
let curr = 1;
nums.forEach((num, idx) => {
if (num < nums[idx + 1]) {
curr++;
}
else curr = 1;
res = Math.max(res, curr);
})
return res;
}; | Longest Continuous Increasing Subsequence |
A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.
Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.
Example 1:
Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
Example 2:
Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
Constraints:
2 <= nums.length <= 5 * 104
0 <= nums[i] <= 5 * 104
| class Solution:
def maxWidthRamp(self, nums: List[int]):
st=[]
n=len(nums)
for i in range(n):
if len(st)==0 or nums[st[-1]]>=nums[i]:
st.append(i)
print(st)
max_idx=-1
for j in range(n-1,-1,-1):
while len(st) and nums[st[-1]]<=nums[j]:
prev=st.pop()
max_idx=max(max_idx,j-prev)
return max_idx | class Solution {
public int maxWidthRamp(int[] nums) {
Stack<Integer> s = new Stack<>();
int res = 0;
for(int i = 0; i< nums.length; i++){
if(!s.isEmpty() && nums[s.peek()]<=nums[i]) {
res = Math.max(res, i-s.peek());
continue;
}
s.push(i);
}
int i = nums.length-1;
while(!s.isEmpty() && i>=0){
if(nums[s.peek()]<=nums[i]){
res = Math.max(res, i-s.peek());
s.pop();
}else{
i--;
}
}
return res;
}
} | class Solution {
public:
int maxWidthRamp(vector<int>& nums) {
int n=nums.size();
if(n==2){
if(nums[0]<=nums[1])return 1;
return 0;
}
stack<int>st;
for(int i=0;i<n;i++){
if(st.empty()||nums[i]<nums[st.top()]){st.push(i);} // maintaining a monotonic decreasing stack
}
int ramp=0;
for(int i=n-1;i>=0;i--){
while(!st.empty() && nums[i]>=nums[st.top()] ){
ramp=max(ramp,i-st.top());
st.pop();
}
}
return ramp;
}
}; | var maxWidthRamp = function(nums) {
let stack = [], ans = 0;
for (let i = 0; i < nums.length; i++) {
let index = lower_bound(stack, i);
ans = Math.max(ans, i - index);
if (!stack.length || nums[i] < nums[stack[stack.length - 1]]) stack.push(i);
}
return ans;
function lower_bound(arr, index) {
if (!arr.length) return index;
let low = 0, high = arr.length - 1;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (nums[arr[mid]] <= nums[index]) high = mid;
else low = mid + 1;
}
return nums[arr[low]] <= nums[index] ? arr[low] : index;
}
}; | Maximum Width Ramp |
Implement the RandomizedSet class:
RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.
Example 1:
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
Constraints:
-231 <= val <= 231 - 1
At most 2 * 105 calls will be made to insert, remove, and getRandom.
There will be at least one element in the data structure when getRandom is called.
| class RandomizedSet:
def __init__(self):
self.data = set()
def insert(self, val: int) -> bool:
if val not in self.data:
self.data.add(val)
return True
return False
def remove(self, val: int) -> bool:
if val in self.data:
self.data.remove(val)
return True
return False
def getRandom(self) -> int:
return random.choice(list(self.data)) | class RandomizedSet {
HashMap<Integer, Integer> map;
ArrayList<Integer> list;
Random rand;
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
rand = new Random();
}
public boolean insert(int val) {
if (!map.containsKey(val)){
map.put(val, list.size());
list.add(val);
return true;
}
return false;
}
public boolean remove(int val) {
if (map.containsKey(val)){
int index = map.get(val);
int last = list.get(list.size() - 1);
if (index != list.size() - 1){
list.set(index, last);
map.put(last, index);
}
list.remove(list.size() - 1);
map.remove(val);
return true;
}
return false;
}
public int getRandom() {
int r = rand.nextInt(list.size());
return list.get(r);
}
} | class RandomizedSet {
public:
unordered_map<int, int> mp;
vector<int> v;
RandomizedSet() {
}
bool insert(int val) {
if(mp.find(val) != mp.end()) return false;
mp[val] = v.size();
v.push_back(val);
return true;
}
bool remove(int val) {
if(mp.find(val) != mp.end()){
v[mp[val]] = v.back();
mp[v.back()] = mp[val];
v.pop_back();
mp.erase(val);
return true;
}
return false;
}
int getRandom() {
return v[rand()%v.size()];
}
}; | var RandomizedSet = function() {
this._data = [];
this._flatData = [];
};
RandomizedSet.prototype.hash = function(val) {
return val % 1e5;
}
RandomizedSet.prototype.insert = function(val) {
const hash = this.hash(val);
let basket = this._data[hash];
for (let i = 0; i < basket?.length; i++) {
if (basket[i][0] === val) { return false; }
}
if (!basket) {
this._data[hash] = [[val, this._flatData.length]];
} else {
this._data[hash].push([val, this._flatData.length]);
}
this._flatData.push(val);
return true;
};
RandomizedSet.prototype.remove = function(val) {
const hash = this.hash(val);
let basket = this._data[hash];
if (!basket) { return false; }
for (let i = 0; i < basket.length; i++) {
const currBasket = basket[i];
if (currBasket[0] === val) {
const idxInFlat = currBasket[1];
const reassignedValueInFlat = del(this._flatData, idxInFlat);
// Write new address in _data if needed
if (reassignedValueInFlat) {
this._data[this.hash(reassignedValueInFlat)].forEach(item => {
if (item[0] === reassignedValueInFlat) {
item[1] = idxInFlat;
return; // from forEach
}
});
}
// Delete from _data
del(basket, i);
return true;
}
}
return false;
};
RandomizedSet.prototype.getRandom = function() {
return this._flatData[getRandomInt(0, this._flatData.length - 1)];
};
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function del(arr, idx) {
if (!arr.length) { return null; }
if (idx === arr.length - 1) { arr.pop(); return null; }
arr[idx] = arr.pop();
return arr[idx];
} | Insert Delete GetRandom O(1) |
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
| class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
sol=(a,b)
return sum(sol)
``` | class Solution {
public int getSum(int a, int b) {
return Integer.sum(a, b);
}
} | class Solution {
public:
int getSum(int a, int b) {
vector<int> arr = {a,b};
return accumulate(arr.begin(),arr.end(),0);
}
}; | /**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
if (a==0){
return b;
}
else if (b==0){
return a;
}
else{
return getSum((a^b),(a&b)<<1);
}
}; | Sum of Two Integers |
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.
The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Example 2:
Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
Example 3:
Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.
Constraints:
1 <= firstLen, secondLen <= 1000
2 <= firstLen + secondLen <= 1000
firstLen + secondLen <= nums.length <= 1000
0 <= nums[i] <= 1000
| class Solution:
def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:
n = len(nums)
p = [0]
for el in nums:
p.append(p[-1] + el)
msum = 0
for f, s in [(firstLen, secondLen), (secondLen, firstLen)]:
for i in range(f - 1, n - s + 1):
for j in range(i + 1, n - s + 1):
l = p[i + 1] - p[i - f + 1]
r = p[j + s] - p[j]
msum = max(msum, l + r)
return msum | class Solution {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
int []dp1=new int[nums.length];
int []dp2=new int[nums.length];
int sum=0;
for(int i=0;i<nums.length;i++){
if(i<firstLen){
sum+=nums[i];
dp1[i]=sum;
}else{
sum+=nums[i]-nums[i-firstLen];
dp1[i]=Math.max(sum,dp1[i-1]);
}
}
sum=0;
for(int i=nums.length-1;i>=0;i--){
if(i+secondLen>=nums.length){
sum+=nums[i];
dp2[i]=sum;
}else{
sum+=nums[i]-nums[i+secondLen];
dp2[i]=Math.max(sum,dp2[i+1]);
}
}
int max=0;
for(int i=firstLen-1;i<nums.length-secondLen;i++){
max=Math.max(max,dp1[i]+dp2[i+1]);
}
int max1=max;
dp1=new int[nums.length];
dp2=new int[nums.length];
sum=0;
for(int i=0;i<nums.length;i++){
if(i<secondLen){
sum+=nums[i];
dp1[i]=sum;
}else{
sum+=nums[i]-nums[i-secondLen];
dp1[i]=Math.max(sum,dp1[i-1]);
}
}
sum=0;
for(int i=nums.length-1;i>=0;i--){
if(i+firstLen>=nums.length){
sum+=nums[i];
dp2[i]=sum;
}else{
sum+=nums[i]-nums[i+firstLen];
dp2[i]=Math.max(sum,dp2[i+1]);
}
}
max=0;
for(int i=secondLen-1;i<nums.length-firstLen;i++){
max=Math.max(max,dp1[i]+dp2[i+1]);
}
int max2=max;
return Math.max(max1,max2);
}
} | class Solution {
public:
int solve(vector<int>& prefixSum, int n, int firstLen, int secondLen){
vector<int> dp(n, 0);
dp[n-secondLen] = prefixSum[n]-prefixSum[n-secondLen];
for(int i=n-secondLen-1; i>=0; i--){
dp[i] = max(dp[i+1], prefixSum[i+secondLen]-prefixSum[i]);
}
dp[firstLen] = dp[firstLen] + prefixSum[firstLen]-prefixSum[0];
for(int i=firstLen+1; i<=n-secondLen; i++){
dp[i] = max(dp[i-1], dp[i] + (prefixSum[i]-prefixSum[i-firstLen]));
}
return *max_element(dp.begin(), dp.end());
}
int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
int n = nums.size();
vector<int> prefixSum(n+1, 0);
for(int i=1; i<=n; i++){
prefixSum[i] = prefixSum[i-1] + nums[i-1];
}
return max(solve(prefixSum, n, firstLen, secondLen), solve(prefixSum, n, secondLen, firstLen));
}
}; | var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) {
function helper(arr, x, y)
{
const n = arr.length;
let sum = 0;
const dp1 = []; // store left x sum
const dp2 = []; // store right y sum
for(let i = 0; i<n; i++)
{
if(i<x) {
sum += arr[i];
dp1[i] = sum;
}
else {
sum += arr[i] - arr[i-x];
dp1[i] = Math.max(dp1[i-1], sum);
}
}
sum = 0;
for(let i = n-1; i>=0; i--)
{
if(i>=n-y)
{
sum += arr[i];
dp2[i] = sum;
}
else
{
sum += arr[i] - arr[i+y];
dp2[i] = Math.max(dp2[i+1], sum);
}
}
let max = -Infinity;
for(let i = x-1; i< n-y; i++)
{
max = Math.max(max, dp1[i] + dp2[i+1]);
}
return max;
}
return Math.max(helper(nums, firstLen, secondLen),
helper(nums, secondLen, firstLen));
}; | Maximum Sum of Two Non-Overlapping Subarrays |
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.
Train tickets are sold in three different ways:
a 1-day pass is sold for costs[0] dollars,
a 7-day pass is sold for costs[1] dollars, and
a 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel.
For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
Constraints:
1 <= days.length <= 365
1 <= days[i] <= 365
days is in strictly increasing order.
costs.length == 3
1 <= costs[i] <= 1000
| class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
min_cost = float('inf')
que = deque()
# enqueue the possible state of day 1
que.append((days[0], costs[0]))
que.append((days[0]+7-1, costs[1]))
que.append((days[0]+30-1, costs[2]))
last_day = days[-1]
for i in range(1, len(days)):
for _ in range(len(que)):
node = que.popleft()
if node[0] < days[i]:
# try taking all the three pass on that day and enqueue
que.append((days[i], node[1]+costs[0]))
if days[i] + 7 - 1 >= last_day:
min_cost = min(min_cost, node[1] + costs[1])
else:
que.append((days[i]+7-1, node[1]+costs[1]))
if days[i] + 30 - 1 >= last_day:
min_cost = min(min_cost, node[1] + costs[2])
else:
que.append((days[i]+30-1, node[1]+costs[2]))
else:
que.append(node)
for _ in range(len(que)):
node = que.popleft()
min_cost = min(min_cost, node[1])
return min_cost | class Solution {
public int mincostTickets(int[] days, int[] costs) {
HashSet<Integer> set = new HashSet<>();
for(int day: days) set.add(day);
int n = days[days.length - 1];
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 1; i <= n; i++){
if(!set.contains(i)){
dp[i] = dp[i - 1];
continue;
}
int a = dp[Math.max(0, i - 1)] + costs[0];
int b = dp[Math.max(0, i - 7)] + costs[1];
int c = dp[Math.max(0, i - 30)] + costs[2];
dp[i] = Math.min(a, Math.min(b, c));
}
return dp[n];
}
} | class Solution {
public:
int f(int i,int j,vector<int>& days,vector<int>& costs,vector<vector<int>>& dp) {
if (i==days.size()) return 0;
if (days[i]<j) return f(i+1,j,days,costs,dp);
if (dp[i][j]!=-1) return dp[i][j];
int x=costs[0]+f(i+1,days[i]+1,days,costs,dp);
int y=costs[1]+f(i+1,days[i]+7,days,costs,dp);
int z=costs[2]+f(i+1,days[i]+30,days,costs,dp);
return dp[i][j]=min(x,min(y,z));
}
int mincostTickets(vector<int>& days, vector<int>& costs) {
vector<vector<int>> dp(days.size(),vector<int>(days[days.size()-1]+1,-1));
return f(0,1,days,costs,dp);
}
}; | var mincostTickets = function(days, costs) {
let store = {};
for(let i of days) {
store[i] = true
}
let lastDay = days[days.length - 1]
let dp = new Array(days[days.length - 1] + 1).fill(Infinity);
dp[0] = 0;
for(let i = 1; i< days[days.length - 1] + 1; i++) {
if(!store[i]) {
dp[i] = dp[i-1];
continue;
}
dp[i] = costs[0] + dp[i-1];
dp[i] = Math.min(costs[1] + dp[Math.max(i - 7, 0)], dp[i]);
dp[i] = Math.min(costs[2] + dp[Math.max(i - 30, 0)], dp[i]);
}
return dp[lastDay]
}; | Minimum Cost For Tickets |
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:
If nums[i] is positive, move nums[i] steps forward, and
If nums[i] is negative, move nums[i] steps backward.
Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.
A cycle in the array consists of a sequence of indices seq of length k where:
Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
Every nums[seq[j]] is either all positive or all negative.
k > 1
Return true if there is a cycle in nums, or false otherwise.
Example 1:
Input: nums = [2,-1,1,2,2]
Output: true
Explanation:
There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...
The cycle's length is 3.
Example 2:
Input: nums = [-1,2]
Output: false
Explanation:
The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.
By definition the sequence's length must be strictly greater than 1 to be a cycle.
Example 3:
Input: nums = [-2,1,-1,-2,-2]
Output: false
Explanation:
The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.
Every nums[seq[j]] must be either all positive or all negative.
Constraints:
1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
nums[i] != 0
Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?
| class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
n = len(nums)
for i in range(n):
seen = set()
minval = float('inf')
maxval = float('-inf')
j = i
while j not in seen:
seen.add(j)
minval = min(minval, nums[j])
maxval = max(maxval, nums[j])
k = 1 + abs(nums[j]) // n
j = (k * n + j + nums[j]) % n
if j == i and len(seen) > 1 and (minval > 0 or maxval < 0):
return True
return False | class Solution {
public boolean circularArrayLoop(int[] nums) {
for (int i=0; i<nums.length; i++) {
boolean isForward = nums[i] > 0;
int slow = i;
int fast = i;
do {
slow = findNextIndex(nums, isForward, slow);
fast = findNextIndex(nums, isForward, fast);
if (fast != -1) {
fast = findNextIndex(nums, isForward, fast);
}
} while (slow != -1 && fast != -1 && slow != fast);
if (slow != -1 && slow == fast) {
return true;
}
}
return false;
}
private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {
boolean direction = arr[currentIndex] >= 0;
if (isForward != direction) {
return -1;
}
int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;
if (nextIndex < 0) {
nextIndex += arr.length;
}
if (nextIndex == currentIndex) {
nextIndex = -1;
}
return nextIndex;
}
} | class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
unordered_set<int>us;
for(int i{0};i<nums.size() && us.find(i)==us.end();i++){
unordered_map<int,int>um;
int index=0;
int j=i;
um[i];
bool flag1=0,flag2=0;
while(true){
if(nums.at(i)<0){
index=(nums.size()+nums.at(j)+j)%nums.size();
flag1=1;
}else{
index=(nums.at(j)+j)%nums.size();
flag2=1;
}
if(nums.at(index)>0 && flag1==1){
break;
}else if(nums.at(index)<0 && flag2==1){
break;
}
if(um.find(index)==um.end()){
um[index];
us.insert(index);
}else{
if(j==index){
break;
}
if(um.size()>1){
return true;
}else{
break;
}
}
j=index;
}
}
return false;
}
}; | var circularArrayLoop = function(nums) {
// cannot be a cycle if there are less than 2 elements
const numsLen = nums.length;
if (numsLen < 2) return false;
// init visited array
const visited = Array(numsLen).fill(false);
// check each index to see if a cycle can be produced
for (let i = 0; i < numsLen; i++) {
if (visited[i]) continue;
visited[i] = true;
// determine initial direction
const isPositive = nums[i] > 0;
// reset which indices were visited after each iteration
const visitedPerIdx = Array(numsLen).fill(false);
// reset cycle length and current index after each iteration
let cycleLen = 0,
currIdx = i;
// loop while cycle is valid
while (true) {
// break if current index moves cycle in opposite direction
if (isPositive !== nums[currIdx] > 0) break;
// calc next valid index
let nextIdx = (currIdx + nums[currIdx]) % numsLen;
// map negative index to a positive index
if (nextIdx < 0) nextIdx += numsLen;
// break if cycle points to same index
if (currIdx === nextIdx) break;
cycleLen++;
// a cycle is found when the index has already been visited in the current outer iteration, and
// the cycle length is greater than 1.
if (visitedPerIdx[nextIdx] && cycleLen > 1) return true;
visitedPerIdx[nextIdx] = true;
visited[nextIdx] = true;
// set curr index to new index
currIdx = nextIdx;
}
}
return false;
}; | Circular Array Loop |
The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.
For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.
Example 1:
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
Output: ["AAAAACCCCC","CCCCCAAAAA"]
Example 2:
Input: s = "AAAAAAAAAAAAA"
Output: ["AAAAAAAAAA"]
Constraints:
1 <= s.length <= 105
s[i] is either 'A', 'C', 'G', or 'T'.
| class Solution(object):
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
seqs = {}
i = 0
while i+10 <= len(s):
curr = s[i:i+10]
if curr in seqs:
seqs[curr] = seqs[curr] + 1
else:
seqs[curr] = 1
i += 1
repeats = []
for seq in list(seqs.keys()):
if seqs[seq] > 1:
repeats.append(seq)
return repeats | class Solution {
public List<String> findRepeatedDnaSequences(String s) {
HashMap<String,Integer> map =new HashMap();
int i=0;
int j=0;
int k=10;
StringBuilder sb=new StringBuilder("");
while(j<s.length()){
sb.append(s.charAt(j));
if(j-i+1<k){
j++;
}else if(j-i+1==k){
if(!map.containsKey(sb.toString())){
map.put(sb.toString(),1);
}else{
map.put(sb.toString(),map.get(sb.toString())+1);
}
sb.deleteCharAt(0);
i++;
j++;
}
}
List<String> list=new ArrayList();
for(Map.Entry<String,Integer> mapElement:map.entrySet()){
if(mapElement.getValue()>1){
list.add(mapElement.getKey());
}
}
return list;
}
} | class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
unordered_map<string,int> freq;
int start = 0 , end = 9;
while(end < s.size()){
bool flag = true;
for(int i = start ; i <= end ; i++){
if(s[i] == 'A' or s[i] == 'C' or s[i] == 'G' or s[i] == 'T') continue;
else {flag = false ; break ;}
}
if(flag){
string temp = s.substr(start , 10);
freq[temp]++;
}
start++;
end++;
}
vector<string> ans;
for(auto it : freq){
if(it.second >= 2) ans.push_back(it.first);
}
return ans;
}
}; | // 187. Repeated DNA Sequences
var findRepeatedDnaSequences = function(s) {
let map = {};
let res = [];
for (let i = 0; i <= s.length-10; i++) {
let s10 = s.substring(i, i+10);
map[s10] = (map[s10] || 0) + 1;
if (map[s10] === 2) res.push(s10);
}
return res;
}; | Repeated DNA Sequences |
You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Constraints:
1 <= croakOfFrogs.length <= 105
croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.
| class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
c = r = o = a = k = max_frog_croak = present_frog_croak = 0
# need to know, at particular point,
# what are the max frog are croaking,
for i, v in enumerate(croakOfFrogs):
if v == 'c':
c += 1
# c gives a signal for a frog
present_frog_croak += 1
elif v == 'r':
r += 1
elif v == 'o':
o += 1
elif v == 'a':
a += 1
else:
k += 1
# frog stop croaking
present_frog_croak -= 1
max_frog_croak = max(max_frog_croak, present_frog_croak)
# if any inoder occurs;
if c < r or r < o or o < a or a < k:
return -1
# if all good, else -1
if present_frog_croak == 0 and c == r and r == o and o == a and a == k:
return max_frog_croak
return -1 | class Solution {
public int minNumberOfFrogs(String croakOfFrogs) {
int[] index = new int[26];
String corak = "croak";
// Giving index to each characters
for (int i = 0; i < corak.length(); ++i)
index[corak.charAt(i) - 'a'] = i;
int ans = 0, sum = 0;
int[] count = new int[5];
for (char c : croakOfFrogs.toCharArray()) {
int i = index[c - 'a'];
// If it is not 'c' it will decrease the sum
if (c != 'c') {
if (count[i - 1]-- <= 0) return -1;
sum--;
}
// If it is not 'k' it will increase the sum
if (c != 'k') {
count[i]++;
sum++;
}
ans = Math.max(ans, sum);
}
return sum == 0 ? ans : -1;
}
} | class Solution {
public:
int minNumberOfFrogs(string croakOfFrogs) {
unordered_map<char,int> mp;
int size=croakOfFrogs.size();
for(int i=0;i<size;i++)
{
mp[croakOfFrogs[i]]++;
if(mp['c']<mp['r'] || mp['r']<mp['o'] || mp['o']<mp['a'] || mp['a']<mp['k'])
return -1;
}
int count=mp[croakOfFrogs[0]];
for(auto i:croakOfFrogs)
{
if(count!=mp[i])
return -1;
}
int ans=0;
int i=0;
int temp=0;
for(i=0;i<size;i++)
{
if(croakOfFrogs[i]=='c')
{
temp++;
}
else if(croakOfFrogs[i]=='k')
{
temp--;
}
if(temp>ans)
ans=temp;
}
return ans;
}
}; | var minNumberOfFrogs = function(croakOfFrogs) {
const croakArr = new Array(5).fill(0); //Array to store occurence of each char
let overlap = 0; //Store the number of overlaps
for(let i = 0; i < croakOfFrogs.length; i++) {
switch(croakOfFrogs[i]) {
case 'c':
croakArr[0] += 1;
//Check if new start, is overlapping with others
if((croakArr[0] - croakArr[4] - overlap) > 1) {
++overlap;
}
break;
case 'r':
//Condition to check if r comes before c
if(croakArr[0] <= croakArr[1]) return -1;
croakArr[1] += 1;
break;
case 'o':
//Condition to check if o comes before r
if(croakArr[1] <= croakArr[2]) return -1;
croakArr[2] += 1;
break;
case 'a':
//Condition to check if a comes before o
if(croakArr[2] <= croakArr[3]) return -1;
croakArr[3] += 1;
break;
case 'k':
//Condition to check if k comes before a
if(croakArr[3] <= croakArr[4]) return -1;
croakArr[4] += 1;
break;
}
}
//Check if all items of array have same count else return -1
//If all items have same count return overlap + 1
return (Math.max(...croakArr) === Math.min(...croakArr)) ? overlap + 1 : -1;
}; | Minimum Number of Frogs Croaking |
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
Example 1:
Input: n = 3
Output: 5
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 19
| class Solution(object):
def numTrees(self, n):
if n == 0 or n == 1:
return 1
# Create 'sol' array of length n+1...
sol = [0] * (n+1)
# The value of the first index will be 1.
sol[0] = 1
# Run a loop from 1 to n+1...
for i in range(1, n+1):
# Within the above loop, run a nested loop from 0 to i...
for j in range(i):
# Update the i-th position of the array by adding the multiplication of the respective index...
sol[i] += sol[j] * sol[i-j-1]
# Return the value of the nth index of the array to get the solution...
return sol[n] | class Solution {
public int numTrees(int n) {
// Create 'sol' array of length n+1...
int[] sol = new int[n+1];
// The value of the first index will be 1.
sol[0] = 1;
// Run a loop from 1 to n+1...
for(int i = 1; i <= n; i++) {
// Within the above loop, run a nested loop from 0 to i...
for(int j = 0; j < i; j++) {
// Update the i-th position of the array by adding the multiplication of the respective index...
sol[i] += sol[j] * sol[i-j-1];
}
}
// Return the value of the nth index of the array to get the solution...
return sol[n];
}
} | class Solution {
public:
int catalan (int n,vector<int> &dp)
{
if(n<=1)
return 1;
int ans =0;
for(int i=0;i<n;i++)
{
ans+=catalan(i,dp)*catalan(n-1-i,dp);
}
return ans;
}
int numTrees(int n) {
vector<int> dp(n+1,-1);
dp[0] = 1;
dp[1] = 1;
for(int i=2;i<=n;i++)
{
int ans = 0;
for(int j=0;j<i;j++)
{
ans += dp[j]*dp[i-1-j];
}
dp[i] = ans;
}
return dp[n];
// return catalan(n,dp);
}
}; | var numTrees = function(n) {
// Create 'sol' array to store the solution...
var sol = [1, 1];
// Run a loop from 2 to n...
for (let i = 2; i <= n; i++) {
sol[i] = 0;
// Within the above loop, run a nested loop from 1 to i...
for (let j = 1; j <= i; j++) {
// Update the i-th position of the array by adding the multiplication of the respective index...
sol[i] += sol[i - j] * sol[j - 1];
}
}
// Return the value of the nth index of the array to get the solution...
return sol[n];
}; | Unique Binary Search Trees |
Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.
The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.
Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.
Example 1:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
Output: [3,1,5]
Explanation:
The restaurants are:
Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1]
After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).
Example 2:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
Output: [4,3,2,1,5]
Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.
Example 3:
Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
Output: [4,5]
Constraints:
1 <= restaurants.length <= 10^4
restaurants[i].length == 5
1 <= idi, ratingi, pricei, distancei <= 10^5
1 <= maxPrice, maxDistance <= 10^5
veganFriendlyi and veganFriendly are 0 or 1.
All idi are distinct.
| class Solution:
def f_fcn(self,restaurants, veganFriendly, maxPrice, maxDistance):
f_lst = filter(lambda x: (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or
(veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance), restaurants)
return f_lst
def h_fcn(self,lst):
return([lst[0], lst[1]])
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
res = map(self.h_fcn, self.f_fcn(restaurants, veganFriendly, maxPrice, maxDistance))
return map(lambda x: x[0], sorted(res, key=lambda x: (-x[1], -x[0]))) | class Restaurant {
int id, rating;
Restaurant(int id, int rating) {
this.id = id;
this.rating = rating;
}
}
class RestaurantComparator implements Comparator<Restaurant> {
@Override
public int compare(Restaurant r1, Restaurant r2) {
return r1.rating == r2.rating ? r2.id - r1.id : r2.rating - r1.rating;
}
}
class Solution {
public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
PriorityQueue<Restaurant> heap = new PriorityQueue<>(new RestaurantComparator());
if(veganFriendly == 1) {
for(int[] restaurant: restaurants) {
if(restaurant[2] == 1 && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {
heap.offer(new Restaurant(restaurant[0], restaurant[1]));
}
}
} else {
for(int[] restaurant: restaurants) {
if(restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {
heap.offer(new Restaurant(restaurant[0], restaurant[1]));
}
}
}
List<Integer> answer = new ArrayList<>();
while(!heap.isEmpty()) {
answer.add(heap.poll().id);
}
return answer;
}
} | //comparator class for sorting restaurants by their rating
class comp{
public:
bool operator ()(vector<int>a,vector<int>b){
//same rating then sort by ids
if(a[1]==b[1]) return a[0]>b[0];
return a[1]>b[1];
}
};
class Solution {
public:
vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance)
{ //sort restaurants by their rating
sort(restaurants.begin(),restaurants.end(),comp());
vector<int>ans;
for(int i=0;i<restaurants.size();i++){
//veganfriendly
if(veganFriendly)
{
// store ids who satisfy the constraints
if(restaurants[i][2]==veganFriendly and restaurants[i][3]<=maxPrice and restaurants[i][4]<=maxDistance)
{
ans.push_back(restaurants[i][0]);
}
}
// non vegan
else{
// store ids who satisfy the constraints
if(restaurants[i][3]<=maxPrice and restaurants[i][4]<=maxDistance)
{
ans.push_back(restaurants[i][0]);
}
}
}
return ans;
}
}; | var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) {
let result = []
// veganFriendly filter
if(veganFriendly === 1){
restaurants = restaurants.filter(restaurant=> restaurant[2] === 1)
}
//max price
restaurants = restaurants.filter(restaurant=>restaurant[3]<=maxPrice)
// max distance
restaurants = restaurants.filter(restaurant=>restaurant[4]<=maxDistance)
restaurants.sort((a,b)=>b[1]-a[1])
let tempArr = []
for(let i=0; i<restaurants.length;i++){
if(restaurants[i+1] && restaurants[i][1]===restaurants[i+1][1] ){
tempArr.push(restaurants[i][0])
tempArr.push(restaurants[i+1][0])
i++
}
else{
if(tempArr.length>0){
tempArr.sort((a,b)=>b-a)
result =[...result,...tempArr]
tempArr=[]
}
result.push(restaurants[i][0])
}
}
return result
}; | Filter Restaurants by Vegan-Friendly, Price and Distance |
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.
Your task is to move the box 'B' to the target position 'T' under the following rules:
The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).
The character '.' represents the floor which means a free cell to walk.
The character '#' represents the wall which means an obstacle (impossible to walk there).
There is only one box 'B' and one target cell 'T' in the grid.
The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.
The player cannot walk through the box.
Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.
Example 1:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#",".","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.
Example 2:
Input: grid = [["#","#","#","#","#","#"],
["#","T","#","#","#","#"],
["#",".",".","B",".","#"],
["#","#","#","#",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: -1
Example 3:
Input: grid = [["#","#","#","#","#","#"],
["#","T",".",".","#","#"],
["#",".","#","B",".","#"],
["#",".",".",".",".","#"],
["#",".",".",".","S","#"],
["#","#","#","#","#","#"]]
Output: 5
Explanation: push the box down, left, left, up and up.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid contains only characters '.', '#', 'S', 'T', or 'B'.
There is only one character 'S', 'B', and 'T' in the grid.
| class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
m,n=len(grid),len(grid[0])
q=deque()
start,target,box=(0,0),(0,0),(0,0)
for i in range(m):
for j in range(n):
if grid[i][j]=="B":
box=(i,j)
elif grid[i][j]=="T":
target=(i,j)
elif grid[i][j]=="S":
start=(i,j)
q.append((box[0],box[1],0,start[0],start[1]))
visited=set()
directions=((1,0,-1,0),(0,1,0,-1),(-1,0,1,0),(0,-1,0,1))
visited.add(box+box)
def solve(i,j,bi,bj):
nonlocal seen
if (i,j)==(bi,bj):
return True
ans=False
for d in directions:
ni,nj=i+d[0],j+d[1]
if 0<=ni<m and 0<=nj<n and (ni,nj) not in seen and grid[ni][nj]!="#":
seen.add((ni,nj))
ans=ans or solve(ni,nj,bi,bj)
if ans: return ans
return ans
while q:
i,j,pushes,si,sj=q.popleft()
if (i,j)==target:
return pushes
if pushes>m+n:
return -1
for d in directions:
ni,nj,bi,bj=i+d[0],j+d[1],i+d[2],j+d[3]
if 0<=ni<m and 0<=nj<n and (ni,nj,i,j) not in visited and grid[ni][nj]!="#" and 0<=bi<m and 0<=bj<n and grid[bi][bj]!="#":
seen=set()
seen.add((i,j))
grid[i][j]=="#"
res=solve(si,sj,bi,bj)
grid[i][j]="."
if not res:
continue
visited.add((ni,nj,i,j))
q.append((ni,nj,pushes+1,i,j))
return -1 | /**
Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves)
Uses BFS/A* Algorithm to visit valid transition states
Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations
*/
class Solution {
private int targetRow;
private int targetCol;
private char[][] grid;
private static int[][] DIRS = {
{1,0}, //Down
{-1,0},//Up
{0,1}, //Right
{0,-1} //Left
};
/**
State holds shopkeeper and box location, as well as how many times the box has been pushed
*/
class State implements Comparable<State>{
int personRow;
int personCol;
int boxRow;
int boxCol;
int boxPushes;
public State(int personRow, int personCol, int boxRow, int boxCol, int boxPushes){
this.personRow = personRow;
this.personCol = personCol;
this.boxRow = boxRow;
this.boxCol = boxCol;
this.boxPushes = boxPushes;
}
// Override equals - used along with hashcode when we have visited HashSet
public boolean equals(Object o){
State other = (State) o;
return
this.personRow == other.personRow &&
this.personCol == other.personCol &&
this.boxRow == other.boxRow &&
this.boxCol == other.boxCol;
}
// Override the hashCode - Note: it's okay for this to have collisions
// But it won't due to the problem constraint that there is a bound on NxM dimensions
public int hashCode(){
return personRow *10_000 + personCol * 1_000 + boxRow * 100 + boxCol;
}
// Override to string method - helpful in debugging state.
public String toString(){
return "ShopKeeper:{row:"+personRow+", col:"+personCol+"}" +
"Box:{row:"+boxRow+", col:"+boxCol+"}";
}
// Implement comparable interface such that we return the state that
// has the possibility of lowest distance using box push count + Manhattan distance
public int compareTo(State other){
int minDistanceThis = this.boxPushes + distanceToTarget(this);
int minDistanceOther = other.boxPushes + distanceToTarget(other);
return Integer.compare(minDistanceThis, minDistanceOther);
}
}
// Calculates Manhattan distance
private int distanceToTarget(State state){
int yDiff = Math.abs(state.boxCol - targetCol);
int xDiff = Math.abs(state.boxRow - targetRow);
return yDiff + xDiff;
}
/**
Given a state, compare box location to target location to determine if it is
a solution state.
*/
private boolean isSolutionState(State state){
return state.boxRow == targetRow && state.boxCol == targetCol;
}
/**
Given a state, finds all valid transition states.
This is accomplished by moving the ShopKeeper in all 4 directions and validate
- Next ShopKeeper location is in bounds and is not a wall
We have additional logic for when the next shopkeeper location is the box location:
- Get next box location, by pushing the same direction, again validate that
the next box location is in bounds, and is not a wall.
If it's a valid transition, create the new state with the new shop keeper location
and if the box moved, the new box location (also increment the number of box moves).
**/
private List<State> getNeighbors(State state){
int personRow = state.personRow;
int personCol = state.personCol;
int boxRow = state.boxRow;
int boxCol = state.boxCol;
List<State> states = new ArrayList<>();
for(int[] dir : DIRS){
int rowMove = dir[0];
int colMove = dir[1];
int personRowNew = personRow + rowMove;
int personColNew = personCol + colMove;
// Shopkeeper cannot move into wall or go out of bounds skip to next direction
if(!inBounds(personRowNew, personColNew) ||
isWall(personRowNew, personColNew)){
continue;
}
// Whether or not person will collide with box
boolean willPushBox = personRowNew == boxRow && personColNew == boxCol;
if(willPushBox){
int boxRowNew = boxRow + rowMove;
int boxColNew = boxCol + colMove;
// Validate box can be pushed - if so push box and add to neighbor states
if(inBounds(boxRowNew, boxColNew) &&
!isWall(boxRowNew, boxColNew)){
states.add(new State(personRowNew, personColNew, boxRowNew, boxColNew, state.boxPushes + 1));
}
} else {
//Shop keeper moved, but not box
states.add(new State(personRowNew, personColNew, boxRow, boxCol, state.boxPushes));
}
}
return states;
}
// Given row/col, return whether it is wall
private boolean isWall(int row, int col){
char cell = grid[row][col];
return cell == '#';
}
// Given row/col return whether is inBounds
private boolean inBounds(int row, int col){
int rows = grid.length;
int cols = grid[0].length;
if(row < 0 || col < 0 || row > rows-1 || col > cols-1){
return false;
}
return true;
}
/**
Returns initial state. Also finds and stores the target location.
*/
private State getInitialState(){
int shopKeeperRow=0;
int shopKeeperCol=0;
int boxRow = 0;
int boxCol = 0;
for(int r=0; r<grid.length; r++){
char[] row = grid[r];
for(int c=0; c<row.length; c++){
char cell = grid[r][c];
if(cell == 'T'){
this.targetRow = r;
this.targetCol = c;
}
else if(cell == 'B'){
boxRow = r;
boxCol = c;
} else if(cell == 'S'){
shopKeeperRow = r;
shopKeeperCol = c;
}
}
}
return new State(shopKeeperRow, shopKeeperCol, boxRow, boxCol, 0);
}
public int minPushBox(char[][] grid) {
this.grid = grid;
State initialState = getInitialState();
Queue<State> queue = new PriorityQueue<>();
Set<State> visited = new HashSet<>();
queue.offer(initialState);
// Explore every state using BSF and keep track of the best solution
while(!queue.isEmpty()){
State state = queue.poll();
if(visited.contains(state)){
continue;
}
visited.add(state);
/*
Note: the reason we can return the first solution state we find, is because we are
using priority queue with minDistance heuristic which means the first solution we find
is guaranteed to be the optimal solution - (A* Algorithm)
*/
if(isSolutionState(state)){
return state.boxPushes;
}
for(State neighbor : getNeighbors(state)){
if(!visited.contains(neighbor)){
queue.offer(neighbor);
}
};
}
// No solution - return -1
return -1;
}
} | class Solution {
public:
pair<int,int> t; //target
pair<int,int> s; //source
pair<int,int> b; //box
// struct to store each member in priority queue
struct node {
int heuristic; // to find the dist between target and box
int dist; // to keep track of how much the box moved
pair<int,int> src; // to store the source
pair<int,int> dest; // to store the box location
};
struct comp {
bool operator()(node const& a, node const& b){
return a.heuristic + a.dist > b.heuristic + b.dist;
}
};
int direction[4][2]= {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int minPushBox(vector<vector<char>>& grid) {
int m=grid.size();
int n=grid[0].size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]=='T')
t={i,j};
else if(grid[i][j]=='B')
b={i,j};
else if(grid[i][j]=='S')
s={i,j};
}
}
priority_queue<node,vector<node>,comp> pq;
set<string> visited;
node initialState = node{manhattanDist(b.first,b.second),0,s,b};
string initialStr = hash(initialState);
pq.push(initialState);
while(!pq.empty()){
auto cur = pq.top();
pq.pop();
// we have reached the target return
if(cur.dest == t)
return cur.dist;
// hash the cur string and
string cur_vis = hash(cur);
if(visited.count(cur_vis)) continue;
// mark it as visited
visited.insert(cur_vis);
// in all the four directions
for(auto& dir:direction){
int sx = cur.src.first + dir[0];
int sy = cur.src.second + dir[1];
// if the new source is valid index
if(valid(sx,sy,grid)){
//if the source is equal to the where the box is
if(sx == cur.dest.first && sy == cur.dest.second){
int bx=cur.dest.first + dir[0];
int by=cur.dest.second + dir[1];
// if the box is at right position
if(valid(bx,by,grid)){
// increment the dist by 1 and update the source and box location
node updated = node{manhattanDist(bx,by),cur.dist+1,{sx,sy},{bx,by}};
pq.push(updated);
}
}else{
// update the new location of source
node updated = node{cur.heuristic,cur.dist,{sx,sy},cur.dest};
pq.push(updated);
}
}
}
}
// we cannot perform the operation
return -1;
}
string hash(node t){
stringstream ss;
ss<<t.src.first<<" "<<t.src.second<<" "<<t.dest.first<<" "<<t.dest.second;
return ss.str();
}
int manhattanDist(int i, int j){
return abs(t.first-i) + abs(t.second-j);
}
bool valid(int i, int j, vector<vector<char>>& g){
if(i<0 || j<0 || i>=g.size() || j>=g[0].size() || g[i][j]=='#') return false;
return true;
}
}; | /**
* @param {character[][]} grid
* @return {number}
*/
var minPushBox = function(grid) {
// common info & utils
const m = grid.length
const n = grid[0].length
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
const add = (a, b) => [a[0] + b[0], a[1] + b[1]]
const equals = (a, b) => a[0] === b[0] && a[1] === b[1]
const validate = ([x, y]) => x >= 0 && y >= 0 && x < m && y < n
const getKey = ([x, y]) => x * n + y
// find all player, ball, target, and free cells
const init = () => {
let player
let ball
let target
const freeSet = new Set()
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '.') {
freeSet.add(getKey([i, j]))
} else if (grid[i][j] === 'S') {
freeSet.add(getKey([i, j]))
player = [i, j]
} else if (grid[i][j] === 'B') {
freeSet.add(getKey([i, j]))
ball = [i, j]
} else if (grid[i][j] === 'T') {
freeSet.add(getKey([i, j]))
target = [i, j]
}
}
}
return { player, ball, target, freeSet }
}
const { player, ball, target, freeSet } = init()
const targetKey = getKey(target)
// detect whether two cells are connected
const connCache = new Map() // [x,y,x2,y2,x3,y3] => boolean
const getConnKey = (a, b, ball) => {
if (
a[0] > b[0] ||
a[0] === b[0] && a[1] > b[1]
) {
[a, b] = [b, a]
}
return [a[0], a[1], b[0], b[1], ball[0], ball[1]].join(',')
}
const isConnected = (a, b, ball) => {
if (a[0] === b[0] && a[1] === b[1]) {
return true
}
const connKey = getConnKey(a, b, ball)
if (connCache.has(connKey)) {
return connCache.get(connKey)
}
const bKey = getKey(b)
const ballKey = getKey(ball)
const visited = new Array(m * n).fill(false)
visited[getKey(a)] = true
const queue = [a]
while (queue.length) {
const cell = queue.shift()
for (let i = 0; i < dirs.length; i++) {
const next = add(cell, dirs[i])
if (validate(next)) {
const nextKey = getKey(next)
if (nextKey === bKey) {
connCache.set(connKey, true)
return true
}
if (
freeSet.has(nextKey) &&
nextKey !== ballKey &&
!visited[nextKey]
) {
visited[nextKey] = true
queue.push(next)
}
}
}
}
connCache.set(connKey, false)
return false
}
// solve the game
const getStateKey = ([x, y], [xx, yy]) => [x, y, xx, yy].join(',') // ball, player
const stateCache = new Set() // Set<stateKey>
let queue = [[ball, player]]
let count = 1
while (queue.length) {
const nextQueue = []
for (let i = 0; i < queue.length; i++) {
const [ball, player] = queue[i]
for (let j = 0; j < dirs.length; j++) {
const dir = dirs[j]
const reverseDir = [dir[0] ? -dir[0] : 0, dir[1] ? -dir[1] : 0]
const nextBall = add(ball, dir)
const nextPlayer = add(ball, reverseDir)
const nextBallKey = getKey(nextBall)
const nextPlayerKey = getKey(nextPlayer)
if (
validate(nextBall) &&
validate(nextPlayer) &&
freeSet.has(nextBallKey) &&
freeSet.has(nextPlayerKey)
) {
const nextStateKey = getStateKey(nextBall, nextPlayer)
if (isConnected(player, nextPlayer, ball)) {
if (!stateCache.has(nextStateKey)) {
stateCache.add(nextStateKey)
if (nextBallKey === targetKey) {
return count
}
nextQueue.push([nextBall, nextPlayer])
}
}
}
}
}
queue = nextQueue
count++
}
return -1
}; | Minimum Moves to Move a Box to Their Target Location |
You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.
A string is encrypted with the following process:
For each character c in the string, we find the index i satisfying keys[i] == c in keys.
Replace c with values[i] in the string.
Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string "" is returned.
A string is decrypted with the following process:
For each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.
Replace s with keys[i] in the string.
Implement the Encrypter class:
Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary.
String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.
int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.
Example 1:
Input
["Encrypter", "encrypt", "decrypt"]
[[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]]
Output
[null, "eizfeiam", 2]
Explanation
Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);
encrypter.encrypt("abcd"); // return "eizfeiam".
// 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am".
encrypter.decrypt("eizfeiam"); // return 2.
// "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'.
// Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd".
// 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.
Constraints:
1 <= keys.length == values.length <= 26
values[i].length == 2
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
All keys[i] and dictionary[i] are unique.
1 <= word1.length <= 2000
1 <= word2.length <= 200
All word1[i] appear in keys.
word2.length is even.
keys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters.
At most 200 calls will be made to encrypt and decrypt in total.
| class Encrypter:
def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):
self.hashmap = dict()
for i in range(len(keys)):
self.hashmap[keys[i]] = values[i]
self.dictmap = defaultdict(int)
for word in dictionary:
self.dictmap[self.encrypt(word)] += 1
def encrypt(self, word1: str) -> str:
output = ''
for char in word1:
output += self.hashmap[char]
return output
def decrypt(self, word2: str) -> int:
return self.dictmap[word2] | class Encrypter {
Map<String, Integer> encryptedDictCount;
int[] keys;
Set<String> dictionary;
String[] val;
public Encrypter(char[] keys, String[] values, String[] dictionary) {
this.keys = new int[26];
encryptedDictCount = new HashMap<>();
this.val = values.clone();
this.dictionary = new HashSet<>(Arrays.asList(dictionary));
for(int i=0; i<keys.length; i++) {
this.keys[keys[i] - 'a'] = i;
}
for(String dict : dictionary) {
String encrpted = encrypt(dict);
encryptedDictCount.put(encrpted, encryptedDictCount.getOrDefault(encrpted, 0) + 1);
}
}
public String encrypt(String word1) {
StringBuilder sb = new StringBuilder();
for(int i =0; i < word1.length(); i++) {
int c = word1.charAt(i) - 'a';
sb.append(val[keys[c]]);
}
return sb.toString();
}
public int decrypt(String word2) {
return encryptedDictCount.getOrDefault(word2, 0);
}
} | class Encrypter {
public:
unordered_set<string> dict;
unordered_map<char,string> en;
unordered_map<string,vector<char>> dy;
Encrypter(vector<char>& keys, vector<string>& values, vector<string>& dictionary) {
for(auto& t:dictionary)
{ dict.insert(t);}
for(int i=0;i<keys.size();i++)
{
char c=keys[i];
string s=values[i];
en[c]=s;
dy[s].push_back(c);
}
}
string encrypt(string word1) {
string ans="";
for(char c:word1)
{
ans+=en[c];
}
return ans;
}
int decrypt(string word2) {
int cnt=0;
for(auto t:dict)
{
string ans="";
for(int i=0;i<t.size();i++)
{
ans+=en[t[i]];
}
if(ans==word2)
cnt++;
}
return cnt;
}
}; | var Encrypter = function(keys, values, dictionary) {
this.encryptMap = new Map();
for (let i = 0; i < keys.length; i++) {
this.encryptMap.set(keys[i], values[i]);
}
this.dict = new Set(dictionary);
// Encypt the values in dict for easy comparison later
this.encryptedVals = [];
for (let word of this.dict) {
this.encryptedVals.push(this.encrypt(word));
}
};
Encrypter.prototype.encrypt = function(word1) {
let encrypted = '';
for (let char of word1) {
encrypted += this.encryptMap.get(char);
}
return encrypted;
};
Encrypter.prototype.decrypt = function(word2) {
return this.encryptedVals.filter(x => x === word2).length;
}; | Encrypt and Decrypt Strings |
A conveyor belt has packages that must be shipped from one port to another within days days.
The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], days = 3
Output: 6
Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], days = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
Constraints:
1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
| class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def calc(m):#function calculate no of days for given weight
c,s=0,0
for i in weights:
if i+s>m:
c+=1
s=0
s+=i
if s>0:
c+=1
return c
left,right=max(weights),sum(weights)
while left <=right:
mid = (left+right)//2
if calc(mid) > days:
left = mid+1
else :
right = mid -1
return left | class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 0;
int right = 0;
// left is the biggest element in the array. It's set as the lower boundary.
// right is the sum of the array, which is the upper limit.
for (int weight : weights) {
left = Math.max(weight, left);
right += weight;
}
int res = 0;
while (left <= right) {
int mid = (left + right) / 2;
// make sure mid is a possible value
if (isPossible(weights, days, mid)) {
res = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return res;
}
public boolean isPossible(int [] weights, int days, int mid) {
int totalDays = 1;
int totalWeight = 0;
for (int i = 0; i < weights.length; i++) {
totalWeight += weights[i];
// increase totalDays if totalWeight is larger than mid
if (totalWeight > mid) {
totalDays++;
totalWeight = weights[i];
}
// the problem states all the packages have to ship within `days` days
if (totalDays > days) {
return false;
}
}
return true;
}
} | class Solution {
public:
// function to check if it is possible to ship all the items within the given number of days using a given weight capacity
bool isPossible(int cp, vector<int>& weights, int days)
{
int d = 1;
int cw = 0;
// iterate through the weights and check if it is possible to ship all the items
for (auto x : weights) {
if (x + cw <= cp) {
// if the current weight can be added to the current capacity, add it
cw += x;
} else {
// if not, increment the number of days required for shipping and start a new shipment
d++;
cw = x;
if (x > cp) {
// if the current weight is greater than the current capacity, it is impossible to ship all the items
return false;
}
}
}
// check if it is possible to ship all the items within the given number of days
return d <= days;
}
// function to find the minimum weight capacity required to ship all the items within the given number of days
int shipWithinDays(vector<int>& weights, int days)
{
// initialize the search range for the weight capacity
int s = 1;
int e = 1E9;
int ans = -1;
// perform binary search on the weight capacity range
while (s <= e) {
// set the mid-point of the range as the current weight capacity
int mid = (s + e) / 2;
// check if it is possible to ship all the items within the given number of days using the current weight capacity
bool ok = isPossible(mid, weights, days);
// if it is possible to ship all the items within the given number of days using the current weight capacity,
// set the current weight capacity as the new answer and reduce the upper bound of the weight capacity range
if (ok) {
ans = mid;
e = mid - 1;
} else {
// if it is not possible to ship all the items within the given number of days using the current weight capacity,
// increase the lower bound of the weight capacity range
s = mid + 1;
}
}
// return the minimum weight capacity required to ship all the items within the given number of days
return ans;
}
}; | /**
* @param {number[]} weights
* @param {number} days
* @return {number}
*/
var shipWithinDays = function(weights, days) {
// set left as max of weight, set right as sum of weight
let left = Math.max(...weights), right = weights.reduce((a, b) => a + b);
// max weight cannot exceed the capacity of ship
while (left < right) {
// set middle weight
const m = Math.floor((left + right) / 2);
// reset weight if can be load
can(m) ? (left = m + 1) : (right = m);
}
// result
return left;
// check if load can be
function can(v) {
let need = 1, current = 0;
for (let i of weights) {
if (current + i > v) {
need++;
current = i;
}
else {
current += i;
}
}
return need > days;
}
}; | Capacity To Ship Packages Within D Days |
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Constraints:
The number of nodes in the list is n.
1 <= k <= n <= 5000
0 <= Node.val <= 1000
Follow-up: Can you solve the problem in O(1) extra memory space?
| # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
# Intialize the result and the current node to the head
res = node = head
# Initialize the index of the current node to 0
i = 0
# Initialize the head and tail of the reversed nodes group to None
reversedHead, reversedTail = None, None
# Initialize the tail of the previous group to None
previousTail = None
# Iterate through all nodes
while node:
# When we reach the first node in a group
if i % k == 0:
# If there is a previous group, connect its tail to the current node
# This is the case when we have less than k nodes left
if previousTail:
previousTail.next = node
# Initialize the head and tail of the reversed nodes group
reversedHead = reversedTail = ListNode(node.val)
# Continue to reverse subsequent nodes
else:
reversedHead = ListNode(node.val, reversedHead)
# If we are able to reach the last node in a reversed nodes group
if i % k == k - 1:
# If there is a previous group, connect its tail to the current node
# This is the case when we have k nodes and thus, we should reverse this group
if previousTail:
previousTail.next = reversedHead
# Set the tail of the previous group to the tail of the reversed nodes group
previousTail = reversedTail
# Set the head of the first reversed nodes group as the result
if i == k - 1:
res = reversedHead
# Continue to the next node
i, node = i + 1, node.next
return res | class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int numOfNodes = count(head);
ListNode ptr = null;
List<ListNode> start = new ArrayList<>(), end = new ArrayList<>();
ListNode f = null;
while (head != null) {
if (numOfNodes >= k) {
start.add(head);
int count = 0;
while (count < k) {
ListNode temp = head.next;
head.next = ptr;
ptr = head;
head = temp;
count++;
}
end.add(ptr);
ptr = null;
numOfNodes -= count;
}
else {
f = head;
break;
}
}
int n = start.size();
for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);
start.get(n - 1).next = f;
return end.get(0);
}
public int count(ListNode head) {
ListNode temp = head;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
} | class Solution {
pair<ListNode* , ListNode*> get_rev_list(ListNode* root){
ListNode *tail = root;
ListNode *curr = root , *temp , *prev = NULL;
while(curr != NULL){
temp = curr -> next;
curr -> next = prev;
prev = curr;
curr = temp;
}
return make_pair(prev , tail);
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k == 1)
return head;
vector<pair<ListNode* , ListNode*>> store;
ListNode *temp = head , *temp_head = head;
int len = 0;
while(temp != NULL){
len++;
if(len == k){
ListNode *next_head = temp -> next;
temp -> next = NULL;
store.push_back(get_rev_list(temp_head));
temp = next_head;
len = 0;
temp_head = next_head;
}
else
temp = temp -> next;
}
if(len == k)
store.push_back(get_rev_list(temp_head));
for(int i = 1; i < store.size(); i++)
store[i - 1].second -> next = store[i].first;
if(len != k)
store[store.size() - 1].second -> next = temp_head;
return store[0].first;
}
}; | var reverseKGroup = function(head, k) {
const helper = (node) => {
let ptr = node;
let t = k;
let prev = null;
while(t && ptr) {
prev = ptr;
ptr = ptr.next;
t -= 1;
}
if(t > 0) //if k is not zero then do not reverse, simply return;
return node;
let f = prev.next;
prev.next = null;
let [rev, end] = reverseList(node);
end.next = helper(f);
return rev;
}
return helper(head);
};
var reverseList = function(head) {
let prev = null;
let current = head;
let end = head;
while(current) {
let next = current.next;
current.next = prev;
prev = current;
current = next;
}
return [prev, end];
}; | Reverse Nodes in k-Group |
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.
| class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# parent array to keey track
parent = list(range(m*n))
# rank array used for union by rank and size calculation
rank = [1 for _ in range(m*n)]
# standard DSU find function
def find(x):
while x != parent[x]:
parent[x] = parent[parent[x]]
x = parent[x]
return x
# standard DSU union by rank function
def union(x,y):
parX, parY = find(x), find(y)
if parX == parY: return
if rank[parX] >= rank[parY]:
rank[parX] += rank[parY]
parent[parY] = parX
else:
rank[parY] += rank[parX]
parent[parX] = parY
# Step 1: join the land
# for each island we perform union operation
for i, row in enumerate(grid):
for j, val in enumerate(row):
# important condition: if we have a water body, we set its rank to 0 (will be used in the next step)
if not val:
rank[i*m+j] = 0
continue
# performing union of land bodies
for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:
# outside of grid check
if not (0 <= x < m and 0 <= y < n): continue
if grid[x][y]: union(i*m+j, x*m+y)
# Step 2: convert a water body (if present)
# the minimum final ans will always be the size of the largest land present
ans = max(rank)
for i, row in enumerate(grid):
for j, val in enumerate(row):
# we dont need to do anything if we encounter a land
if val: continue
neighbours = set()
res = 0
#
for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:
# outside of grid check
if not (0 <= x < m and 0 <= y < n): continue
# checking unique neighbours by adding the parent to the set
# here we dont care if the neighbour is water as its rank is 0 so it contributes nothing
idx = x*m+y
neighbours.add(find(idx))
# Once we have all unique neighbours, just add their ranks
for idx in neighbours:
res += rank[idx]
# res + 1 because we convert the current cell (i,j) to land too
ans = max(ans, res+1)
return ans | class Solution {
int dir[][] = new int[][]{
{1, 0},
{-1,0},
{0,1},
{0,-1}
};
private int countArea(int grid[][], int i, int j, int num){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)
return 0;
if(grid[i][j] != 1) return 0;
grid[i][j] = num;
int count = 0;
for(int d[] : dir){
count += countArea(grid, i + d[0], j + d[1], num);
}
return 1 + count;
}
private void fillDP(int grid[][], int dp[][], int i, int j, int count, int num){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return ;
if(grid[i][j] != num) return;
if(dp[i][j] != 0) return ;
dp[i][j] = count;
for(int d[] : dir){
fillDP(grid, dp, i + d[0], j + d[1], count, num);
}
}
public int largestIsland(int[][] grid) {
int n = grid.length, m = grid[0].length;
int dp[][] = new int[n][m];
int num = 1;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(grid[i][j] == 1){
++num;
int count1 = countArea(grid, i, j, num);
fillDP(grid, dp, i, j, count1, num);
}
}
}
int max = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(grid[i][j] != 0) continue;
int val = 1;
Set<Integer> set = new HashSet<>();
for(int d[] : dir){
int newRow = i + d[0];
int newCol = j + d[1];
if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= m) continue;
if(set.contains(grid[newRow][newCol])) continue;
val += dp[newRow][newCol];
set.add(grid[newRow][newCol]);
}
max = Math.max(max, val);
}
}
if(max == 0) return n * m;
return max;
}
} | class Solution {
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
bool isValid(vector<vector<int>>const &grid,vector<vector<int>> &visited, int row, int col){
int n=grid.size();
if(row<0 || row>=n || col<0 || col>=n || grid[row][col]!=1 || visited[row][col]!=0){
return false;
}
return true;
}
int helper(vector<vector<int>>const &grid,vector<vector<int>> &visited, int row, int col){
if(!isValid(grid,visited,row,col)) return 0;
visited[row][col]=1;
return 1+helper(grid,visited, row+dir[0][0], col+dir[0][1])+
helper(grid,visited, row+dir[1][0], col+dir[1][1])+
helper(grid,visited, row+dir[2][0], col+dir[2][1])+
helper(grid,visited, row+dir[3][0], col+dir[3][1]);
return 0;
}
public:
int largestIsland(vector<vector<int>>& grid) {
int ans=0;
int n=grid.size();
for(int i=0;i<n;i++){
for(int j=0;j<grid.size();j++){
if(grid[i][j]==0){
grid[i][j]=1;
vector<vector<int>> visited(n,vector<int>(n,0));
ans=max(ans,helper(grid,visited, i,j));
grid[i][j]=0;
}
}
}
return ans==0?n*n:ans;
}
}; | var largestIsland = function(grid) {
const n = grid.length
/**
* Create the merge find (union find) structure --> https://www.youtube.com/watch?v=ibjEGG7ylHk
* For this case, we will form the sets at once, already assigning the same representative to all members.
* Thus, we can use this simplistic implementation without path compression and find(i) = mf[i]
*/
const mf = []
for (let i = 0; i < n*n; i++) {
mf.push(i)
}
// Helper that converts coordinates to array position
const toPos = (r, c) => r * n + c
// Recursively set the merge find structure to represent the islands' map
const merge = (r, c, repr) => {
mf[toPos(r, c)] = repr // Merge coordinate
/**
* Visit neighbors. To visit a neighboring coordinate we first check for:
* Boundaries (coordinates stay within matrix limits)
* Neighbor is land (contains a 1)
* We didn't visit it already (has different representative)
*/
if (r > 0 && grid[r-1][c] === 1 && mf[toPos(r-1, c)] !== repr) { // Top
merge(r-1, c, repr)
}
if (c < n-1 && grid[r][c+1] === 1 && mf[toPos(r, c+1)] !== repr) { // Right
merge(r, c+1, repr)
}
if (r < n-1 && grid[r+1][c] === 1 && mf[toPos(r+1, c)] !== repr) { // Bottom
merge(r+1, c, repr)
}
if (c > 0 && grid[r][c-1] === 1 && mf[toPos(r, c-1)] !== repr) { // Left
merge(r, c-1, repr)
}
}
/**
* For each land (1) position that wasn't already merged into a set,
* we define a new set with its neighbors.
*/
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const pos = toPos(i, j)
if (grid[i][j] === 1 && mf[pos] === pos) {
merge(i, j, pos)
}
}
}
/**
* We can now calculate the surface of every island by counting the number of cells
* with the same representative.
*/
const count = Array(n*n).fill(0)
mf.forEach(el => count[el]++)
/**
* Now we have to decide on which sea (0) should be toggled into land (1).
* For this we save, for each zero, which sets it is contact with. Once this is done,
* we can calculate the entire surface by suming 1 + the surface of all touching sets.
* Again, to add the neighbor set to the store, we need to check that it is a one, that we
* are within the boundaries, and that it was not already marked as neighbor.
* We store the maximum surface found, which is the final solution.
*/
let maxSurface = 0
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] === 0) {
const touching = []
let currentSurface = 1
if (r > 0 && grid[r-1][c] === 1 && !touching.includes(mf[toPos(r-1, c)])) { // Top
touching.push(mf[toPos(r-1,c)])
}
if (c < n-1 && grid[r][c+1] === 1 && !touching.includes(mf[toPos(r, c+1)])) { // Right
touching.push(mf[toPos(r,c+1)])
}
if (r < n-1 && grid[r+1][c] === 1 && !touching.includes(mf[toPos(r+1, c)])) { // Bottom
touching.push(mf[toPos(r+1, c)])
}
if (c > 0 && grid[r][c-1] === 1 && !touching.includes(mf[toPos(r, c-1)])) { // Left
touching.push(mf[toPos(r, c-1)])
}
touching.forEach(set => currentSurface += count[set])
if (currentSurface > maxSurface) {
maxSurface = currentSurface
}
}
}
}
/**
* If maxSurface remained at zero, it means the input is a matrix of ones.
*/
if (maxSurface > 0) { return maxSurface }
return n*n
} | Making A Large Island |
Given an equation, represented by words on the left side and the result on the right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
No two characters can map to the same digit.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on the left side (words) will equal to the number on the right side (result).
Return true if the equation is solvable, otherwise return false.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Explanation: There is no possible mapping to satisfy the equation, so we return false.
Note that two different characters cannot map to the same digit.
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contain only uppercase English letters.
The number of different characters used in the expression is at most 10.
| class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
# reverse words
words = [i[::-1] for i in words]
result = result[::-1]
allWords = words + [result]
# chars that can not be 0
nonZero = set()
for word in allWords:
if len(word) > 1:
nonZero.add(word[-1])
# numbers selected in backtracking
selected = set()
# char to Int map
charToInt = dict()
mxLen = max([len(i) for i in allWords])
def res(i = 0, c = 0, sm = 0):
if c == mxLen:
return 1 if sm == 0 else 0
elif i == len(words):
num = sm % 10
carry = sm // 10
if c >= len(result):
if num == 0:
return res(0, c+1, carry)
else:
return 0
# result[c] should be mapped to num if a mapping exists
if result[c] in charToInt:
if charToInt[result[c]] != num:
return 0
else:
return res(0, c+1, carry)
elif num in selected:
return 0
# if mapping does not exist, create a mapping
elif (num == 0 and result[c] not in nonZero) or num > 0:
selected.add(num)
charToInt[result[c]] = num
ret = res(0, c + 1, carry)
del charToInt[result[c]]
selected.remove(num)
return ret
else:
return 0
else:
word = words[i]
if c >= len(word):
return res(i+1, c, sm)
elif word[c] in charToInt:
return res(i+1, c, sm + charToInt[word[c]])
else:
ret = 0
# possibilities for word[c]
for j in range(10):
if (j == 0 and word[c] not in nonZero) or j > 0:
if j not in selected:
selected.add(j)
charToInt[word[c]] = j
ret += res(i + 1, c, sm + j)
del charToInt[word[c]]
selected.remove(j)
return ret
return res() > 0 | class Solution {
public static boolean isSolvable(String[] words, String result) {
// reverse all strings to facilitate add calculation.
for (int i = 0; i < words.length; i++) {
words[i] = new StringBuilder(words[i]).reverse().toString();
}
result = new StringBuilder(result).reverse().toString();
if (!checkLength(words, result)) {
return false;
}
boolean[] visited = new boolean[10]; // digit 0, 1, ..., 9
int[] chToDigit = new int[26];
Arrays.fill(chToDigit, -1);
return dfs(0, 0, 0, visited, chToDigit, words, result);
}
/**
* Elminate the case where result is too long
* word1: AAA
* word2: BBB
* result: XXXXXXXXX
*/
private static boolean checkLength(String[] words, String result) {
int maxLen = 0;
for (String word : words) {
maxLen = Math.max(maxLen, word.length());
}
return result.length() == maxLen || result.length() == maxLen + 1;
}
/*
Put all words like this:
w1: ABC
w2: EF
w3: GHIJ
result: KLMNO
i, is the row
j, is the column
carrier, the one contributed from previous calculation
chToDigit, 26 int array, which records choosen digit for 'A', 'B', 'C', ... If not choosen any, default is -1
*/
private static boolean dfs(int i, int j, int carrier, boolean[] visited, int[] chToDigit, String[] words, String result) {
if (i == words.length) {
char ch = result.charAt(j);
// (i, i) at bottom right corner. final check
if (j == result.length() - 1) {
// 1. check if carrier is equal or greater than 10. If so, false.
if (carrier >= 10) {
return false;
}
// 2. check if result.length() > 1 && result.lastCh is zero. If so the false.
if (j > 0 && j == result.length() - 1 && chToDigit[ch - 'A'] == 0) {
return false;
}
// not selected, can select any. True.
if (chToDigit[ch - 'A'] == -1) {
System.out.println(Arrays.toString(chToDigit));
return true;
} else { // if selected, check if it matches with carrier. Also, carrier can't be 0. result = '00' is invalid
return chToDigit[ch - 'A'] == carrier;
}
} else { // reached normal result line.
// 1. if not selected. Use current carrier's unit digit
if (chToDigit[ch - 'A'] == -1) {
int selectedDigit = carrier % 10;
// For example carrier = 13. selectedDigit = 3. ch = 'H'. Should set 3 to 'H'.
// But 3 is already taken by 'B' previously. So wrong.
if (visited[selectedDigit]) {
return false;
}
visited[selectedDigit] = true;
chToDigit[ch - 'A'] = selectedDigit;
if (dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result)) {
return true;
}
chToDigit[ch - 'A'] = -1;
visited[selectedDigit] = false;
} else { // 2. selected
// just need to check if ch.digit equals to unit digit.
if (chToDigit[ch - 'A'] != carrier % 10) {
return false;
}
boolean ans = dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result);
return ans;
}
} //
} else { // normal word
String word = words[i];
// 1. check if j is equal or greater than word.len. If so pass to next word.
if (j >= word.length()) {
boolean ans = dfs(i + 1, j, carrier, visited, chToDigit, words, result);
return ans;
}
// 2. check if it's last ch, word.len is greater than 1, and is '0'. If so false;
if (j == word.length() - 1 && word.length() > 1 && chToDigit[word.charAt(j) - 'A'] == 0) {
return false;
}
char ch = word.charAt(j);
// 3. check if word.ch is selected. Just add current digit and move to next word.
if (chToDigit[ch - 'A'] != -1) {
int newSum = carrier + chToDigit[ch - 'A'];
boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);
return ans;
} else {
for (int k = 0; k < visited.length; k++) {
if (visited[k]) {
continue;
}
visited[k] = true;
chToDigit[ch - 'A'] = k;
int newSum = k + carrier;
boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);
if (ans) {
return true;
}
visited[k] = false;
chToDigit[ch - 'A'] = -1;
}
}
}
return false;
}
} | class Solution {
int limit = 0;
unordered_map<char, int> c2i;
unordered_map<int, char> i2c;
bool helper(vector<string> &words, string &result, int digit, int wid, int sum)
{
if(digit==limit)
return sum == 0;
if(wid==words.size())
{
if(c2i.count(result[digit])==0 && i2c.count(sum%10)==0)
{
if(sum%10==0 && digit+1 == limit)
return false; //Means leading zeros
c2i[result[digit]] = sum%10;
i2c[sum%10] = result[digit];
bool tmp = helper(words, result, digit+1, 0, sum/10); //0 because it will
//go one digit at a time until all digits in words are finished
c2i.erase(result[digit]);
i2c.erase(sum%10);
return tmp;
}
else if(c2i.count(result[digit]) && c2i[result[digit]] == sum%10) //c2i for that exits and is equal to sum%10, remember default will be 0 and sum%10 can also be 0
{
if(digit+1 == limit && c2i[result[digit]]==0)
return false; //again same condition of leading zeros
return helper(words, result, digit+1, 0, sum/10);
}
else //if result[digit] exists in c2i but is not equal to sum%10
return false;
}
if(digit>=words[wid].length()) //digit>current words length
return helper(words, result, digit, wid+1, sum); //go to next word at same position
//(digit) and sum, also going wid + 1 that is why checking wid limit in last condition already
if(c2i.count(words[wid][digit]))
{
if(digit+1 == words[wid].length() && words[wid].length() > 1 && c2i[words[wid][digit]]==0)
return false; //here we checking if there is no leading 0 in the word itself
return helper(words, result, digit, wid+1, sum+c2i[words[wid][digit]]);
}
for(int i=0; i<10; i++)
{
if(digit+1==words[wid].length() && i==0 && words[wid].length()>1)
continue;
if (i2c.count(i))
continue;
c2i[words[wid][digit]] = i;
i2c[i] = words[wid][digit];
bool tmp = helper(words, result, digit, wid+1, sum+i);
c2i.erase(words[wid][digit]);
i2c.erase(i);
if(tmp)
return true;
}
return false;
}
public:
bool isSolvable(vector<string>& words, string result) {
limit = result.length();
for(auto s:words)
{
if(s.length()>limit)
return false;
}
for(auto &s:words)
{
reverse(s.begin(), s.end());
}
reverse(result.begin(), result.end());
return helper(words, result, 0, 0, 0);
}
}; | /**
* @param {string[]} words
* @param {string} result
* @return {boolean}
*/
var isSolvable = function(words, result) {
// set to hold all the first characters
const firstChars = new Set();
// map for steps 1 & 2
// this will hold the key as the character and multiple as the value
let map = {};
for (let i = 0; i < result.length; i++) {
const char = result[i];
if (!i) firstChars.add(char);
if (!map.hasOwnProperty(char)) map[char] = 0;
map[char] -= 10 ** (result.length - i - 1);
}
for (let j = 0; j < words.length; j++) {
const word = words[j];
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!i) firstChars.add(char);
if (!map.hasOwnProperty(char)) map[char] = 0;
map[char] += 10 ** (word.length - i - 1);
}
}
// Step 3: we group the positive and negative values
const positives = [];
const negatives = [];
Object.entries(map).forEach((entry) => {
if (entry[1] < 0) negatives.push(entry);
else positives.push(entry);
})
// Step 4: backtrack
const numsUsed = new Set();
const backtrack = (val = 0) => {
// if we have used all the characters and the value is 0 the input is solvable
if (!positives.length && !negatives.length) return val === 0;
// get the store that we are going to examine depending on the value
let store = val > 0 || (val === 0 && negatives.length) ? negatives : positives;
if (store.length === 0) return false;
const entry = store.pop();
const [char, multiple] = entry;
// try every possible value watching out for the edge case that it was a first character
for (let i = firstChars.has(char) ? 1 : 0; i < 10; i++) {
if (numsUsed.has(i)) continue;
numsUsed.add(i);
if (backtrack(i * multiple + val)) return true;
numsUsed.delete(i);
}
store.push(entry);
return false;
}
return backtrack();
}; | Verbal Arithmetic Puzzle |