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 playing a solitaire game with three piles of stones of sizes aββββββ, b,ββββββ and cββββββ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).
Given three integers aβββββ, b,βββββ and cβββββ, return the maximum score you can get.
Example 1:
Input: a = 2, b = 4, c = 6
Output: 6
Explanation: The starting state is (2, 4, 6). One optimal set of moves is:
- Take from 1st and 3rd piles, state is now (1, 4, 5)
- Take from 1st and 3rd piles, state is now (0, 4, 4)
- Take from 2nd and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 6 points.
Example 2:
Input: a = 4, b = 4, c = 6
Output: 7
Explanation: The starting state is (4, 4, 6). One optimal set of moves is:
- Take from 1st and 2nd piles, state is now (3, 3, 6)
- Take from 1st and 3rd piles, state is now (2, 3, 5)
- Take from 1st and 3rd piles, state is now (1, 3, 4)
- Take from 1st and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 7 points.
Example 3:
Input: a = 1, b = 8, c = 8
Output: 8
Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
After that, there are fewer than two non-empty piles, so the game ends.
Constraints:
1 <= a, b, c <= 105
| class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a, b, c = sorted([a, b, c], reverse=True)
ans = 0
while a > 0 and b > 0:
a -= 1
b -= 1
ans += 1
a, b, c = sorted([a, b, c], reverse=True)
return ans | class Solution {
public int maximumScore(int a, int b, int c) {
// Make sure a <= b <= c
if (a>b) return maximumScore(b,a,c);
if (b>c) return maximumScore(a,c,b);
// if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c
if (a+b<=c) return a+b;
// if sum of smallest numbers is greater than c, then we can (a+b)/2 pairs after making c empty
return c+(a+b-c)/2;
}
} | class Solution {
public:
int maximumScore(int a, int b, int c) {
return min((a + b + c) / 2, a + b + c - max({a, b, c}));
}
}; | /**
* @param {number} a
* @param {number} b
* @param {number} c
* @return {number}
*/
var maximumScore = function(a, b, c) {
let resultArray = [];
resultArray.push(a);
resultArray.push(b);
resultArray.push(c);
resultArray.sort((a,b)=>a-b);
let counter=0;
while(resultArray[0]>0||resultArray[1]>0||resultArray[2]>0){
if(resultArray[0]===0&&resultArray[1]===0){
break;
}
resultArray[1]--;
resultArray[2]--;
counter++
if(resultArray[1]<resultArray[0]){
exchange(resultArray,1,0);
}
if(resultArray[2]<resultArray[0]){
exchange(resultArray,2,0);
}
}
if(resultArray[0]+resultArray[1]+resultArray[2]===0) return counter;
if(resultArray[0]<0||resultArray[1]<0||resultArray[2]<0) counter--;
return counter;
function exchange(array, indexa,indexb){
let temp = array[indexa];
array[indexa] = array[indexb];
array[indexb] = temp;
}
}; | Maximum Score From Removing Stones |
You are given two 0-indexed integer arrays servers and tasks of lengths nββββββ and mββββββ respectively. servers[i] is the weight of the iββββββthββββ server, and tasks[j] is the time needed to process the jββββββthββββ task in seconds.
Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.
At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.
A server that is assigned task j at second t will be free again at second t + tasks[j].
Build an array ansββββ of length m, where ans[j] is the index of the server the jββββββth task will be assigned to.
Return the array ansββββ.
Example 1:
Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
Output: [2,2,0,2,1,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 2 until second 1.
- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
- At second 2, task 2 is added and processed using server 0 until second 5.
- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
- At second 4, task 4 is added and processed using server 1 until second 5.
- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.
Example 2:
Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
Output: [1,4,1,4,1,3,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 1 until second 2.
- At second 1, task 1 is added and processed using server 4 until second 2.
- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4.
- At second 3, task 3 is added and processed using server 4 until second 7.
- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9.
- At second 5, task 5 is added and processed using server 3 until second 7.
- At second 6, task 6 is added and processed using server 2 until second 7.
Constraints:
servers.length == n
tasks.length == m
1 <= n, m <= 2 * 105
1 <= servers[i], tasks[j] <= 2 * 105
| class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
servers_available = [(w, i) for i,w in enumerate(servers)]
heapify(servers_available)
tasks_in_progress = []
res = []
time = 0
for j,task in enumerate(tasks):
time = max(time, j)
if not servers_available:
time = tasks_in_progress[0][0]
while tasks_in_progress and tasks_in_progress[0][0] <= time:
heappush(servers_available, heappop(tasks_in_progress)[1])
res.append(servers_available[0][1])
heappush(tasks_in_progress, (time + task, heappop(servers_available)))
return res | class Solution {
public int[] assignTasks(int[] servers, int[] tasks) {
PriorityQueue<int[]> availableServer = new PriorityQueue<int[]>((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0])));
for(int i = 0; i < servers.length; i++){
availableServer.add(new int[]{i, servers[i]});
}
//int[[] arr,
//arr[0] - server index
//arr[1] - server weight
//arr[2] - free time
PriorityQueue<int[]> processingServer = new PriorityQueue<int[]>(
(a, b) ->
(
a[2] != b[2] ? a[2] - b[2] : // try to sort increasing order of free time
a[1] != b[1] ? a[1] - b[1] : // try to sort increasing order of server weight
a[0] - b[0] // sort increasing order of server index
)
);
int[] result = new int[tasks.length];
for(int i = 0; i < tasks.length; i++){
while(!processingServer.isEmpty() && processingServer.peek()[2] <= i){
int serverIndex = processingServer.remove()[0];
availableServer.add(new int[]{serverIndex, servers[serverIndex]});
}
int currentTaskTimeRequired = tasks[i];
int[] server;
//when current task will free the server done
int freeTime = currentTaskTimeRequired;
if(!availableServer.isEmpty()){
server = availableServer.remove();
freeTime += i;
}else{
server = processingServer.remove();
//append previous time
freeTime += server[2];
}
int serverIndex = server[0];
processingServer.add(new int[]{serverIndex, servers[serverIndex] ,freeTime});
//assign this server to current task
result[i] = serverIndex;
}
return result;
}
} | class Solution {
public:
vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {
priority_queue<vector<long long>, vector<vector<long long>>, greater<vector<long long>>> free, busy;
for (int i = 0; i < servers.size(); ++i) {
free.push(vector<long long>{servers[i], i});
}
vector<int> ans;
long long time = 0;
queue<int> task_queue;
while (ans.size() < tasks.size()) {
// Bring all eligible tasks to task_queue.
for (int i = ans.size() + task_queue.size(); i <= time && i < tasks.size(); ++i) {
task_queue.push(tasks[i]);
}
// Bring all eligible servers to free queue.
while (!busy.empty() && busy.top()[0] <= time) {
auto& top = busy.top();
free.push(vector<long long>{top[1], top[2]});
busy.pop();
}
// If we have no servers, we cannot match until one of the servers becomes free.
if (free.empty()) {
time = busy.top()[0];
continue;
}
while(!task_queue.empty() && !free.empty()) {
// Now we just take the first task and first server as per defined priority and match the two.
int task = task_queue.front();
auto& top = free.top();
ans.push_back(top[1]);
busy.push(vector<long long>{time + task, top[0], top[1]});
task_queue.pop();
free.pop();
}
// Only increment time to receive new tasks once we have processed all tasks so far.
if (task_queue.empty()) time++;
}
return ans;
}
}; | var assignTasks = function(servers, tasks) {
// create a heap to manage free servers.
// free servers will need to be prioritized by weight and index
const freeServers = new Heap((serverA, serverB) => (
serverA.weight - serverB.weight || serverA.index - serverB.index
));
// create a heap to manage used servers.
// used servers will need to be prioritized by availableTime, weight and index
const usedServers = new Heap((serverA, serverB) => (
serverA.availableTime - serverB.availableTime ||
serverA.weight - serverB.weight ||
serverA.index - serverB.index
));
// add all the servers into the free servers heap with the time it is available
// being 0
for (let i = 0; i < servers.length; i++) {
freeServers.push({ weight: servers[i], index: i, availableTime: 0 })
}
const result = [];
for (let i = 0; i < tasks.length; i++) {
// find all the servers that are available and add them to the
// free servers heap
while (usedServers.size() && usedServers.peak().availableTime <= i) {
freeServers.push(usedServers.pop());
}
// get the free server with the lowest weight or lower index
// or the usedServer with the lowest start time.
const server = freeServers.pop() || usedServers.pop();
result.push(server.index);
const availableTime = Math.max(i, server.availableTime);
server.availableTime = availableTime + tasks[i];
usedServers.push(server);
}
return result;
};
class Heap {
/**
* Create a Heap
* @param {function} compareFunction - compares child and parent element
* to see if they should swap. If return value is less than 0 it will
* swap to prioritize the child.
*/
constructor(compareFunction) {
this.store = [];
this.compareFunction = compareFunction;
}
peak() {
return this.store[0];
}
size() {
return this.store.length;
}
pop() {
if (this.size() < 2) {
return this.store.pop();
}
const result = this.store[0];
this.store[0] = this.store.pop();
this.heapifyDown(0);
return result;
}
push(val) {
this.store.push(val);
this.heapifyUp(this.size() - 1);
}
heapifyUp(child) {
while (child) {
const parent = Math.floor((child - 1) / 2);
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
child = parent;
} else {
return child;
}
}
}
heapifyDown(parent) {
while (true) {
let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());
if (this.shouldSwap(child2, child)) {
child = child2;
}
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
parent = child;
} else {
return parent;
}
}
}
shouldSwap(child, parent) {
return child && this.compareFunction(this.store[child], this.store[parent]) < 0;
}
} | Process Tasks Using Servers |
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].
Return an array containing the result for the given queries.
Example 1:
Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1]
Explanation: The queries are processed as follow:
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].
Therefore, the array containing the result is [2,1,2,1].
Example 2:
Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]
Example 3:
Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]
Constraints:
1 <= m <= 10^3
1 <= queries.length <= m
1 <= queries[i] <= m
| class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
perm=[i for i in range(1,m+1)]
res=[]
for i in queries:
ind=perm.index(i)
res.append(ind)
perm=[perm.pop(ind)]+perm
return res | class Solution {
public int[] processQueries(int[] queries, int m) {
int[] results = new int[queries.length];
ArrayList<Integer> permutations = new ArrayList<Integer>();
// Filling the permuations array with numbers.
for (int i = 0; i < m; i++)
permutations.add(i+1);
// Looping on the queries & checking their index in the permuations
for (int i = 0; i < queries.length; i++) {
int query = queries[i];
for (int j = 0; j < permutations.size(); j++)
if (permutations.get(j) == query) {
results[i] = j;
int temp = permutations.get(j);
permutations.remove(j);
permutations.add(0, temp);
break;
}
}
return results;
}
} | class Solution {
public:
vector<int> processQueries(vector<int>& queries, int m) {
vector<int> p;
for(int i=0; i<m; i++) p.push_back(m-i);
for(int i=0; i<queries.size(); i++)
{
auto it = find(p.begin(), p.end(), queries[i]);
int j = it - p.begin();
int tmp = p[j];
p.erase(it);
p.push_back(tmp);
queries[i] = m-j-1;
}
return queries;
}
}; | var processQueries = function(queries, m) {
let result = [];
let permutation = [];
for(let i=0; i<m; i++){
permutation.push(i+1);
}
for(let i=0; i<queries.length; i++){
let index = permutation.indexOf(queries[i]);
result.push(index);
permutation.splice(index,1);
permutation.unshift(queries[i]);
}
return result;
}; | Queries on a Permutation With Key |
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
Constraints:
n == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105
| class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
unstable=0
for i in range(1,len(nums)):
if nums[i]<nums[i-1]:
unstable+=1
if i<2 or nums[i-2]<=nums[i]:
nums[i-1]=nums[i]
else:
nums[i]=nums[i-1]
if unstable>1:
return False
return True | class Solution {
public boolean checkPossibility(int[] nums) {
int modified = 0, prev = nums[0], index = 0;
for (; index < nums.length; ++index) {
if (nums[index] < prev) {
if (++modified > 1) return false;
if (index - 2 >= 0 && nums[index - 2] > nums[index]) continue;
}
prev = nums[index];
}
return true;
}
} | class Solution {
public:
bool checkPossibility(vector<int>& nums) {
if(nums.size()<=2)
return true;
//creating a diff array(size=n-1) to store differences bw 2 consecutive ele.
vector<int>diff(nums.size()-1);
int neg=0;
for(int i=0;i<nums.size()-1;i++)
{
diff[i]=nums[i+1]-nums[i];
diff[i]<0?neg++:0; //no of negative differences
}
if(neg>1)
return false;
for(int i=0;i<diff.size();i++)
{
if(diff[i]<0 and i!=diff.size()-1)
{
if(i==0)
// if(diff[i+1]>=0)
continue; //if the first diff is neg, the next is obviosly>=0 as neg<=1, and this mountain can be resolved;
// else
// return false;
if((nums[i-1]<=nums[i+1]) || (diff[i+1])>=abs(diff[i]))
continue; //the major mountain cases, lemme know below if want explaination of these
else
return false;
}
}
return true;
} | var checkPossibility = function(nums) {
let changed = false
for(let i=nums.length-1; i>0; i--) {
if(nums[i-1] > nums[i]) {
if(changed) return false;
if(i === nums.length-1 || nums[i-1] < nums[i+1]) nums[i] = nums[i-1]
else nums[i-1] = nums[i];
changed = true
}
}
return true;
}; | Non-decreasing Array |
A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can not reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation: We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Constraints:
1 <= target, startFuel <= 109
0 <= stations.length <= 500
0 <= positioni <= positioni+1 < target
1 <= fueli < 109
| class Solution:
def minRefuelStops(self, t, F, S):
S.append([t, 0])
heap, ans = [], 0
for p,f in S:
while heap and p > F:
F -= heapq.heappop(heap)
ans += 1
if p > F: return -1
heapq.heappush(heap, -f)
return ans | class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
if(startFuel >= target) return 0;
int[][] dp = new int[stations.length + 1][stations.length + 1];
for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel;
for (int j = 1; j < dp.length; j++) {
for (int i = j; i < dp.length; i++) {
dp[i][j] = Math.max(dp[i-1][j], stations[i-1][0] > dp[i-1][j-1] ?
Integer.MIN_VALUE : dp[i-1][j-1] + stations[i-1][1]);
if(dp[i][j] >= target) return j;
}
}
return -1;
}
} | /*
The approach here used is - first cosider the stations which are possible at a particular time and then take the one with maximum fuel that can be filled this ensure that with only one fill up the vehicle will move to furthest distance.
Now there might be case where if we don't fill up from multiple stations ata paritcular time, then it will not be possible to reach end as there might not be any stations at the ending side of the target.
To handle above case, when such situation arise then we need to take the next max fuel refill that is pissible from the already seen stations.
Like this way keep on taking fuels from stations in decreasing manner.
If at any point of time the queue is empty then, it means we do not have sufficent fuel to reach target.
=> This logic can be implemented by simply using a priority queue where the max fuel station is at top of the queue.
*/
class Solution {
public:
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
auto comp = [](vector<int> a, vector<int> b){ return a[1] < b[1]; };
priority_queue<vector<int>, vector<vector<int>>, decltype(comp)> pq(comp);
int i = 0, distance = startFuel, refillCount = 0;
while(distance < target ){
while(i < stations.size() && distance >= stations[i][0]){
pq.push(stations[i++]);
}
if(pq.empty()) return -1;
distance += pq.top()[1];
refillCount++;
pq.pop();
}
return refillCount;
}
}; | var minRefuelStops = function(target, startFuel, stations) {
let pq = new MaxPriorityQueue({compare: (a, b) => b[1] - a[1]});
let idx = 0, reachablePosition = startFuel, refuels = 0;
// reachablePosition is the farthest position reachable so far
while (reachablePosition < target) {
// While reachablePosition is >= to the current station's position, add the current station to the heap
// These stations are all reachable based on the fuel available
// Once reachablePosition is less than a station's position, the while loop ends
while (idx < stations.length && reachablePosition >= stations[idx][0]) {
pq.enqueue([stations[idx][0], stations[idx][1]]);
idx++;
}
// Next, add fuel from the heap in a greedy manner: the station with the most fuel gets added first
// All stations in the heap are reachable, so the position is irrelevant
if (pq.size()) {
let [pos, fuel] = pq.dequeue();
reachablePosition += fuel;
refuels++;
} else break;
}
return reachablePosition >= target ? refuels : -1;
}; | Minimum Number of Refueling Stops |
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:
The ith customer gets exactly quantity[i] integers,
The integers the ith customer gets are all equal, and
Every customer is satisfied.
Return true if it is possible to distribute nums according to the above conditions.
Example 1:
Input: nums = [1,2,3,4], quantity = [2]
Output: false
Explanation: The 0th customer cannot be given two different integers.
Example 2:
Input: nums = [1,2,3,3], quantity = [2]
Output: true
Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.
Example 3:
Input: nums = [1,1,2,2], quantity = [2,2]
Output: true
Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= 1000
m == quantity.length
1 <= m <= 10
1 <= quantity[i] <= 105
There are at most 50 unique values in nums.
| class Solution:
def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:
freq = {}
for x in nums: freq[x] = 1 + freq.get(x, 0)
vals = sorted(freq.values(), reverse=True)
quantity.sort(reverse=True) # pruning - large values first
def fn(i):
"""Return True if possible to distribute quantity[i:] to remaining."""
if i == len(quantity): return True
seen = set()
for k in range(len(vals)):
if vals[k] >= quantity[i] and vals[k] not in seen:
seen.add(vals[k]) # pruning - unqiue values
vals[k] -= quantity[i]
if fn(i+1): return True
vals[k] += quantity[i] # backtracking
return fn(0) | class Solution {
public boolean canDistribute(int[] nums, int[] quantity) {
// Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums)
freq.put(num, freq.getOrDefault(num, 0)+1);
// Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]
int[] dist = new int[freq.size()];
int idx = 0;
for (int f : freq.values())
dist[idx++] = f;
// Fullfill the quantities from the biggest quantity to the smallest.
// If the bigger quantity can't be filled, the program will stop as early as possible.
Arrays.sort(quantity);
return rec(dist, quantity, quantity.length-1);
}
// try to fullfill the j-th order quantity
private boolean rec(int[] dist, int[] quantity, int j) {
// stop condition. We've fulfilled all the order quantities.
if (j == -1)
return true;
Set<Integer> used = new HashSet<>();
for (int i = 0 ; i < dist.length ; ++i) {
// Use a set to make sure that
// we don't distribute from the same amount to this j-th order for more than once.
// With this check, the program reduces from 97ms to 25 ms.
if (dist[i] >= quantity[j] && used.add(dist[i])) {
dist[i] -= quantity[j];
if (rec(dist, quantity, j-1))
return true;
dist[i] += quantity[j];
}
}
return false;
}
} | class Solution {
public:
bool solve(vector<int>&q, map<int,int>&count, int idx){
if(idx==q.size()){
return true;
}
for(auto it=count.begin();it!=count.end();it++){
if(it->second>=q[idx]){
count[it->first]-=q[idx];
if(solve(q,count,idx+1))
return true;
count[it->first]+=q[idx];
}
}
return false;
}
bool canDistribute(vector<int>& nums, vector<int>& quantity) {
map<int,int>count;
int n=nums.size();
for(int i=0;i<n;i++){
count[nums[i]]++;
}
sort(quantity.begin(),quantity.end(),greater<int>());
return solve(quantity,count,0);
}
}; | var canDistribute = function(nums, quantity) {
quantity.sort((a,b)=>b-a)
let freq={},flag=false
for(let num of nums)
freq[num]=(freq[num]||0) +1
let set=Object.keys(freq),n=set.length,k=quantity.length
let rec=(prefix)=>{
if(prefix.length==k || flag==true)
return flag=true
for(let i=0;i<n;i++){
freq[set[i]]-=quantity[prefix.length]
prefix.push(set[i])
if( freq[set[i]]>=0)
rec(prefix)
prefix.pop()
freq[set[i]]+=quantity[prefix.length]
}
}
rec([])
return flag
}; | Distribute Repeating Integers |
You are given a 0-indexed binary string s which represents the types of buildings along a street where:
s[i] = '0' denotes that the ith building is an office and
s[i] = '1' denotes that the ith building is a restaurant.
As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.
For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that would form "011" which is not allowed due to having two consecutive buildings of the same type.
Return the number of valid ways to select 3 buildings.
Example 1:
Input: s = "001101"
Output: 6
Explanation:
The following sets of indices selected are valid:
- [0,2,4] from "001101" forms "010"
- [0,3,4] from "001101" forms "010"
- [1,2,4] from "001101" forms "010"
- [1,3,4] from "001101" forms "010"
- [2,4,5] from "001101" forms "101"
- [3,4,5] from "001101" forms "101"
No other selection is valid. Thus, there are 6 total ways.
Example 2:
Input: s = "11100"
Output: 0
Explanation: It can be shown that there are no valid selections.
Constraints:
3 <= s.length <= 105
s[i] is either '0' or '1'.
| class Solution:
def numberOfWays(self, s: str) -> int:
temp = []
c0 = 0
c1 = 0
for char in s :
if char == "0" :
c0+=1
else:
c1+=1
temp.append([c0,c1])
total0 = c0
total1 = c1
count = 0
for i in range(1, len(s)-1) :
if s[i] == "0" :
m1 = temp[i-1][1]
m2 = total1 - temp[i][1]
count += m1*m2
else:
m1 = temp[i-1][0]
m2 = total0 - temp[i][0]
count += m1*m2
return count
| class Solution
{
public long numberOfWays(String s)
{
int zero = 0; // Individual zeroes count
long zeroOne = 0; // Number of combinations of 01s
int one = 0; // Individual ones count
long oneZero = 0; // Number of combinations of 10s
long tot = 0; // Final answer
for(char ch : s.toCharArray())
{
if(ch == '0')
{
zero++;
if(one > 0)
oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10
if(zeroOne > 0)
tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010
}
else
{
one++;
if(zero > 0)
zeroOne += zero; // Each of the previously found 0s can pair to form 01
if(oneZero > 0)
tot += oneZero; // Each of the previously formed 10 can form 101
}
}
return tot;
}
} | class Solution {
public:
long long numberOfWays(string s) {
long long a=0,b=0,ans=0; // a and b are the number of occurances of '1' and '0' after the current building respectively.
for(int i=0;i<s.length();i++){
if(s[i]=='1')
a++;
else
b++;
}
long long c=0,d=0; // c and d are the number of occurances of '1' and '0' before the current building respectively.
for(int i=0;i<s.length();i++){
if(s[i]=='1'){ // Counting the sequences of "010"
ans+=(d*b);
a--;
c++;
}
else{ // Counting the sequences of "101"
ans+=(a*c);
b--;
d++;
}
}
return ans;
}
}; | var numberOfWays = function(s) {
const len = s.length;
const prefix = new Array(len).fill(0).map(() => new Array(2).fill(0));
for(let i = 0; i < len; i++) {
const idx = s[i] == '1' ? 1 : 0;
if(i == 0) prefix[i][idx]++;
else {
prefix[i] = Array.from(prefix[i-1]);
prefix[i][idx]++;
}
}
let ans = 0;
for(let i = 1; i < len - 1; i++) {
const c = s[i] == '1' ? 0 : 1;
ans += (prefix.at(-1)[c] - prefix[i][c]) * prefix[i-1][c];
}
return ans;
}; | Number of Ways to Select Buildings |
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
Example 1:
Input: arr = [3,1,2,4]
Output: 17
Explanation:
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
Example 2:
Input: arr = [11,81,94,43,3]
Output: 444
Constraints:
1 <= arr.length <= 3 * 104
1 <= arr[i] <= 3 * 104
| class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
small_before = [-1]*n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
if stack:small_before[i] = stack[-1]
stack.append(i)
best = [0]*(n+1)
ans = 0
for i in range(n):
best[i] = best[small_before[i]] + (i - small_before[i])*arr[i]
ans += best[i]
return ans%1000000007 | class Solution {
public int sumSubarrayMins(int[] arr) {
int n = arr.length;
int ans1[] = nsl(arr);
int ans2[] = nsr(arr);
long sum=0;
for(int i=0;i<n;i++){
sum=(sum + (long)(arr[i]*(long)(ans1[i]*ans2[i])%1000000007)%1000000007)%1000000007;
}
return (int)sum;
}
public static int[] nsl(int arr[]){
Stack<Integer> s = new Stack<>();
int ans[] = new int[arr.length];
for(int i=0;i<arr.length;i++){
while(!s.isEmpty() && arr[i]<arr[s.peek()]){
s.pop();
}
if(s.isEmpty()){
ans[i] = i-(-1);
s.push(i);
}
else{
ans[i] = i-s.peek();
s.push(i);
}
}
return ans;
}
public static int[] nsr(int arr[]){
Stack<Integer> s = new Stack<>();
int ans[] = new int[arr.length];
for(int i=arr.length-1;i>=0;i--){
while(!s.isEmpty() && arr[s.peek()]>=arr[i]){
s.pop();
}
if(s.isEmpty()){
ans[i] = arr.length-i;
s.push(i);
}
else{
ans[i] = s.peek()-i;
s.push(i);
}
}
return ans;
}
} | class Solution {
public: //Thanks to Bhalerao-2002
int sumSubarrayMins(vector<int>& A) {
int n = A.size();
int MOD = 1e9 + 7;
vector<int> left(n), right(n);
// for every i find the Next smaller element to left and right
// Left
stack<int>st;
st.push(0);
left[0] = 1; // distance = 1, left not found, this is distance multiplied with num, so it can't be zero
for(int i=1; i<n; i++)
{
while(!st.empty() && A[i] < A[st.top()])
st.pop();
if(st.empty())
left[i] = i+1; // total distance if less element not found = i+1
else
left[i] = i - st.top(); // distance = i-st.top()
st.push(i);
}
while(st.size())
st.pop();
// Right
st.push(n-1);
right[n-1] = 1; // distance = 1, right not found, this is distance multiplied with num, so it can't be zero
for(int i=n-2; i>=0; i--)
{
while(!st.empty() && A[i] <= A[st.top()])
st.pop();
if(st.empty())
right[i] = n-i; // distance
else
right[i] = st.top()-i;
st.push(i);
}
// total number of subarrays : (Left[i] * Right[i])
// total contribution in A[i] element in final answer : (Left * Right) * A[i]
for(int i=0; i<n; i++)
cout << left[i] << " : " << right[i] << endl;
// for each i, contribution is (Left * Right) * Element
int res = 0;
for(int i=0; i<n; i++)
{
long long prod = (left[i]*right[i])%MOD;
prod = (prod*A[i])%MOD;
res = (res + prod)%MOD;
}
return res%MOD;
}
}; | var sumSubarrayMins = function(arr) {
M = 10**9+7
stack = [-1]
res = 0
arr.push(0)
for(let i2 = 0; i2 < arr.length; i2++){
while(arr[i2] < arr[stack[stack.length -1]]){
i = stack.pop()
i1 = stack[stack.length-1]
Left = i - i1
Right = i2 -i
res += (Left*Right*arr[i])
};
stack.push(i2)
};
return res%M
}; | Sum of Subarray Minimums |
You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Constraints:
1 <= num <= 104
num consists of only 6 and 9 digits.
| class Solution:
def maximum69Number(self, num):
lst= list(str(num)) #! convert the number to a list
for i in range(len(lst)): #! iterate through the list
if lst[i]=='6': #! if the element is 6
lst[i]='9' #! replace the element with 9
break #! break the loop
return int(''.join(lst)) #! convert the list to a number | class Solution {
public int maximum69Number (int num) {
int i;
String s=String.valueOf(num);
int l=s.length();
int max=num;
for(i=0;i<l;i++)
{
char c[]=s.toCharArray();
if(c[i]=='9')
{
c[i]='6';
}
else
{
c[i]='9';
}
String p=new String(c);
int k=Integer.parseInt(p);
max=Math.max(max,k);
}
return max;
}
} | class Solution {
public:
int maximum69Number (int num) {
string s=to_string(num);
for(int i=0;i<s.size();i++){
if(s[i]=='6'){
s[i]='9';
break;
}
}
num=stoi(s);
return num;
}
}; | var maximum69Number = function(num) {
let flag=true
num= num.toString().split('').map((x)=>{
if(x!=='9'&&flag){
flag=false
return '9'
}
return x
})
return parseInt(num.join(''))
}; | Maximum 69 Number |
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Example 1:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
Example 2:
Input: nums = [-1,0]
Output: [-1,0]
Example 3:
Input: nums = [0,1]
Output: [1,0]
Constraints:
2 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each integer in nums will appear twice, only two integers will appear once.
| class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
x = Counter(nums)
return([y for y in x if x[y] == 1]) | class Solution {
public int[] singleNumber(int[] nums) {
if (nums == null || nums.length < 2 || nums.length % 2 != 0) {
throw new IllegalArgumentException("Invalid Input");
}
int aXORb = 0;
for (int n : nums) {
aXORb ^= n;
}
int rightSetBit = aXORb & -aXORb;
int a = 0;
for (int n : nums) {
if ((n & rightSetBit) != 0) {
a ^= n;
}
}
return new int[] {a, aXORb ^ a};
}
} | class Solution {
public:
vector<int> singleNumber(vector<int>& nums){
vector<int> ans;
int xorr = 0;
for(int i=0; i<nums.size(); i++){
xorr = xorr xor nums[i];
}
int count = 0;
while(xorr){
if(xorr & 1){
break;
}
count++;
xorr = xorr >> 1;
}
int xorr1 = 0;
int xorr2 = 0;
for(int i=0; i<nums.size(); i++){
if(nums[i] & (1 << count)){
xorr1 = xorr1 xor nums[i];
}
else{
xorr2 = xorr2 xor nums[i];
}
}
ans.push_back(xorr1);
ans.push_back(xorr2);
return ans;
}
}; | var singleNumber = function(nums) {
let hash ={}
for ( let num of nums){
if( hash[num]===undefined)
hash[num] =1
else
hash[num]++
}
let result =[]
for ( let [key, value] of Object.entries(hash)){
if(value==1)
result.push(key)
}
return result
}; | Single Number III |
You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).
Tax is calculated as follows:
The first upper0 dollars earned are taxed at a rate of percent0.
The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
And so on.
You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: brackets = [[3,50],[7,10],[12,25]], income = 10
Output: 2.65000
Explanation:
Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.
The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.
In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.
Example 2:
Input: brackets = [[1,0],[4,25],[5,50]], income = 2
Output: 0.25000
Explanation:
Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.
The tax rate for the two tax brackets is 0% and 25%, respectively.
In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.
Example 3:
Input: brackets = [[2,50]], income = 0
Output: 0.00000
Explanation:
You have no income to tax, so you have to pay a total of $0 in taxes.
Constraints:
1 <= brackets.length <= 100
1 <= upperi <= 1000
0 <= percenti <= 100
0 <= income <= 1000
upperi is sorted in ascending order.
All the values of upperi are unique.
The upper bound of the last tax bracket is greater than or equal to income.
| class Solution:
def calculateTax(self, brackets: List[List[int]], income: int) -> float:
taxtot=0
if(brackets[0][0]<income):
taxtot+=brackets[0][0]*(brackets[0][1])
income-=brackets[0][0]
else:
taxtot+=income*(brackets[0][1])
return taxtot/100
i=1
while(income>0 and i<len(brackets)):
if(income>(brackets[i][0]-brackets[i-1][0])):
taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]
income-=brackets[i][0]-brackets[i-1][0]
else:
taxtot+=income*brackets[i][1]
income=0
i+=1
return taxtot/100 | class Solution {
public double calculateTax(int[][] brackets, int income) {
double ans=0;
int pre=0;
for(int[] arr : brackets){
int val=arr[0]; arr[0]-=pre; pre=val;
ans+=(double)(Math.min(income,arr[0])*arr[1])/100;
income-=arr[0];
if(income<=0){ break; }
}
return ans;
}
} | class Solution {
public:
double calculateTax(vector<vector<int>>& brackets, int income)
{
double tax = 0;
if(brackets[0][0]<=income) tax=(brackets[0][0]*brackets[0][1]/100.0);
else return (income*brackets[0][1]/100.0);
for(int i=1; i<brackets.size(); i++)
{
if(brackets[i][0]<=income)
tax += ((brackets[i][0]-brackets[i-1][0])*brackets[i][1]/100.0);
else
{
tax += ((income-brackets[i-1][0])*brackets[i][1]/100.0);
break;
}
}
return tax;
}
}; | var calculateTax = function(brackets, income) {
return brackets.reduce(([tax, prev], [upper, percent]) => {
let curr = Math.min(income, upper - prev);
tax += curr * (percent / 100);
income -= curr;
if (income <= 0) brackets.length = 0;
return [tax, upper];
}, [0, 0])[0];
}; | Calculate Amount Paid in Taxes |
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendarTwo class:
MyCalendarTwo() Initializes the calendar object.
boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.
Example 1:
Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]
Explanation
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
Constraints:
0 <= start < end <= 109
At most 1000 calls will be made to book.
| class Node:
def __init__(self, start, end, val):
self.start = start
self.end = end
self.val = val
self.left = None
self.right = None
def insertable(self, node):
if node.end <= node.start:
return True
if node.end <= self.start:
if not self.left:
return True
else:
return self.left.insertable(node)
elif node.start >= self.end:
if not self.right:
return True
else:
return self.right.insertable(node)
else:
if self.val == 1:
leftS = min(self.start, node.start)
leftE = max(self.start, node.start)
rightS = min(self.end, node.end)
rightE = max(self.end, node.end)
if not self.left and not self.right:
return True
elif not self.left:
return self.right.insertable(Node(rightS, rightE, 1))
elif not self.right:
return self.left.insertable(Node(leftS, leftE, 1))
else:
resL = self.left.insertable(Node(leftS, leftE, 1))
resR = self.right.insertable(Node(rightS, rightE, 1))
if resL and resR:
return True
return False
else:
return False
def insert(self, node):
if node.end <= node.start:
return
if node.end <= self.start:
if not self.left:
self.left = node
else:
self.left.insert(node)
elif node.start >= self.end:
if not self.right:
self.right = node
else:
self.right.insert(node)
else:
leftS = min(self.start, node.start)
leftE = max(self.start, node.start)
rightS = min(self.end, node.end)
rightE = max(self.end, node.end)
self.val += 1
self.start, self.end = leftE, rightS
if not self.left and not self.right:
self.left = Node(leftS, leftE, 1) if leftS < leftE else None
self.right = Node(rightS, rightE, 1) if rightS < rightE else None
elif not self.left:
self.left = Node(leftS, leftE, 1) if leftS < leftE else None
self.right.insert(Node(rightS, rightE, 1))
elif not self.right:
self.right = Node(rightS, rightE, 1) if rightS < rightE else None
self.left.insert(Node(leftS, leftE, 1))
else:
self.left.insert(Node(leftS, leftE, 1))
self.right.insert(Node(rightS, rightE, 1))
return
class MyCalendarTwo:
def __init__(self):
self.root = None
def book(self, start: int, end: int) -> bool:
if not self.root:
self.root = Node(start, end, 1)
return True
else:
newNode = Node(start, end, 1)
if self.root.insertable(newNode):
self.root.insert(newNode)
return True
return False | class MyCalendarTwo {
private List<int[]> bookings;
private List<int[]> doubleBookings;
public MyCalendarTwo() {
bookings = new ArrayList<>();
doubleBookings = new ArrayList<>();
}
public boolean book(int start, int end) {
for(int[] b : doubleBookings)
{
//condition to check for the overlaping
if(start < b[1] && end > b[0])
return false;
}
for(int[] b : bookings)
{
if(start < b[1] && end > b[0]) {
doubleBookings.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});
}
}
bookings.add(new int[]{start, end});
return true;
}
} | class MyCalendarTwo {
public:
map<int,int>mpp;
MyCalendarTwo() {
}
bool book(int start, int end) {
mpp[start]++;
mpp[end]--;
int sum=0;
for(auto it:mpp){
sum+=it.second;
if(sum>2){
mpp[start]--;
mpp[end]++;
return false;
}
}
return true;
}
}; | var MyCalendarTwo = function() {
this.calendar = [];
this.overlaps = [];
};
/**
* @param {number} start
* @param {number} end
* @return {boolean}
*/
MyCalendarTwo.prototype.book = function(start, end) {
for (let date of this.overlaps) {
if (start < date[1] && end > date[0]) return false;
}
for (let date of this.calendar) {
if (start < date[1] && end > date[0]) {
this.overlaps.push([Math.max(date[0], start), Math.min(date[1], end)]);
}
}
this.calendar.push([start, end]);
return true;
}; | My Calendar II |
There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit.
Choose a subset s of the n elements such that:
The size of the subset s is less than or equal to numWanted.
There are at most useLimit items with the same label in s.
The score of a subset is the sum of the values in the subset.
Return the maximum score of a subset s.
Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
Output: 9
Explanation: The subset chosen is the first, third, and fifth items.
Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third items.
Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1
Output: 16
Explanation: The subset chosen is the first and fourth items.
Constraints:
n == values.length == labels.length
1 <= n <= 2 * 104
0 <= values[i], labels[i] <= 2 * 104
1 <= numWanted, useLimit <= n
| from collections import defaultdict
import heapq
class Solution:
def largestValsFromLabels(
self, values: list[int], labels: list[int], numWanted: int, useLimit: int
) -> int:
# Add labels and values into the heap
heap = [(-value, label) for value, label in zip(values, labels)]
heapq.heapify(heap)
# Initialize the hashmap
used = defaultdict(int)
# Initialize the result
res = 0
# Iterate until we have used a certain number or the heap is empty
while numWanted > 0 and heap:
# Pop a label and its value from the heap
value, label = heapq.heappop(heap)
# If we can use such label
if used[label] < useLimit:
# Add its value to the result
res += -value
# Increment its count in the hashmap
used[label] += 1
# Decrement the number of numbers we still want
numWanted -= 1
return res | class Solution {
public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
PriorityQueue<Pair<Integer, Integer>> maxHeap =
new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey()));
for(int i=0;i<values.length;i++) {
maxHeap.add(new Pair<Integer, Integer>(values[i], labels[i]));
}
Map<Integer, Integer> labelLimitMap = new HashMap<>();
int sum = 0;
while(numWanted != 0) {
int label = maxHeap.peek().getValue();
if(labelLimitMap.containsKey(label)) {
if(labelLimitMap.get(label) == useLimit) {
maxHeap.poll();
} else {
labelLimitMap.put(label, labelLimitMap.get(label) + 1);
sum += maxHeap.poll().getKey();
numWanted--;
}
} else {
labelLimitMap.put(label, 1);
sum += maxHeap.poll().getKey();
numWanted--;
}
// This Holds since at most numWanted is mentioned.
if(maxHeap.isEmpty()) {
return sum;
}
}
return sum;
}
} | class Solution {
public:
int largestValsFromLabels(vector<int>& values, vector<int>& labels, int numWanted, int useLimit) {
// same label item should be less than uselimit
priority_queue<pair<int,int>>q; // this will give us maximum element because we need to maximise the sum
for(int i=0;i<values.size();i++)
{
q.push({values[i],i});
}
long long int ans=0;
unordered_map<int,int>m;
// we cant use more numbers than useLimit
// storing each use labels in map to count the use limit of that number
int i=0;
while(i<numWanted)
{
int t=q.top().first; //number
int ind=q.top().second; // labels index
q.pop();
if(m[labels[ind]]<useLimit) // if less than count then include in our answer
{
ans+=t;
m[labels[ind]]++;
i++;
}
if(q.size()==0)
{
break;
}
}
return ans;
}
}; | /**
* @param {number[]} values
* @param {number[]} labels
* @param {number} numWanted
* @param {number} useLimit
* @return {number}
*/
var largestValsFromLabels = function(values, labels, numWanted, useLimit) {
// this sortValues will create an addition array that keep track of the value idx after descending sort
// which is useful to map the labels accordingly
let sortValues = values.map((val, idx) => [val, idx]), sortLabels = []
sortValues.sort((a, b) => b[0] - a[0])
for (let [val, idx] of sortValues) {
sortLabels.push(labels[idx])
}
values.sort((a, b) => b - a)
labels = sortLabels
let i = 0, map = {}, ans = 0
while (i < values.length && numWanted > 0) {
if (map[labels[i]]) map[labels[i]] ++
else map[labels[i]] = 1
if ((map[labels[i]]) <= useLimit) {
ans += values[i]
numWanted--
}
i++
}
return ans
}; | Largest Values From Labels |
Given the strings s1 and s2 of size n and the string evil, return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.
Example 1:
Input: n = 2, s1 = "aa", s2 = "da", evil = "b"
Output: 51
Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".
Example 2:
Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
Output: 0
Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.
Example 3:
Input: n = 2, s1 = "gx", s2 = "gz", evil = "x"
Output: 2
Constraints:
s1.length == n
s2.length == n
s1 <= s2
1 <= n <= 500
1 <= evil.length <= 50
All strings consist of lowercase English letters.
| from functools import lru_cache
class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
def srange(a, b):
return [chr(i) for i in range(ord(a),ord(b)+1)]
def LPS(pat):
lps = [0]
i, target = 1, 0
while i < len(pat):
if pat[i] == pat[target]:
target += 1
lps.append(target)
i += 1
elif target:
target = lps[target-1]
else:
lps.append(0)
i += 1
return lps
lps = LPS(evil)
M = 10**9+7
@lru_cache(None)
def dfs(i, max_matched_idx, lb, rb):
if max_matched_idx == len(evil): return 0
if i == n: return 1
l = s1[i] if lb else 'a'
r = s2[i] if rb else 'z'
candidates = srange(l, r)
res = 0
for j, c in enumerate(candidates):
nxt_matched_idx = max_matched_idx
while evil[nxt_matched_idx] != c and nxt_matched_idx:
nxt_matched_idx = lps[nxt_matched_idx-1]
res = (res + dfs(i+1, nxt_matched_idx+(c==evil[nxt_matched_idx]),
lb = (lb and j == 0), rb = (rb and j==len(candidates)-1)))%M
return res
return dfs(0, 0, True, True) | class Solution {
Integer[][][][] dp;
int mod = 1000000007;
int[] lps;
private int add(int a, int b) {
return (a % mod + b % mod) % mod;
}
private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) {
if(evI == evil.length) return 0;
if(cur == s2.length) return 1;
if(dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] != null) return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI];
char start = isStrictLower ? s1[cur] : 'a';
char end = isStrictUpper ? s2[cur] : 'z';
int res = 0;
for(char ch = start; ch <= end; ch ++) {
if(evil[evI] == ch)
res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, evI + 1));
else {
int j = evI;
while (j > 0 && evil[j] != ch) j = lps[j - 1];
if (ch == evil[j]) j++;
res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, j));
}
}
return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] = res;
}
public int findGoodStrings(int n, String s1, String s2, String evil) {
char[] arr = s1.toCharArray();
char[] brr = s2.toCharArray();
char[] crr = evil.toCharArray();
lps = new int[crr.length];
for (int i = 1, j = 0; i < crr.length; i++) {
while (j > 0 && crr[i] != crr[j]) j = lps[j - 1];
if (crr[i] == crr[j]) lps[i] = ++j;
}
dp = new Integer[n][2][2][crr.length];
return solve(arr, brr, 0, true, true, crr, 0);
}
} | class Solution {
public:
using ll = long long;
int findGoodStrings(int n, string s1, string s2, string evil) {
int M = 1e9+7;
int m = evil.size();
// kmp
int f[m];
f[0] = 0;
for (int i = 1, j = 0; i < m; ++i) {
while (j != 0 && evil[i] != evil[j]) {
j = f[j-1];
}
if (evil[i] == evil[j]) {
++j;
}
f[i] = j;
}
// next(i,c) jump function when matched i length and see c
int next[m+1][26];
for (int i = 0; i <= m; ++i) {
for (int j = 0; j < 26; ++j) {
if (i < m && evil[i] == 'a'+j) {
next[i][j] = i+1;
} else {
next[i][j] = i == 0? 0: next[f[i-1]][j];
}
}
}
// dp(i,j,l1,l2) length i greater than s1, less than s2;
// match j length of evil
// l1 true means limited for s1, l2 true means limited for s2
ll dp[n+1][m+1][2][2];
memset(dp, 0, sizeof(dp));
dp[0][0][1][1] = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int c = 0; c < 26; ++c) {
int k = next[j][c];
char ch = 'a'+c;
dp[i+1][k][0][0] += dp[i][j][0][0];
if (dp[i][j][1][1]) {
if (ch > s1[i] && ch < s2[i]) {
dp[i+1][k][0][0] += dp[i][j][1][1];
} else if (ch == s1[i] && ch == s2[i]) {
dp[i+1][k][1][1] += dp[i][j][1][1];
} else if (ch == s1[i]) {
dp[i+1][k][1][0] += dp[i][j][1][1];
} else if (ch == s2[i]) {
dp[i+1][k][0][1] += dp[i][j][1][1];
}
}
if (dp[i][j][1][0]) {
if (ch > s1[i]) {
dp[i+1][k][0][0] += dp[i][j][1][0];
} else if (ch == s1[i]) {
dp[i+1][k][1][0] += dp[i][j][1][0];
}
}
if (dp[i][j][0][1]) {
if (ch < s2[i]) {
dp[i+1][k][0][0] += dp[i][j][0][1];
} else if (ch == s2[i]) {
dp[i+1][k][0][1] += dp[i][j][0][1];
}
}
dp[i+1][k][0][0] %= M;
}
}
}
ll ans = 0;
for (int i = 0; i < m; ++i) {
ans += dp[n][i][0][0] + dp[n][i][0][1] + dp[n][i][1][0];
ans %= M;
}
return ans;
}
}; | const mod = 10 ** 9 + 7
let cache = null
/**
* @param {number} n
* @param {string} s1
* @param {string} s2
* @param {string} evil
* @return {number}
*/
var findGoodStrings = function(n, s1, s2, evil) {
/**
* 17 bits
* - 9 bit: 2 ** 9 > 500 by evil
* - 6 bit: 2 ** 6 > 50 by evil
* - 1 bit left (bound)
* - 1 bit right (bound)
*
* cache: `mainTraver` is the prefix length, `evilMatch` is matching for evil
*
* answer: marnTravel 0, evil 0, s prefix has the last character
*/
cache = new Array(1 << 17).fill(-1)
return dfs(0, 0, n, s1, s2, evil, true, true, computeNext(evil))
}
/**
* DFS:
* 1. loop from `s1` to `s2`, range of position `i` is [0, n]: 0 means no start, n means complete
* 2. if `s1` has traversed to nth, it means has been generated a legal character, and return 1; else
* 3. `mainTravel` is the length of the `s` generated by dfs last time
* 4. `evilMatch` is the length that matches the last generated `s` in evilMatch evil
* 5. n, s1, s2, evil, left, right, next
*/
function dfs(mainTravel, evilMatch, n, s1, s2, evil, left, right, next, ans = 0) {
// same length means that the match has been successful
if(evilMatch === evil.length) {
return 0
}
// this means s is conformed
if(mainTravel === n) {
return 1
}
// get key for cache
let key = generateKey(mainTravel, evilMatch, left, right)
// because any combination of the four categories will only appear once, there will be no repetition
if(cache[key] !== -1) {
return cache[key]
}
// get start, end calculate
let [start, end] = [left ? s1.charCodeAt(mainTravel) : 97, right ? s2.charCodeAt(mainTravel) : 122]
// loop
for(let i = start; i <= end; i++) {
// get char code
let code = String.fromCharCode(i)
// actually, `evilMatch` will only get longer or stay the same, not shorter
let m = evilMatch
while((m > 0) && (evil[m] !== code)) {
m = next[m - 1]
}
if(evil[m] === code) {
m++
}
// recursive
ans += dfs(mainTravel + 1, m, n, s1, s2, evil, left && (i === start), right && (i === end), next)
// too large
ans %= mod
}
// result after cache set
return cache[key] = ans, ans
}
// create key for cache
function generateKey(mainTravel, evilMatch, left, right) {
return (mainTravel << 8) | (evilMatch << 2) | ((left ? 1 : 0 ) << 1) | (right ? 1 : 0)
}
// for next right move, index + 1
function computeNext(evil, n = evil.length, ans = new Array(n).fill(0), k = 0) {
for(let i = 1; i < n; i++) {
while((k > 0) && (evil[i] !== evil[k])) {
k = ans[k - 1]
}
if(evil[i] === evil[k]) {
ans[i] = ++k
}
}
return ans
} | Find All Good Strings |
Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: houses = [1,4,8,10,20], k = 3
Output: 5
Explanation: Allocate mailboxes in position 3, 9 and 20.
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
Example 2:
Input: houses = [2,3,5,12,18], k = 2
Output: 9
Explanation: Allocate mailboxes in position 3 and 14.
Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
Constraints:
1 <= k <= houses.length <= 100
1 <= houses[i] <= 104
All the integers of houses are unique.
| class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
houses.sort()
@lru_cache(None)
def dp(left, right, k):
if k == 1: # <-- 1.
mid = houses[(left+right) // 2]
return sum(abs(houses[i] - mid) for i in range(left, right + 1))
return min(dp(left, i, 1) + dp(i+1, right, k - 1)
for i in range(left, right - k + 2)) # <-- 2.
return dp(0, len(houses)-1, k) | class Solution {
public int minDistance(int[] houses, int k) {
Arrays.sort(houses);
int n = houses.length;
int[] dp = new int[n];
for (int i = 1; i < n; i++){ // know optimal dist for i-1, then for i, we add houses[i] - houses[i/2]
dp[i]=dp[i-1]+houses[i]-houses[i/2];
}
for (int i = 0; i < k-1; i++){
int[] next = new int[n];
Arrays.fill(next, Integer.MAX_VALUE);
for (int j = 0; j < n; j++){
int sum = 0;
for (int m = j; m >= 0; m--){
sum += houses[(m+j+1)>>1]-houses[m]; // likewise, adding to the front needs the +1 to account for the truncation.
next[j] = Math.min(next[j], (m==0?0:dp[m-1])+sum);
}
}
dp=next;
}
return dp[n-1];
}
} | class Solution {
public:
int dp[101][101] ;
int solve(vector<int>&houses , int pos , int k){
if(k < 0) return 1e9 ;
if(pos >= houses.size()) return k ? 1e9 : 0 ;
if(dp[pos][k] != -1) return dp[pos][k] ;
//at current position pos, spread the group from (pos upto j) and allot this whole group 1 mailbox.
//start new neigbour at j + 1
int ans = INT_MAX ;
for(int j = pos ; j < houses.size() ; ++j ){
int middle = (pos + j) / 2 , cost = 0 ;
//cost calculation
for(int i = pos ; i <= j ; ++i ) cost += abs(houses[middle] - houses[i]);
ans = min(ans,cost + solve(houses,j + 1, k - 1)) ;
}
return dp[pos][k] = ans ;
}
int minDistance(vector<int>& houses, int k) {
sort(begin(houses),end(houses)) ;
memset(dp,-1,sizeof(dp)) ;
return solve(houses,0,k);
}
}; | /**
* @param {number[]} houses
* @param {number} k
* @return {number}
*/
var minDistance = function(houses, k) {
var distance=[],median,dist,cache={};
houses.sort(function(a,b){return a-b});
//distance[i][j] is the minimun distacne if we cover houses from ith index to jth index with 1 mailbox. This mailbox will be at the median index of sub array from ith index to jth index.
for(let i=0;i<houses.length;i++){
for(let j=i;j<houses.length;j++){
median = Math.floor((i+j)/2);
dist=0;
for(let k=i;k<=j;k++){
dist+=Math.abs(houses[median]-houses[k]);
}
if(distance[i]===undefined){
distance[i]=[];
}
distance[i][j]=dist;
}
}
return dp(0,k);
function dp(i,k){
let cacheKey=i+"_"+k;
if(cache[cacheKey]!==undefined){
return cache[cacheKey];
}
let min=Number.MAX_SAFE_INTEGER,ans;
if(i===houses.length && k===0){//Its a correct answer only if we have used all the mailboxes and all the houses are completed.
return 0;
}
if(i===houses.length || k===0){//Other than the first if condition, every other condition to exhaust either mailboxes for houses is an invalid answer. So returning minus an infinite number from here.
return min;
}
for(let j=i;j<houses.length;j++){//Here in each step we are covering houses from ith index to jth index with one mailbox and calling dp function to cover the rest of the houses, starting from jth+1 index with the remaining k-1 houses. In each possible answer we will keep the minimum ans.
ans = dp(j+1,k-1)+distance[i][j];
min = Math.min(min,ans);
}
cache[cacheKey]=min;
return min;
}
}; | Allocate Mailboxes |
Given a string licensePlate and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.
For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
Example 1:
Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.
Example 2:
Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]
Output: "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.
Constraints:
1 <= licensePlate.length <= 7
licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i] consists of lower case English letters.
| class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
newPlate = '' # modify the licensePlate
for i in licensePlate:
if i.isalpha():
newPlate += i.lower()
c = Counter(newPlate)
l1 = [] # store (word,len,index)
for idx,word in enumerate(words):
if Counter(word) >= c:
l1.append((word,len(word),idx))
l1.sort(key = lambda x:(x[1],idx))
return l1[0][0] | class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
//Store count of letters in LicensePlate
int[] licensePlateCount = new int[26];
//To store all words which meet the criteria
ArrayList<String> res = new ArrayList<>();
//To find min length word that meets the criteria
int min = Integer.MAX_VALUE;
//Add char count for each char in LicensePlate
for(Character c:licensePlate.toCharArray()) {
if(isChar(c)) {
licensePlateCount[Character.toLowerCase(c) - 'a']++;
}
}
//Add char count for each word in words
for(String word : words) {
int[] wordCharCount = new int[26];
boolean flag = true;
for(Character c:word.toCharArray()) {
wordCharCount[Character.toLowerCase(c) - 'a']++;
}
//Eliminate words that don't satisfy the criteria
for(int i = 0; i<26;i++) {
if(licensePlateCount[i] > wordCharCount[i]) flag = false;
}
//Add words satisfying criteria to res and calculate min word length
if(flag) {
res.add(word);
if(word.length() < min) min = word.length();
}
}
//Return 1st word in array meeting all criteria
for(int i = 0; i < res.size();i++) {
if(res.get(i).length() == min) return res.get(i);
}
//If not found, return -1 (or whatever interviewer expects)
return "-1";
}
private boolean isChar(Character c) {
if((c >='a' && c <='z') ||
(c>='A' && c<='Z')) return true;
return false;
}
} | class Solution {
public:
string shortestCompletingWord(string licensePlate, vector<string>& words)
{
string ans="";
vector<int> m(26,0);
for(auto &lp:licensePlate)
{
if(isalpha(lp))
m[tolower(lp)-'a']++;
}
for(auto &word:words)
{
vector<int> v=m;
for(auto &ch:word)
{
v[tolower(ch)-'a']--;
}
bool flag=true;
for(int i=0;i<26;i++)
{
if(v[i]>0)
flag =false;
}
if(flag&&(ans==""||ans.size()>word.size()))
ans=word;
}
return ans;
}
};
//if you like the solution plz upvote. | var shortestCompletingWord = function(licensePlate, words) {
// Object to hold the shortest word that matches
var match = {'found':false, 'word':''};
// Char array to hold the upper case characters we want to match
var licensePlateChars = licensePlate.toUpperCase().replace(/[^A-Z]/g, '').split('');
words.forEach(function (word) {
// if we already have a match make sure that the word we are checking is shorter
if (!match.found || word.length < match.word.length) {
var replaceWord = word.toUpperCase();
// Loop over each character in the license plate and replace one at a time
// the key here is that replace will only replace 1 S even if there are 2
licensePlateChars.forEach(function (lChar) {
replaceWord = replaceWord.replace(lChar, '');
});
// We know the word works if the length of the word minus
// the length of chars equals the length of the new word
if (word.length - licensePlateChars.length === replaceWord.length) {
match.found = true;
match.word = word
}
}
});
return match.word;
}; | Shortest Completing Word |
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
Example 1:
Input: grid = [[1,1],[3,4]]
Output: 8
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [1], [3], [4].
- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
- Paths with length 3: [1 -> 3 -> 4].
The total number of paths is 4 + 3 + 1 = 8.
Example 2:
Input: grid = [[1],[2]]
Output: 3
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [2].
- Paths with length 2: [1 -> 2].
The total number of paths is 2 + 1 = 3.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= grid[i][j] <= 105
| class Solution:
def __init__(self):
self.dp = None
self.di = [0, 0, -1, 1]
self.dj = [-1, 1, 0, 0]
self.mod = 1000000007
def countPaths(self, grid):
n = len(grid)
m = len(grid[0])
self.dp = [[0] * m for _ in range(n)]
ans = 0
for i in range(n):
for j in range(m):
ans = (ans + self.dfs(grid, i, j, -1)) % self.mod
return ans
def dfs(self, grid, i, j, prev):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= prev:
return 0
if self.dp[i][j] != 0:
return self.dp[i][j]
self.dp[i][j] = 1
for k in range(4):
self.dp[i][j] += self.dfs(grid, i + self.di[k], j + self.dj[k], grid[i][j])
self.dp[i][j] %= self.mod
return self.dp[i][j] % self.mod | class Solution {
long[][] dp;
int mod = 1_000_000_007;
public int countPaths(int[][] grid) {
dp = new long[grid.length][grid[0].length];
long sum=0L;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
sum = (sum + dfs(grid,i,j,0)) % mod;
}
}
return (int)sum;
}
long dfs(int[][] grid,int i,int j,int pre){
if(i<0||j<0||i>=grid.length||j>=grid[0].length) return 0;
if(grid[i][j]<=pre) return 0;
if(dp[i][j]>0) return dp[i][j];
long a = dfs(grid,i+1,j,grid[i][j]);
long b = dfs(grid,i,j+1,grid[i][j]);
long c = dfs(grid,i-1,j,grid[i][j]);
long d = dfs(grid,i,j-1,grid[i][j]);
dp[i][j] = (1+a+b+c+d)%mod;
return dp[i][j];
}
} | class Solution {
public:
int mod = 1000000007;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int countPaths(vector<vector<int>>& grid) {
vector <vector <int>> dp(grid.size(),vector<int>(grid[0].size(),-1));
long long count = 0;
for(int i = 0; i<grid.size(); i++){
for(int j = 0; j<grid[0].size(); j++){
count = (count%mod + dfs(i,j,grid,dp)%mod)%mod;
}
}
return (int)count%mod;
}
protected:
bool isvalid(int x, int y, vector<vector<int>>&grid){
if(x<0 or x>=grid.size() or y<0 or y>=grid[0].size()) return false;
return true;
}
int dfs(int x, int y, vector <vector<int>>&grid,vector <vector<int>>&dp){
if(dp[x][y]!=-1) return dp[x][y];
int ans = 1;
for(int i = 0; i<4; i++){
if(isvalid(x+dx[i],y+dy[i],grid) and grid[x][y]>grid[x+dx[i]][y+dy[i]]){
ans = (ans%mod+dfs(x+dx[i],y+dy[i],grid,dp)%mod)%mod;
}
}
return dp[x][y] = ans%mod;
}
}; | var countPaths = function(grid) {
let mod = Math.pow(10, 9) + 7;
let result = 0;
let rows = grid.length, columns = grid[0].length;
let dp = Array(rows).fill(null).map(_ => Array(columns).fill(0));
const dfs = (r, c, preVal)=> {
if (r < 0 || r == rows || c < 0 || c == columns || grid[r][c] <= preVal) return 0
if (dp[r][c]) return dp[r][c]
return dp[r][c] = (1 + dfs(r + 1, c, grid[r][c]) +
dfs(r - 1, c, grid[r][c]) +
dfs(r , c + 1, grid[r][c]) +
dfs(r , c - 1, grid[r][c])) % mod;
}
for(let i = 0; i < rows; i++) {
for(let j = 0; j < columns; j++) {
result += dfs(i, j, -1) % mod;
}
}
return result % mod;
}; | Number of Increasing Paths in a Grid |
You are given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= target <= 106
| class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
nums.sort()
left, right = 0, len(nums) - 1
count = 0
mod = 10 ** 9 + 7
while left <= right:
if nums[left] + nums[right] > target:
right -= 1
else:
count += pow(2, right - left, mod)
left += 1
return count % mod | class Solution {
public int numSubseq(int[] nums, int target) {
int n = nums.length;
int i =0, j = n-1;
int mod = (int)1e9+7;
Arrays.sort(nums);
int[] pow = new int[n];
pow[0]=1;
int count =0;
for(int z =1;z<n;z++){
pow[z] = (pow[z-1]*2)%mod;
}
while(i<=j){
if((nums[i]+nums[j]) <= target){
count=(count+pow[j-i])%mod;
i++;
}
else if((nums[i]+nums[j]) > target)
j--;
}
return count;
}
} | class Solution {
private:
int mod=1e9+7;
int multiply(int a,int b){
if(b==0){
return 0;
} else if(b%2==0){
int ans=multiply(a,b/2);
return (ans%mod+ans%mod)%mod;
} else {
int ans=multiply(a,b-1);
return (a%mod+ans%mod)%mod;
}
}
int power(int b,int e){
if(e==0){
return 1;
} else if(e%2==0){
int ans=power(b,e/2);
return multiply(ans,ans);
} else {
int ans=power(b,e-1);
return multiply(b,ans);
}
}
public:
int numSubseq(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int start=0,end=0;
while(end<nums.size() and nums[start]+nums[end]<=target){
end++;
}
end--;
int ans=0;
while(start<=end){
if(nums[start]+nums[end]<=target){
ans=(ans%mod+power(2,end-start))%mod;
start++;
} else {
end--;
}
}
return ans;
}
}; | const MOD = 1000000007;
var numSubseq = function(nums, target) {
nums.sort((a, b) => a - b);
const len = nums.length;
const pow = new Array(len).fill(1);
for(let i = 1; i < len; i++) {
pow[i] = (pow[i - 1] * 2) % MOD;
}
let l = 0, r = len - 1, ans = 0;
while(l <= r) {
if(nums[l] + nums[r] > target) {
r--; continue;
} else {
ans = (ans + pow[r - l]) % MOD;
l++;
}
}
return ans % MOD;
}; | Number of Subsequences That Satisfy the Given Sum Condition |
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
Return the minimum number of moves required to make s valid.
Example 1:
Input: s = "())"
Output: 1
Example 2:
Input: s = "((("
Output: 3
Constraints:
1 <= s.length <= 1000
s[i] is either '(' or ')'.
| class Solution:
def minAddToMakeValid(self, s: str) -> int:
stack = []
for parenthese in s:
if parenthese == "(":
stack.append("(")
else:
if not stack or stack[-1] == ")":
stack.append(")")
if stack and stack[-1] == "(":
stack.pop()
return len(stack) | class Solution {
public int minAddToMakeValid(String s) {
int open = 0;
int extra = 0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('){
open++;
}else{
if(open==0){
extra++;
}else{
open--;
}
}
}
return open+extra;
}
} | class Solution {
public:
int minAddToMakeValid(string s) {
stack<char> sta;
int nums = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '(')
{
sta.push(s[i]);
}
else
{
if (!sta.empty())
{
sta.pop();
}
else
{
nums++;
}
}
}
nums += sta.size();
return nums;
}
}; | var minAddToMakeValid = function(s) {
let stack = []
let count = 0
for(let i=0;i<s.length;i++) {
let ch = s[i]
if(ch === '(') {
stack.push(ch)
} else {
let top = stack.pop()
if(top != '(') count++
}
}
count += stack.length
return count
}; | Minimum Add to Make Parentheses Valid |
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Constraints:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity? | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False | class Solution {
public boolean increasingTriplet(int[] nums) {
if(nums.length < 3)
return false;
int x = Integer.MAX_VALUE;
int y = Integer.MAX_VALUE;
for (int i : nums){
if(i <= x){
x = i;
}else if (i <= y)
y = i;
else
return true;
}
return false;
}
} | class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
int smallest = INT_MAX;
int second_smallest = INT_MAX;
for(int i = 0;i<n;i++)
{
if(nums[i] <= smallest)
{
smallest = nums[i];
}
else if(nums[i] <= second_smallest)
{
second_smallest = nums[i];
}
else
{
return true;
}
}
return false;
}
}; | var increasingTriplet = function(nums) {
const length = nums.length, arr = [];
let tripletFound = false, arrLength, added = false, found = false;
if(length < 3) return false;
arr.push([nums[0],1]);
for(let index = 1; index < length; index++) {
let count = 1;
added = false;
found = false;
arrLength = arr.length;
for(let index2 = 0; index2 < arrLength; index2++) {
if(arr[index2][0] < nums[index]) {
added = true;
if(count !== arr[index2][1]+1) {
count = arr[index2][1]+1;
if(JSON.stringify(arr[index2+1]) !== JSON.stringify([nums[index],count]))
arr.push([nums[index],count]);
}
if(arr[index2][1]+1 === 3) {
tripletFound = true;
break;
}
}
if(arr[index2][0] === nums[index]) found = true;
}
if(tripletFound) break;
if(!added && !found) {
arr.push([nums[index],1]);
}
}
return tripletFound;
}; | Increasing Triplet Subsequence |
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.
Example 1:
Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
Example 2:
Input: arr = [1,2,3]
Output: [1,2,3]
Explanation: After calling your function, the input array is modified to: [1,2,3]
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 9
| class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
l = len(arr)
i,c=0,0
while i<l:
if arr[i]==0:
arr.insert(i+1,0)
i+=1
arr.pop()
i+=1 | class Solution {
// Time Complexity = O(n)
// Space Complexity = O(1)
public void duplicateZeros(int[] arr) {
// Loop through the array
for(int i = 0; i < arr.length; i++) {
// Trigger Condition
if(arr[i] ==0) {
int j; // auxilliary variable for swapping
for(j = arr.length-2; j>=i+1; j--) {
arr[j+1] = arr[j]; // Shift each element by one space
}
arr[j+1] = 0; // Duplicating the zero on the consecutive index of i
i++; // Skipping the duplicated zero index in the array
}
}
}
} | class Solution {
public:
void duplicateZeros(vector<int>& arr) {
for(int i=0;i<arr.size();i++)
{
if(arr[i]==0)
{
arr.pop_back();
arr.insert(arr.begin()+i,0);
i++;
}
}
}
}; | /**
* @param {number[]} arr
* @return {void} Do not return anything, modify arr in-place instead.
*/
var duplicateZeros = function(arr) {
// Variables
const originalLength = arr.length;
// Iterate over all the numbers in 'arr', if the number is 0 we duplicate it and skip the next loop iteration to prevent an overflow.
for (let idx = 0; idx < arr.length; idx ++)
{
const number = arr[idx];
if (number === 0 )
{
arr.splice(idx, 0, 0);
idx += 1;
};
};
// Here we restore the array to its original length.
return (arr.length = originalLength);
}; | Duplicate Zeros |
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
| class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
# defining dictionary
occ = dict()
# adding elements with their counts in dictionary
for element in arr:
if element not in occ:
occ[element] = 0
else:
occ[element] += 1
# list of count of elements
values = list(occ.values())
# Unique count
unique = set(values)
if len(values) == len(unique):
return True
else:
return False | class Solution {
public boolean uniqueOccurrences(int[] arr) {
Arrays.sort(arr);
HashSet<Integer> set = new HashSet<>();
int c = 1;
for(int i = 1; i < arr.length; i++)
{
if(arr[i] == arr[i-1]) c++;
else
{
if(set.contains(c)) return false;
set.add(c);
c = 1;
}
}
if(set.contains(c)) return false;
return true;
}
} | class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
unordered_map<int,int>sk;
unordered_map<int,int>skk;
for(int i=0;i<arr.size();i++){
sk[arr[i]]++;
}
for(auto j : sk)
{
if(skk[j.second]==1){
return false;
}
skk[j.second]++;
}
return true;
}
}; | var uniqueOccurrences = function(arr) {
const obj = {};
// Creating hashmap to store count of each number
arr.forEach(val => obj[val] = (obj[val] || 0) + 1);
// Creating an array of the count times
const val = Object.values(obj).sort((a, b) => a-b);
// Now, just finding the duplicates
for(let i = 0; i<val.length-1; i++){
if(val[i]===val[i+1]) return false;
}
return true;
}; | Unique Number of Occurrences |
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.
All gardens have at most 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.
Example 1:
Input: n = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]
Explanation:
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
Example 2:
Input: n = 4, paths = [[1,2],[3,4]]
Output: [1,2,1,2]
Example 3:
Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output: [1,2,3,4]
Constraints:
1 <= n <= 104
0 <= paths.length <= 2 * 104
paths[i].length == 2
1 <= xi, yi <= n
xi != yi
Every garden has at most 3 paths coming into or leaving it.
| class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
g = defaultdict(list)
for u,v in paths:
g[u-1].append(v-1)
g[v-1].append(u-1)
ans = [0]*n
for i in range(n):
c = [1,2,3,4]
for j in g[i]:
if ans[j] in c: c.remove(ans[j])
ans[i] = c.pop()
return ans | class Solution {
public int[] gardenNoAdj(int n, int[][] paths) {
boolean[][] graph = new boolean[n][n];
for(int i = 0;i<paths.length;i++){
int u = paths[i][0]-1;
int v = paths[i][1]-1;
graph[u][v] = true;
graph[v][u] = true;
}
int[] colored = new int[n];
boolean[] available = new boolean[4];
Arrays.fill(colored,-1);
colored[0] = 1;
for(int i = 1;i<n;i++){
for(int j = 0;j<n;j++){
if(graph[i][j] && colored[j]!=-1){
available[colored[j]-1]=true;
}
}
int k,flag = 0;
for(k = 0;k<4;k++){
if(available[k]==false){
flag = 1;
break;
}
}
colored[i] = k+1;
Arrays.fill(available,false);
}
return colored;
}
} | class Solution {
public:
int check(vector<int> a[],vector<int> &col,int sv,int i)
{
for(auto it:a[sv])
{
if(col[it]==i)return 0;
}
return 1;
}
void dfs(vector<int> a[],vector<int> &col,int sv,int lc)
{
for(int i = 1;i<5;i++)
{
if(check(a,col,sv,i))
{
col[sv] = i;
break;
}
}
for(auto it:a[sv])
{
if(col[it]==-1)
{
dfs(a,col,it,col[sv]);
}
}
}
vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) {
vector<int> a[n];
for(auto it:paths)
{
a[it[0]-1].push_back(it[1]-1);
a[it[1]-1].push_back(it[0]-1);
}
vector<int> col(n,-1);
for(int i = 0;i<n;i++)
{
if(col[i]==-1)
{
dfs(a,col,i,-7);
}
}
return col;
}
}; | /**
* @param {number} n
* @param {number[][]} paths
* @return {number[]}
*/
var gardenNoAdj = function(n, paths) {
//if n is less than or equal to four just return an array of size n from 1 to n
if(n <= 4){
let arr = []
let count = 1
while(arr.length < n){
arr.push(count)
count++
}
return arr
}
//if there are no gardens connecting to each other then just return an array of size n with ones
if(paths.length === 0)return new Array(n).fill(1)
//because we have three possible paths connecting to gardens and 4 flowers we know that this problems is possible because our graph is of degree 3 and we have D + 1 flowers
//to solve
let adjList = {}
// create an array filled with ones so if there is a garden with no path just fill with one
let result = new Array(n).fill(1)
let garden = new Set([1,2,3,4])
//create adj list from the paths
paths.forEach(path => {
let first = path[0];
let second = path[1];
if(first in adjList )adjList[first].neighbors.add(second)
else {adjList[first] = new Fnode(second)}
if(second in adjList)adjList[second].neighbors.add(first)
else {adjList[second] = new Fnode(first)}
})
for(let node in adjList){
//every node
let current = adjList[node]
//create a set of invalid flowers, flowers you can't use because they are part of
//the other gardens this one is connected to.
let invalidFlower = new Set();
//iterate over the neighbors to find what type of flower they have and if it is not
//null included in the invalid flowers set
current.neighbors.forEach(neighbor => {
if(adjList[neighbor]['flower'] !== null){
invalidFlower.add(adjList[neighbor]['flower'])
}
})
//create our possible value or better said our value because we will use the first one
//we obtain.
let possibleFlower;
//we iterate over over our garden {1,2,3,4}
for(let flower of garden) {
//and if our flower is not part of the invalid flowers;
if(!invalidFlower.has(flower)){
//we have found a possible flower we can use
possibleFlower = flower
//we break because this is the only one we need
break;
}
}
// we add our flower to current so that we dont use it in the future
current.flower = possibleFlower
//and update our result
result[node - 1] = possibleFlower
}
//we return our result
return result
};
//create a Flower class just for simplicity
class Fnode{
constructor(neighbor){
this.flower = null
this.neighbors = new Set([neighbor])
}
} | Flower Planting With No Adjacent |
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.
You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.
Example 1:
Input: amount = [1,4,2]
Output: 4
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup and a warm cup.
Second 2: Fill up a warm cup and a hot cup.
Second 3: Fill up a warm cup and a hot cup.
Second 4: Fill up a warm cup.
It can be proven that 4 is the minimum number of seconds needed.
Example 2:
Input: amount = [5,4,4]
Output: 7
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup, and a hot cup.
Second 2: Fill up a cold cup, and a warm cup.
Second 3: Fill up a cold cup, and a warm cup.
Second 4: Fill up a warm cup, and a hot cup.
Second 5: Fill up a cold cup, and a hot cup.
Second 6: Fill up a cold cup, and a warm cup.
Second 7: Fill up a hot cup.
Example 3:
Input: amount = [5,0,0]
Output: 5
Explanation: Every second, we fill up a cold cup.
Constraints:
amount.length == 3
0 <= amount[i] <= 100
| class Solution:
def fillCups(self, amount: List[int]) -> int:
count = 0
amount = sorted(amount, reverse=True)
while amount[0] > 0:
amount[0] -= 1
amount[1] -= 1
count += 1
amount = sorted(amount, reverse=True)
return count | class Solution {
public int fillCups(int[] amount) {
Arrays.sort(amount);
int x=amount[0];
int y=amount[1];
int z=amount[2];
int sum=x+y+z;
if(x+y>z){return sum/2 +sum%2;}
if(x==0&&y==0){return z;}
else{return z;}
}
} | class Solution {
public:
int fillCups(vector<int>& amount) {
sort(amount.begin(),amount.end());
int x=amount[0];
int y=amount[1];
int z=amount[2];
int sum=x+y+z;
if(x+y>z) return sum/2+sum%2;
if(x==0 && y==0) return z;
else return z;
}
}; | var fillCups = function(amount) {
var count = 0
var a = amount
while (eval(a.join("+")) > 0) {
var max = Math.max(...a)
a.splice(a.indexOf(max), 1)
var max2 = Math.max(...a)
a.splice(a.indexOf(max2), 1)
count++
if(max == 0) a.push(0)
else a.push(max - 1)
if (max2==0) a.push(0)
else a.push(max2 - 1)
} return count
} | Minimum Amount of Time to Fill Cups |
There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.
When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.
The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.
Example 1:
Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3
Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
Example 2:
Input: customers = [1], grumpy = [0], minutes = 1
Output: 1
Constraints:
n == customers.length == grumpy.length
1 <= minutes <= n <= 2 * 104
0 <= customers[i] <= 1000
grumpy[i] is either 0 or 1.
| class Solution:
def recursion(self,index,used):
# base case
if index == self.n: return 0
#check in dp
if (index,used) in self.dp: return self.dp[(index,used)]
#choice1 is using the secret technique
choice1 = -float('inf')
# we can only use secret technique once and consecutively
if used == True :
# use the secret technique
end = index + self.minutes if index + self.minutes < self.n else self.n
to_substract = self.prefix_sum[index - 1] if index != 0 else 0
val = self.prefix_sum[end - 1] - to_substract
choice1 = self.recursion(end,False) + val
# Do not use the secret tehcnique and play simple
choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)
ans = choice1 if choice1 > choice2 else choice2
# Memoization is done here
self.dp[(index,used)] = ans
return ans
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
self.n = len(customers)
self.customers = customers
self.grumpy = grumpy
self.minutes = minutes
self.dp = {}
self.prefix_sum = [x for x in customers]
for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]
return self.recursion(0,True)
| class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
int start = -1;
int count = 0;
int max = 0;
int curr = 0;
for (int i = 0; i < customers.length; i++) {
if (grumpy[i] == 0) {
count += customers[i];
} else {
curr += customers[i];
}
if (i-start > minutes) {
start++;
if (grumpy[start] == 1) {
curr -= customers[start];
}
}
max = Math.max(max, curr);
}
return count + max;
}
} | /*
https://leetcode.com/problems/grumpy-bookstore-owner/
TC: O(N)
SC: O(1)
Looking at the problem, main thing to find is the window where the minutes should
be used so that the owner is not grumpy and max customers in that window can be satisifed.
Find the window with most no. of satisfied customers given the owner was originally grumpy but
now has become not grumpy.
Since the owner can only be not grumpy for minutes duration, this sets our window size as well.
So with 'minutes' window size, find the max window.
Then add the max window value with the normal satisfied customers.
*/
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
// Tracks the max window where being not grumpy will add most customers and current grumpy window customers
int max_grumpy_window = 0, grumpy_window = 0;
int curr = 0, n = customers.size();
// Total satisifed customers when owner is not grumpy
int satisfied_cx = 0;
// net effective duration of not being grumpy
minutes = min(minutes, n);
// process the 1st window
while(curr < minutes) {
satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);
grumpy_window += (grumpy[curr] ? customers[curr] : 0);
++curr;
}
max_grumpy_window = max(max_grumpy_window, grumpy_window);
// process the remaining windows
while(curr < n) {
// Remove the 1st element of last window
grumpy_window -= (grumpy[curr - minutes] ? customers[curr - minutes] : 0);
// Add the latest element of current window
grumpy_window += (grumpy[curr] ? customers[curr] : 0);
max_grumpy_window = max(max_grumpy_window, grumpy_window);
satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);
++curr;
}
return satisfied_cx + max_grumpy_window;
}
}; | var maxSatisfied = function(customers, grumpy, minutes) {
let left=0;
let maxUnsatisfied=0;
let curr=0;
let satisfied=0;
// finding the satisfied customers
for(let i=0;i<customers.length;i++){
if(grumpy[i]===0)satisfied+=customers[i];
}
// finding the maximum un-satisfied customers within the give timeframe
// classic sliding window approach
for(let i=0;i<customers.length;i++){
if(grumpy[i]) curr+=customers[i];
if(i-left+1>minutes){
if(grumpy[left])curr-=customers[left]
left++
}
if(i-left+1===minutes){
if(curr>max){
maxUnsatisfied=curr
}
}
}
return satisfied + maxUnsatisfied;
}; | Grumpy Bookstore Owner |
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Constraints:
The input must be a binary string of length 32.
Follow up: If this function is called many times, how would you optimize it? | class Solution:
def hammingWeight(self, n: int) -> int:
i = 0
while n > 0:
if n % 2 != 0: i += 1
n = n >> 1
return i | public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
} | class Solution {
public:
int hammingWeight(uint32_t n) {
int ans=0;
while(n!=0){
n=n&(n-1);
ans++;
}
return ans;
}
}; | var hammingWeight = function(n) {
let count = 0, i = 0;
while(n > 0) {
i = 0;
while(n >= Math.pow(2,i)) {
i++;
}
count++;
n -= Math.pow(2,i-1);
}
return count;
}; | Number of 1 Bits |
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints:
n == nums.length
1 <= n <= 300
nums[i] is either 0, 1, or 2.
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
| class Solution:
def sortColors(self, nums: List[int]) -> None:
red, white, blue = 0, 0, len(nums) - 1
while white <= blue:
if nums[white] == 0:
nums[white], nums[red] = nums[red], nums[white]
red += 1
white += 1
elif nums[white] == 1:
white += 1
else:
nums[white], nums[blue] = nums[blue], nums[white]
blue -= 1 | class Solution {
public void sortColors(int[] nums) {
int zeroIndex = 0, twoIndex = nums.length - 1, i = 0;
while (i <= twoIndex) {
if (nums[i] == 0)
swap(nums, zeroIndex++, i++);
else if (nums[i] == 2)
swap(nums, twoIndex--, i);
else
i++;
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
} | class Solution {
public:
void sortColors(vector<int>& nums) {
int a =0; int b=0,c=0;int i;
for(i=0;i<nums.size();i++){
if(nums[i]==0){
a++;
}
if(nums[i]==1){
b++;
}
else c++;
}
for(i=0;i<nums.size();i++){
if(i<a){
nums[i]=0;
}
else if(i<a+b){
nums[i]=1;
}
else nums[i]=2;
}
}
}; | var sortColors = function(nums) {
let map = {
'0': 0,
'1': 0,
'2': 0
};
for(let char of nums) {
map[char] = map[char] + 1;
}
let values = Object.values(map);
let curr = 0;
for(let k=0; k<values.length; k++) {
for(let i=curr; i<curr+values[k]; i++) {
nums[i] = k;
}
curr = curr + values[k];
}
}; | Sort Colors |
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word consists of lowercase English letters.
ch is a lowercase English letter.
| class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
idx=word.find(ch)
if idx:
return word[:idx+1][::-1]+ word[idx+1:]
return word | class Solution {
public String reversePrefix(String word, char ch) {
char[] c = word.toCharArray();
int locate = 0;
for (int i = 0; i < word.length(); i++) { //first occurrence of ch
if (ch == c[i]) {
locate = i;
break;
}
}
char[] res = new char[word.length()];
for (int i = 0; i <= locate; i++) {
res[i] = c[locate - i];
}
for (int i = locate + 1; i < word.length(); i++) {
res[i] = c[i];
}
return String.valueOf(res);
}
} | class Solution {
public:
string reversePrefix(string word, char ch) {
string ans = "";
int tr = true;
for(auto w : word){
ans.push_back(w);
if(tr && w == ch){
tr=false;
reverse(ans.begin(), ans.end());
}
}
return ans;
}
}; | var reversePrefix = function(word, ch) {
return word.indexOf(ch) !== -1 ? word.split("").slice(0, word.indexOf(ch) + 1).reverse().join("") + word.slice(word.indexOf(ch) + 1) : word;
}; | Reverse Prefix of Word |
You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).
You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.
Return the smallest possible total score that you can achieve with some triangulation of the polygon.
Example 1:
Input: values = [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
Example 2:
Input: values = [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
The minimum score is 144.
Example 3:
Input: values = [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
Constraints:
n == values.length
3 <= n <= 50
1 <= values[i] <= 100
| class Solution:
def minScoreTriangulation(self, values: List[int]) -> int:
n = len(values)
c = [[0 for _ in range(n)] for _ in range(n)]
for L in range(2, n):
for i in range(1, n-L+1):
j = i + L - 1
c[i][j] = float('inf')
for k in range(i, j):
q = c[i][k] + c[k+1][j] + (values[i-1]*values[k]*values[j])
if c[i][j] > q:
c[i][j] = q
return c[1][n-1]
| class Solution {
int solve(int[] v, int i, int j){
if(i+1==j)
return 0;
int ans= Integer.MAX_VALUE;
for(int k=i+1;k<j;k++){
ans= Math.min(ans, (v[i]*v[j]*v[k] + solve(v,i,k) + solve(v,k,j) ) );
}
return ans;
}
int solveMem(int[] v, int i, int j, int[][] dp){
if(i+1==j)
return 0;
if(dp[i][j]!=-1)
return dp[i][j];
int ans= Integer.MAX_VALUE;
for(int k=i+1;k<j;k++){
ans = Math.min(ans, (v[i]*v[j]*v[k] + solveMem(v,i,k,dp) + solveMem(v,k,j,dp) ) );
}
dp[i][j]=ans;
return dp[i][j];
}
int solveTab(int[] v){
int n= v.length;
int[][] dp= new int[n][n];
for(int i=n-1;i>=0;i--){
for(int j=i+2;j<n;j++){
int ans=Integer.MAX_VALUE;
for(int k=i+1;k<j;k++){
ans = Math.min(ans, (v[i]*v[j]*v[k] + dp[i][k] + dp[k][j] ) );
}
dp[i][j]=ans;
}
}
return dp[0][n-1];
}
public int minScoreTriangulation(int[] values) {
int n= values.length;
// return solve(values, 0, n-1); // For Recursion
/* int[][] dp= new int[n][n]; // For Top-Down DP(Memoisation)
for(int[] row:dp){
Arrays.fill(row,-1);
}
return solveMem(values,0,n-1,dp);
*/
return solveTab(values); //For Bottom-Down DP(Tabulisation)
}
} | class Solution {
public:
int f(int i,int j,vector<int>& values,vector<vector<int>> &dp){
if(i == j || i+1 == j) return 0;
if(dp[i][j] != -1) return dp[i][j];
int res = INT_MAX;
for(int k = i+1;k < j;k++)
{
int temp = values[i]*values[j]*values[k] + f(k,j,values,dp) + f(i,k,values,dp);
res = min(res,temp);
}
return dp[i][j] = res;
}
int minScoreTriangulation(vector<int>& values) {
int n = values.size();
vector<vector<int>> dp(n+1,vector<int>(n+1,-1));
return f(0,n - 1,values,dp);
} | var minScoreTriangulation = function(values) {
let dp = Array(values.length).fill().map((i) => Array(values.length).fill(0));
function dfs(i, j) {
if (dp[i][j]) return dp[i][j];
if (j - i < 2) return 0;
let min = Infinity;
// k forms a triangle with i and j, thus bisecting the array into two parts
// These two parts become two subproblems that can be solved recursively
for (let k = i + 1; k < j; k++) {
let sum = values[i] * values[j] * values[k] + dfs(i, k) + dfs(k, j);
min = Math.min(min, sum);
}
return dp[i][j] = min;
}
return dfs(0, values.length - 1);
}; | Minimum Score Triangulation of Polygon |
Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.
Return the length of n. If there is no such n, return -1.
Note: n may not fit in a 64-bit signed integer.
Example 1:
Input: k = 1
Output: 1
Explanation: The smallest answer is n = 1, which has length 1.
Example 2:
Input: k = 2
Output: -1
Explanation: There is no such positive integer n divisible by 2.
Example 3:
Input: k = 3
Output: 3
Explanation: The smallest answer is n = 111, which has length 3.
Constraints:
1 <= k <= 105
| class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if k % 2 == 0: return -1
n = 1
leng = 1
mapp = {}
while True:
rem = n % k
if rem == 0: return leng
if rem in mapp : return -1
mapp[rem] = True
n = n*10 + 1
leng += 1
| class Solution {
public int smallestRepunitDivByK(int k) {
// if (k % 2 == 0 || k % 5 == 0) return -1; // this trick may save a little time
boolean[] hit = new boolean[k];
int n = 0, ans = 0;
while (true) { // at most k times, because 0 <= remainder < k
++ ans;
n = (n * 10 + 1) % k; // we only focus on whether to divide, so we only need to keep the remainder.
if (n == 0) return ans; // can be divisible
if (hit[n]) return -1; // the remainder of the division repeats, so it starts to loop that means it cannot be divisible.
hit[n] = true;
}
}
} | class Solution {
public:
int smallestRepunitDivByK(int k) {
if(k&1==0)return -1;
long long val=0;
for(int i=1; i<=k;i++)
{
// val=((val*10)+1);
if((val=(val*10+1)%k)==0)return i;
}
return -1;
}
}; | /**
* @param {number} k
* @return {number}
*/
var smallestRepunitDivByK = function(k) {
if( 1 > k > 1e6 ) return -1;
let val = 0;
for (let i = 1; i < 1e6; i++) {
val = (val * 10 + 1) % k;
if (val === 0) return i;
}
return -1;
}; | Smallest Integer Divisible by K |
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
The number of nodes in the tree is n.
1 <= k <= n <= 104
0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
| # 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
n=0
stack=[] # to store the elements
cur=root # pointer to iterate
while cur or stack:
while cur: # used to find the left most element
stack.append(cur)
cur=cur.left
cur=stack.pop() # pop the most recent element which will be the least value at that moment
n+=1
if n==k:
return cur.val
cur=cur.right | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int element,count;
public int kthSmallest(TreeNode root, int k) {
inorderTraversal(root,k);
return element;
}
public void inorderTraversal(TreeNode root,int k){
if(root.left != null){
inorderTraversal(root.left,k);
}
count++;
if(count==k){
element = root.val;
}
if(root.right != null){
inorderTraversal(root.right,k);
}
}
} | class Solution {
public:
void findInorder(TreeNode* root, vector<int> &ans) {
if(root == NULL)
return;
findInorder(root->left, ans);
ans.push_back(root->val);
findInorder(root->right, ans);
}
int kthSmallest(TreeNode* root, int k) {
vector<int> ans;
findInorder(root, ans);
return ans[k-1];
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
let stack = [];
while(root != null || stack.length > 0) {
while(root != null){
stack.push(root);
root = root.left
}
root = stack.pop();
if(--k == 0) break;
root = root.right;
};
return root.val;
}; | Kth Smallest Element in a BST |
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
The test cases are generated so that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106
| class Solution:
def helper(self,nums,m):
Sum = 0
for n in nums:
Sum += math.ceil(n/m)
return Sum
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
l,r = 1, max(nums)
while l < r:
mid = (l+r)//2
Sum = self.helper(nums,mid)
if Sum > threshold:
l = mid + 1
else:
r = mid
return r | class Solution {
public int smallestDivisor(int[] a, int h) {
int l = 1, r = a[0];
for (int x : a) if (x > r) r = x;
while (l < r) {
int m = l + (r-l)/2;
if (valid(a, m, h)) r = m;
else l = m + 1;
}
return l;
}
private boolean valid(int[] a, int m, int h) {
for (int x : a)
if ((h -= (x + m-1)/m) < 0) return false;
return true;
}
} | class Solution {
public:
int smallestDivisor(vector<int>& nums, int threshold) {
int l=1,r=0;
for(int n:nums)r=max(r,n);
int mid,s=0;
while(l<r){
s=0;
mid = l+(r-l)/2;
for(int n:nums){
s+= n/mid + (n%mid !=0);
}
if(s<= threshold){
r=mid;
}else{
l=mid+1;
}
}
return r;
}
}; | var smallestDivisor = function(nums, threshold) {
let left = 1;
let right = nums.reduce((r, x) => Math.max(r, x), 0);
while (left <= right) {
const div = Math.floor((left + right) / 2);
const sum = nums.reduce((r, x) => r + Math.ceil(x / div), 0);
if (sum <= threshold) {
right = div - 1;
} else {
left = div + 1;
}
}
return left;
}; | Find the Smallest Divisor Given a Threshold |
A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Example 1:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
Example 2:
Input: words = ["t"]
Output: 2
Explanation: A valid encoding would be s = "t#" and indices = [0].
Constraints:
1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] consists of only lowercase letters.
| class Solution:
def minimumLengthEncoding(self, words):
# root of suffix trie
trie_root = dict()
# helper function to judge leaf node
isLeafNode = lambda node: len(node) == 0
# collection of tail nodes
tail_nodes = []
# set of unique words
unique_words = set(words)
# scan each word
for word in unique_words:
# build suffix trie from root node
cur = trie_root
# scan each character in reversed order
for char in reversed(word):
# update trie
cur[char] = cur.get(char, dict() )
# go to next level
cur = cur[char]
# save tail nodes with corresponding word length, +1 is for '#' symbol
tail_nodes.append( (cur, len(word)+1) )
# summation of the length with all tail node which is also a leaf node
return sum( suffix_length for node, suffix_length in tail_nodes if isLeafNode(node) ) | class Node {
private boolean flag;
private Node[] children;
public Node () {
flag = false;
children = new Node[26];
Arrays.fill (children, null);
}
public boolean getFlag () {
return flag;
}
public Node getChild (int index) {
return children[index];
}
public boolean hasChild (int index) {
return children[index] != null;
}
public void setFlag (boolean flag) {
this.flag = flag;
}
public void makeChild (int index) {
children[index] = new Node();
}
}
class Trie {
private Node root;
public Trie () {
root = new Node();
}
public int addWord (String word) {
boolean flag = true;
Node node = root;
int count = 0;
for (int i = word.length () - 1; i >= 0; --i) {
int index = (int) word.charAt(i) - 97;
if (!node.hasChild (index)) {
flag = false;
node.makeChild (index);
}
node = node.getChild (index);
if (node.getFlag()) {
node.setFlag (false);
count -= word.length() - i + 1;
if (i == 0)
flag = false;
}
}
if (!flag)
node.setFlag (true);
return flag? count: count + 1 + word.length();
}
}
class Solution {
public int minimumLengthEncoding(String[] words) {
Trie trie = new Trie ();
int size = 0;
for (String word: words) {
size += trie.addWord (word);
}
return size;
}
} | class TrieNode{
public:
bool isEnd;
vector<TrieNode*> children;
TrieNode(){
isEnd = false;
children = vector<TrieNode*>(26, NULL);
}
};
class Trie{
public:
TrieNode* root;
Trie(){
root = new TrieNode();
}
void insert(string& word, bool& isSuffix){
auto cur = root;
for(int i=0; i<word.size(); i++){
int index = word[i] - 'a';
//If new node is needed to be inserted for this word, then this word can't be suffix of some other word.
if(cur->children[index] == NULL){
isSuffix = false;
cur->children[index] = new TrieNode();
}
cur = cur->children[index];
}
cur -> isEnd= true;
}
};
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
sort(words.begin(), words.end(), [](string& a, string& b){
return a.size() > b.size();
});
int res = 0;
Trie* trie = new Trie();
for(auto word: words){
reverse(word.begin(), word.end());
bool wordIsSuffix = true;
trie->insert(word, wordIsSuffix);
// If word is not suffix of some other word, it needs to be added separately
if(!wordIsSuffix) res += word.size()+1; //+1 for '#'
}
return res;
}
}; | /**
* @param {string[]} words
* @return {number}
*/
class Trie {
constructor(letter) {
this.letter = letter;
this.children = new Map();
this.isWord = false;
}
}
var minimumLengthEncoding = function(words) {
let minEncodingLength = 0;
const sortedWords = words.sort((a, b) => a.length - b.length);
const buildTrie = (root, word, index) => {
// This means we reached to the end of word, so mark it as a word and compute encoding length
if (index < 0) {
minEncodingLength += word.length + 1;
root.isWord = true;
return;
}
const character = word[index];
// If we do not have a char in children, create a node and add it under root
if (!root.children.has(character)) {
const node = new Trie(character);
root.children.set(character, node);
buildTrie(node, word, index - 1);
return;
}
const node = root.children.get(character);
// Remove the common suffix length considered before since it would be covered as a part of current word traversal
if (node.isWord) {
node.isWord = false;
minEncodingLength -= word.length - index + 1;
}
buildTrie(node, word, index - 1);
};
const root = new Trie();
for (const word of sortedWords) {
buildTrie(root, word, word.length - 1);
}
return minEncodingLength;
}; | Short Encoding of Words |
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Example 1:
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true
Example 2:
Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
Constraints:
The number of nodes in each tree will be in the range [1, 200].
Both of the given trees will have values in the range [0, 200].
| # class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
tree=[]
def inorder(root):
nonlocal tree
if root is None:
return
if root.left is None and root.right is None:
tree.append(root.val)
inorder(root.left)
inorder(root.right)
inorder(root1)
inorder(root2)
tree1=tree[:len(tree)//2]
tree2=tree[len(tree)//2:]
if tree1==tree2:
return True
else:
return False | class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> list1 = new ArrayList<>();
checkLeaf(root1, list1);
List<Integer> list2 = new ArrayList<>();
checkLeaf(root2, list2);
if(list1.size() != list2.size()) return false;
int i = 0;
while(i < list1.size()){
if(list1.get(i) != list2.get(i)){
return false;
}
i++;
}
return true;
}
private void checkLeaf(TreeNode node, List<Integer> arr){
if(node.left == null && node.right == null) arr.add(node.val);
if(node.left != null) checkLeaf(node.left, arr);
if(node.right != null) checkLeaf(node.right, arr);
}
} | /**
* 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:
/* How to get LeafOrder?
Simply traverse the tree Left->right
whenever you get a leaf, push its value to a vector
*/
void getLeafOrder(TreeNode* root, vector<int> &leafOrder){ // Here we are passing vector
if(root == NULL){ // by reference to make changes
return; // directly in main vector
}
// Leaf found -> push its value in the vector
if(root->left == NULL and root->right == NULL){
leafOrder.push_back(root->val);
return;
}
getLeafOrder(root->left, leafOrder); // Left then Right -> to maintain the sequence
getLeafOrder(root->right, leafOrder);
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> leafOrder1;
vector<int> leafOrder2;
getLeafOrder(root1, leafOrder1); // Get leaf order for both trees
getLeafOrder(root2, leafOrder2);
return leafOrder1 == leafOrder2; // return if they are equal or not
}
}; | /*
* 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} root1
* @param {TreeNode} root2
* @return {boolean}
*/
var leafSimilar = function(root1, root2) {
let array1 = [], array2 = [];
let leaf1 = getLeaf(root1, array1),
leaf2 = getLeaf(root2, array2);
if (leaf1.length !== leaf2.length){ // if different lengths, return false right away
return false;
}
for(let i = 0; i < leaf1.length; i++){
if (leaf1[i] !== leaf2[i]){ // compare pair by pair
return false;
}
}
return true;
};
var getLeaf = function(root, array){ // DFS
if (!root){
return;
}
if (!(root.left || root.right)){
array.push(root.val); // push leaf value to the array
}
getLeaf(root.left, array);
getLeaf(root.right, array);
return array;
} | Leaf-Similar Trees |
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Example 1:
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:
Input: root = [5,1,7]
Output: [1,null,5,null,7]
Constraints:
The number of nodes in the given tree will be in the range [1, 100].
0 <= Node.val <= 1000
| class Solution(object):
def increasingBST(self, root):
def sortBST(node):
if not node: return []
# return the in order BST nodes in list
return sortBST(node.left) + [node.val] + sortBST(node.right)
# the in order sorted list of the tree nodes
sorted_list = sortBST(root)
# generate new tree: temp for update, ans for return the root
ans = temp = TreeNode(sorted_list[0])
# insert nodes to the right side of the new tree
for i in range(1, len(sorted_list)):
temp.right = TreeNode(sorted_list[i])
temp = temp.right
return ans | class Solution {
TreeNode inRoot = new TreeNode();
TreeNode temp = inRoot;
public TreeNode increasingBST(TreeNode root) {
inorder(root);
return inRoot.right;
}
public void inorder(TreeNode root) {
if(root==null)
return;
inorder(root.left);
temp.right = new TreeNode(root.val);
temp = temp.right;
inorder(root.right);
}
} | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* temp;
vector<int>z;
TreeNode* increasingBST(TreeNode* root)
{
incresing(root);
sort(z.begin(), z.end());
temp = new TreeNode(z[0]);
create(temp, z);
return temp;
}
void incresing(TreeNode* root)
{
if(root == NULL) return;
z.push_back(root->val);
incresing(root->left);
incresing(root->right);
}
void create(TreeNode* create, vector<int> ze)
{
for(int i = 1; i<ze.size(); i++)
{
cout<<ze[i]<<endl;
create->right = new TreeNode(ze[i]);
create = create->right;
}
}
}; | var increasingBST = function(root) {
let newRoot = new TreeNode(-1);
const newTree = newRoot;
const dfs = (node) => {
if (!node) return null;
if (node.left) dfs(node.left);
const newNode = new TreeNode(node.val);
newRoot.right = newNode;
newRoot.left = null;
newRoot = newRoot.right;
if (node.right) dfs(node.right);
}
dfs(root);
return newTree.right;
}; | Increasing Order Search Tree |
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
listA - The first linked list.
listB - The second linked list.
skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Constraints:
The number of nodes of listA is in the m.
The number of nodes of listB is in the n.
1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA < m
0 <= skipB < n
intersectVal is 0 if listA and listB do not intersect.
intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory? | class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
m = 0
n = 0
temp = headA
while temp != None:
m+=1
temp = temp.next
temp = headB
while temp != None:
n+=1
temp = temp.next
diff = 0
if m>=n :
diff = m-n
else:
diff = n-m
p1 = headA
p2 = headB
if max(m,n) == m:
while diff > 0:
p1 = p1.next
diff-=1
else:
while diff > 0:
p2 = p2.next
diff-=1
while p1 != None and p2!=None:
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None | public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempA = headA, tempB = headB;
int lenA = 0, lenB = 0;
while (tempA != null) {
lenA++;
tempA = tempA.next;
}
while (tempB != null) {
lenB++;
tempB = tempB.next;
}
tempA = headA; tempB = headB;
if (lenB > lenA) {
for (int i = 0; i < lenB - lenA; i++) {
tempB = tempB.next;
}
} else if (lenA > lenB) {
for (int i = 0; i < lenA - lenB; i++) {
tempA = tempA.next;
}
}
while (tempA != null && tempA != tempB) {
tempA = tempA.next;
tempB = tempB.next;
}
return tempA;
}
} | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//function to get length of linked list
int getLength(ListNode *head)
{
//initial length 0
int l = 0;
while(head != NULL)
{
l++;
head = head->next;
}
return l;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//ptr1 & ptr2 will move to check nodes are intersecting or not
//ptr1 will point to the list which have higher length, higher elements (big list)
//ptr2 will point to small list
ListNode *ptr1,*ptr2;
//fetching length of both the list,as we want a node that both ptr points simultaneously
//so if both list have same length of nodes, they travel with same speed, they intersect
//if diff legths, it'll be difficult for us to catch
//so by substracting list with higher length with lower length
//we get same level of length, from which both ptr start travaeling, they may get intersect
int length1 = getLength(headA);
int length2 = getLength(headB);
int diff = 0;
//ptr1 points to longer list
if(length1>length2)
{
diff = length1-length2;
ptr1 = headA;
ptr2 = headB;
}
else
{
diff = length2 - length1;
ptr1 = headB;
ptr2 = headA;
}
//till diff is zero and we reach our desired posn
while(diff)
{
//incrementing ptr1 so that it can be at a place where both list have same length
ptr1 = ptr1->next;
if(ptr1 == NULL)
{
return NULL;
}
diff--;
}
//traverse both pointers together, till any of them gets null
while((ptr1 != NULL) && (ptr2 != NULL))
{
//at any point, both point to same node return it
if(ptr1 == ptr2)
{
return ptr1;
}
//increment both pointers, till they both be NULL
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
//if not found any intersaction, return null
return NULL;
}
}; | var getIntersectionNode = function(headA, headB) {
let node1 = headA;
let node2 = headB;
const set = new Set()
while(node1 !== undefined || node2!== undefined){
if(node1 && set.has(node1)){
return node1
}
if(node2 && set.has(node2)){
return node2
}
if(node1){
set.add(node1)
node1 = node1.next;
}
else if(node2){
set.add(node2)
node2 = node2.next;
}
else {return}
}
}; | Intersection of Two Linked Lists |
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).
Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Example 1:
Input: matrix = [[1,2,3],[3,1,2],[2,3,1]]
Output: true
Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.
Hence, we return true.
Example 2:
Input: matrix = [[1,1,1],[1,2,3],[1,2,3]]
Output: false
Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.
Hence, we return false.
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 100
1 <= matrix[i][j] <= n
| class Solution:
def checkValid(self, matrix: List[List[int]]) -> bool:
lst = [0]*len(matrix)
for i in matrix:
if len(set(i)) != len(matrix):
return False
for j in range(len(i)):
lst[j] += i[j]
return len(set(lst)) == 1 | class Solution {
public boolean checkValid(int[][] matrix) {
int n = matrix.length;
int num = (n*(n+1))/2; // SUM of n number 1 to n;
for(int i=0; i<n; i++)
{
HashSet<Integer> hs = new HashSet<Integer>();
HashSet<Integer> hs1 = new HashSet<Integer>();
int m = num; int k = num;
for(int j = 0; j<n; j++)
{
hs.add(matrix[i][j]);
hs1.add(matrix[j][i]);
m -= matrix[i][j];
k -= matrix[j][i];
}
if(m != 0 || k != 0 || hs.size() != n || hs.size() != n)
{
return false;
}
}
return true;
}
} | class Solution {
public:
bool checkValid(vector<vector<int>>& matrix) {
int n=matrix.size();
unordered_set<int> s1, s2;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(s1.find(matrix[i][j])!=s1.end())
return false;
else
s1.insert(matrix[i][j]);
if(s2.find(matrix[j][i])!=s2.end())
return false;
else
s2.insert(matrix[j][i]);
}
s1.clear();
s2.clear();
}
return true;
}
}; | var checkValid = function(matrix) {
for(let i =0; i<matrix.length;i++){
const cols = new Set(), rows = new Set(matrix[i]);
for(let j =0; j<matrix.length;j++){
if(matrix[j][i] > matrix.length) return false;
cols.add(matrix[j][i])
}
if(cols.size < matrix.length || rows.size < matrix.length) return false;
}
return true;
}; | Check if Every Row and Column Contains All Numbers |
You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
Return the length of the shortest sequence of rolls that cannot be taken from rolls.
A sequence of rolls of length len is the result of rolling a k sided dice len times.
Note that the sequence taken does not have to be consecutive as long as it is in order.
Example 1:
Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.
Example 2:
Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.
Example 3:
Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.
Constraints:
n == rolls.length
1 <= n <= 105
1 <= rolls[i] <= k <= 105
| class Solution:
def shortestSequence(self, rolls: List[int], k: int) -> int:
ans = 1
data = set()
for roll in rolls:
data.add(roll)
if len(data) == k:
ans += 1
data.clear()
return ans | class Solution {
public int shortestSequence(int[] rolls, int k) {
int len = 0;
Set<Integer> set = new HashSet<>();
for(int i:rolls)
{
set.add(i);
if(set.size()==k)
{
set = new HashSet<>();
len++;
}
}
return len+1;
}
} | class Solution {
public:
int shortestSequence(vector<int>& rolls, int k) {
int len = 1;
set<int> data ;
for (int i = 0; i < rolls.size(); i++) {
data.insert(rolls[i]);
if (data.size() == k) {
len++;
data = set<int>();
}
}
return len;
}
}; | var shortestSequence = function(rolls, k)
{
let ans=1;
let sett=new Set();
for(let i of rolls)
{
sett.add(i);
if(sett.size===k)
{
ans++;
sett=new Set();
}
}
return ans;
}; | Shortest Impossible Sequence of Rolls |
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100
| class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
dummy = ListNode(None, head)
prev, curr_1, curr_2 = dummy, head, head.next
while curr_1 and curr_2:
# 1. define temp nodes, temp nodes are comprised of 1 prev node, and multiple curr nodes. The while condition checks those curr nodes only.
node_0 = prev
node_1 = curr_1
node_2 = curr_2
node_3 = curr_2.next
# 2. swap nodes using temp nodes
node_0.next = node_2
node_1.next = node_3
node_2.next = node_1
# 3. move temp nodes to the next window
prev = node_1
curr_1 = node_3
curr_2 = node_3.next if node_3 else None
return dummy.next | class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0) , prev = dummy , curr = head;
dummy.next = head;
while(curr != null && curr.next != null){
prev.next = curr.next;
curr.next = curr.next.next ;
prev.next.next = curr;
curr = curr.next ;
prev = prev.next.next;
}
return dummy.next;
}
} | class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// if head is NULL OR just having a single node, then no need to change anything
if(head == NULL || head -> next == NULL)
{
return head;
}
ListNode* temp; // temporary pointer to store head -> next
temp = head->next; // give temp what he want
head->next = swapPairs(head->next->next); // changing links
temp->next = head; // put temp -> next to head
return temp; // now after changing links, temp act as our head
}
}; | var swapPairs = function(head) {
if(!head || !head.next) return head;
// using an array to store all the pairs of the list
let ptrArr = [];
let ptr = head;
while(ptr) {
ptrArr.push(ptr);
let nptr = ptr.next ? ptr.next.next : null;
if(nptr) ptr.next.next = null;
ptr = nptr;
}
// reversing all the pairs of the list in array
for(let i=0;i<ptrArr.length;i++) {
let node = ptrArr[i];
let temp = node.next;
if(!temp) break;
temp.next = node;
node.next = null;
ptrArr[i] = temp;
}
let dummy = new ListNode(-1);
let nptr = dummy;
// joining all the pairs back again
ptrArr.forEach(ele => {
nptr.next = ele;
nptr = nptr.next.next;
})
return dummy.next;
}; | Swap Nodes in Pairs |
There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
Input: answers = [10,10,10]
Output: 11
Constraints:
1 <= answers.length <= 1000
0 <= answers[i] < 1000
| class Solution:
def numRabbits(self, answers: List[int]) -> int:
counts = {}
count = 0
for answer in answers:
if answer == 0:
# This must be the only rabbit of its color.
count += 1
elif answer not in counts or counts[answer] == 0:
# This is the first time the color appears.
counts[answer] = 1
# Add all rabbits having this new color.
count += answer + 1
else:
# Add one to how many times answer occurred.
counts[answer] += 1
if counts[answer] > answer:
# If n+1 rabbits have said n,
# this color group is complete.
counts[answer] = 0
return count | class Solution {
public int numRabbits(int[] answers) {
HashMap<Integer, Integer> map = new HashMap<>();
int count = 0;
for(int ele : answers) {
if(!map.containsKey(ele+1)) {
map.put(ele+1, 1);
count += ele+1;
}
else if(map.get(ele+1) == ele+1) {
map.put(ele+1, 1);
count += ele+1;
}
else {
int freq = map.get(ele+1);
map.put(ele+1, freq+1);
}
}
return count;
}
} | class Solution {
public:
int numRabbits(vector<int>& answers) {
sort(answers.begin(),answers.end());
int ans = 0;
for(int i=0;i<answers.size();i++){
ans += answers[i]+1;
int num = answers[i];
while(answers[i]==answers[i+1] && num>0 && i+1<answers.size()){
num--;
i++;
}
}
return ans;
}
}; | /**
* @param {number[]} answers
* @return {number}
*/
var numRabbits = function(answers) {
var totalRabbits = 0;
var sumOfLikeAnswers = new Array(1000).fill(0);
for (let i = 0; i < answers.length; i++) {
sumOfLikeAnswers[answers[i]] += 1;
}
for (let i = 0; i < sumOfLikeAnswers.length; i++) {
totalRabbits += Math.ceil(sumOfLikeAnswers[i] / (i+1)) * (i+1);
}
return totalRabbits;
}; | Rabbits in Forest |
You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.
For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.
Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.
Note: The answer should be the minimum product before the modulo operation is done.
Example 1:
Input: p = 1
Output: 1
Explanation: nums = [1].
There is only one element, so the product equals that element.
Example 2:
Input: p = 2
Output: 6
Explanation: nums = [01, 10, 11].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 * 2 * 3 = 6 is already minimized.
Example 3:
Input: p = 3
Output: 1512
Explanation: nums = [001, 010, 011, 100, 101, 110, 111]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is [001, 110, 011, 100, 001, 110, 111].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is [001, 110, 001, 110, 001, 110, 111].
The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.
Constraints:
1 <= p <= 60
| class Solution:
def minNonZeroProduct(self, p: int) -> int:
mod = 10**9+7
return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod | class Solution {
public int mod = 1_000_000_007;
public int minNonZeroProduct(int p) {
if (p == 1) return 1;
long mx = (long)(Math.pow(2, p)) - 1;
long sm = mx - 1;
long n = sm/2;
long sum = rec(sm, n);
return (int)(sum * (mx % mod) % mod);
}
public long rec(long val, long n) {
if (n == 0) return 1;
if (n == 1) return (val % mod);
long newVal = ((val % mod) * (val % mod)) % mod;
if (n % 2 != 0) {
return ((rec(newVal, n/2) % mod) * (val % mod)) % mod;
}
return rec(newVal, n/2) % mod;
}
} | class Solution {
public:
long long myPow(long long base, long long exponent, long long mod) {
if (exponent == 0) return 1;
if (exponent == 1) return base % mod;
long long tmp = myPow(base, exponent/2, mod);
if (exponent % 2 == 0) { // (base ^ exponent/2) * (base ^ exponent/2)
return (tmp * tmp) % mod;
}
else { // (base ^ exponent/2) * (base ^ exponent/2) * base
tmp = tmp * tmp % mod;
base %= mod;
return (tmp * base) % mod;
}
}
int minNonZeroProduct(int p) {
long long range = pow(2, p);
range--;
long long mod = pow(10, 9) + 7;
long long tmp = myPow(range-1, range/2, mod);
return (tmp * (range%mod)) % mod;
}
}; | var minNonZeroProduct = function(p) {
p = BigInt(p);
const MOD = BigInt(1e9 + 7);
const first = ((1n << p) - 1n);
const half = first / 2n;
const second = powMOD(first - 1n, half);
return (first * second) % MOD;
function powMOD(num, exp) {
if (exp === 0n) return 1n;
const tmp = powMOD(num, exp >> 1n);
let res = (tmp * tmp) % MOD;
if (exp % 2n) res = (res * num) % MOD;
return res;
}
}; | Minimum Non-Zero Product of the Array Elements |
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
Example 1:
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
Example 2:
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.
Constraints:
2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
All pairs (fromi, toi) are distinct.
| class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
matrix = [[float('inf')] * n for _ in range(n)]
# initializing the matrix
for u, v, w in edges:
matrix[u][v] = w
matrix[v][u] = w
for u in range(n):
matrix[u][u] = 0
for k in range(n):
for i in range(n):
for j in range(n):
if matrix[i][j] > matrix[i][k] + matrix[k][j]:
matrix[i][j] = matrix[i][k] + matrix[k][j]
# counting reachable cities(neighbor) for every single city
res = [0] * n
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if 0 < matrix[i][j] <= distanceThreshold:
res[j] += 1
return [i for i, x in enumerate(res) if x == min(res)][-1] | class Solution {
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
int[][] graph = new int[n][n];
for(int[] row: graph)
Arrays.fill(row, Integer.MAX_VALUE);
for(int i = 0; i < n; i++)
graph[i][i] = 0;
for(int[] edge: edges)
{
graph[edge[0]][edge[1]] = edge[2];
graph[edge[1]][edge[0]] = edge[2];
}
for(int k = 0; k < n; k++)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(graph[i][k] != Integer.MAX_VALUE && graph[k][j] != Integer.MAX_VALUE)
{
if(graph[i][k] + graph[k][j] < graph[i][j])
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}
int ans = 0;
int city = Integer.MAX_VALUE;;
for(int i = 0; i < n; i++)
{
int current = 0;
for(int j = 0; j < n; j++)
{
if(i != j && graph[i][j] <= distanceThreshold)
current++;
}
if(current <= city)
{
ans = i;
city = current;
}
}
return ans;
}
} | class Solution {
public:
unordered_map<int,int>m;
int findTheCity(int n, vector<vector<int>>& edges, int threshold) {
vector<vector<pair<int,int>>>adj(n);
for(auto x:edges)
{
adj[x[0]].push_back({x[1],x[2]});
adj[x[1]].push_back({x[0],x[2]});
}
int ind=-1,ans=1e8;
for(int i=0;i<n;i++)
{
queue<pair<int,int>>q;
q.push({i,0});
vector<int>dis(n,1e8);
dis[i]=0;
while(!q.empty())
{
int node=q.front().first;
int wt=q.front().second;
q.pop();
for(auto x:adj[node])
{
int node1=x.first;
int wt1=x.second;
if(wt+wt1<dis[node1])
{
dis[node1]=wt+wt1;
q.push({node1,wt+wt1});
}
}
}
int c=0;
for(int i=0;i<dis.size();i++)
{
if(dis[i]<=threshold)
{
c++;
}
}
if(c<=ans)
{
ans=c;
ind=max(ind,i);
}
}
return ind;
}
}; | var findTheCity = function(n, edges, distanceThreshold) {
const dp = Array.from({length: n}, (_, i) => {
return Array.from({length: n}, (_, j) => i == j ? 0 : Infinity)
});
for(let edge of edges) {
const [a, b, w] = edge;
dp[a][b] = dp[b][a] = w;
}
// k is intermediate node
for(let k = 0; k < n; k++) {
// fix distances from i to other nodes with k as intermediate
for(let i = 0; i < n; i++) {
if(i == k || dp[i][k] == Infinity) continue;
for(let j = i + 1; j < n; j++) {
dp[i][j] = dp[j][i] = Math.min(dp[i][j], dp[i][k] + dp[k][j]);
}
}
};
let city = -1, minCity = n;
for(let i = 0; i < n; i++) {
let count = 0;
for(let j = 0; j < n; j++) {
if(i == j) continue;
if(dp[i][j] <= distanceThreshold) count++;
}
if(count <= minCity) {
minCity = count;
city = i;
}
}
return city;
}; | Find the City With the Smallest Number of Neighbors at a Threshold Distance |
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.
Return the number of good triplets.
Example 1:
Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
Example 2:
Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.
Constraints:
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
| class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
count = 0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
for k in range(j+1,len(arr)):
if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k]-arr[i])<=c:
count+=1
return count | class Solution {
public int countGoodTriplets(int[] arr, int a, int b, int c) {
int total = 0;
for (int i = 0; i < arr.length - 2; i++){
for (int j = i+1; j < arr.length - 1; j++){
for (int k = j+1; k < arr.length; k++){
if (helper(arr[i], arr[j]) <= a &&
helper(arr[j], arr[k]) <= b &&
helper(arr[k], arr[i]) <= c)
total++;
}
}
}
return total;
}
private static int helper(int x, int y) {
return Math.abs(x - y);
}
} | class Solution {
public:
int countGoodTriplets(vector<int>& arr, int a, int b, int c) {
int ct = 0;
for(int i = 0; i<arr.size()-2; i++)
{
for(int j = i+1; j<arr.size()-1; j++)
{
if(abs(arr[i]-arr[j])<=a)
for(int k = j+1; k<arr.size(); k++)
{
if(abs(arr[j]-arr[k])<=b && abs(arr[i]-arr[k])<=c)
ct++;
}
}
}
return ct;
}
}; | var countGoodTriplets = function(arr, a, b, c) {
let triplets = 0;
for (let i = 0; i < arr.length - 2; i++) {
for (let j = i + 1; j < arr.length - 1; j++) {
if (Math.abs(arr[i] - arr[j]) > a) continue;
for (let k = j + 1; k < arr.length; k++) {
if (Math.abs(arr[j] - arr[k]) > b || Math.abs(arr[i] - arr[k]) > c) {
continue;
}
triplets++;
}
}
}
return triplets;
}; | Count Good Triplets |
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
It can jump exactly a positions forward (to the right).
It can jump exactly b positions backward (to the left).
It cannot jump backward twice in a row.
It cannot jump to any forbidden positions.
The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
Example 1:
Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
Output: 3
Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.
Example 2:
Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
Output: -1
Example 3:
Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
Output: 2
Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.
Constraints:
1 <= forbidden.length <= 1000
1 <= a, b, forbidden[i] <= 2000
0 <= x <= 2000
All the elements in forbidden are distinct.
Position x is not forbidden.
| class Solution:
def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int:
fb = set(fb)
q = deque([[0,0,True]])
while(q):
n,l,isf = q.popleft()
if(n<0 or n in fb or n>2000+2*b):
continue
fb.add(n)
if(n==x):
return l
if isf and n-b>0:
q.append([n-b,l+1,False])
q.append([n+a,l+1,True])
return -1 | class Solution {
public int minimumJumps(int[] forbidden, int a, int b, int x) {
// Visited Set
Set<Integer> visited = new HashSet<Integer>();
// Add forbidden coordinates to visited
for (int i = 0; i < forbidden.length; i++) {
visited.add(forbidden[i]);
}
// Distance/ Jumps map
Map<Integer, Integer> jumps = new HashMap<>();
jumps.put(0, 0);
// BFS Queue
Queue<Integer[]> q = new LinkedList<>();
q.add(new Integer[] {0, 1});
// BFS
while (q.size() != 0) {
Integer[] ud = q.poll();
int u = ud[0], d = ud[1];
// x found
if (u == x) {
return jumps.get(u);
}
// jump right
if (u + a < 6001 && !visited.contains(u+a)) {
q.add(new Integer[] {u+a, 1});
visited.add(u+a);
jumps.put(u+a, jumps.get(u) + 1);
}
// jump left
if (d != -1 && u - b > -1 && !visited.contains(u-b)) {
q.add(new Integer[] {u-b, -1});
jumps.put(u-b, jumps.get(u) + 1);
}
}
return -1;
}
} | class Solution
{
public:
typedef pair<int, bool> pi;
int minimumJumps(vector<int> &forbidden, int a, int b, int x)
{
set<int> st(forbidden.begin(), forbidden.end());
vector<vector<int>> vis(2, vector<int>(10000, 0));
vis[0][0] = 1;
vis[1][0] = 1;
queue<pi> q;
q.push({0, true});
int ans = 0;
while (!q.empty())
{
int n = q.size();
for (int i = 0; i < n; i++)
{
int curr = q.front().first;
bool canJumpBackward = q.front().second;
q.pop();
if (curr == x)
return ans;
int p1 = curr + a;
int p2 = curr - b;
if (p1 < 10000 && vis[0][p1] == 0 && st.find(p1) == st.end())
{
q.push({p1, true});
vis[0][p1] = 1;
}
if (p2 >= 0 && vis[1][p2] == 0 && st.find(p2) == st.end() && canJumpBackward == true)
{
q.push({p2, false});
vis[1][p2] = 1;
}
}
ans++;
}
return -1;
}
}; | var minimumJumps = function(forbidden, a, b, x) {
let f = new Set(forbidden);
let m = 2000 + 2 * b;
let memo = {};
let visited = new Set();
let res = dfs(0, true);
return res === Infinity ? -1 : res;
function dfs(i,canJumpBack) {
if (i === x) return 0;
let key = `${i},${canJumpBack}`;
visited.add(i);
if (memo[key] !== undefined) return memo[key];
if (i > m || i < 0) return Infinity;
let min = Infinity;
if (canJumpBack && !f.has(i - b) && !visited.has(i-b)) {
min = Math.min(min, 1 + dfs(i - b, false));
}
if (!f.has(i + a) && !visited.has(i+a)) {
min = Math.min(min, 1 + dfs(i + a, true));
}
visited.delete(i);
return memo[key] = min;
}
}; | Minimum Jumps to Reach Home |
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.
Let incident(a, b) be defined as the number of edges that are connected to either node a or b.
The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:
a < b
incident(a, b) > queries[j]
Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.
Note that there can be multiple edges between the same two nodes.
Example 1:
Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]
Output: [6,5]
Explanation: The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
Example 2:
Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]
Output: [10,10,9,8,6]
Constraints:
2 <= n <= 2 * 104
1 <= edges.length <= 105
1 <= ui, vi <= n
ui != vi
1 <= queries.length <= 20
0 <= queries[j] < edges.length
| class Solution:
def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
p_c = [0] * (n+1) # point counter
e_c = defaultdict(int) # edge counter
for a,b in edges:
p_c[a] += 1
p_c[b] += 1
if a<b:
e_c[(a,b)] += 1
else:
e_c[(b,a)] += 1
f_c = defaultdict(int) # frequency of point counter (compress the individual calculations into massive one)
for i in range(1, n+1):
f_c[p_c[i]] += 1
cnt_amt = defaultdict(int) # frequency of same cnt on pairs without edge adjustment
f_key = list(f_c.keys()) # frequency key
l_f = len(f_key)
for i in range(l_f):
f1 = f_key[i]
cnt_amt[f1*2] += f_c[f1] * (f_c[f1]-1) // 2 # 3 points with 4, then you get 8
# for a frequency of 3 * (3-2) // 2 = 3
for j in range(i+1, l_f):
f2 = f_key[j]
cnt_amt[f1+f2] += f_c[f1] * f_c[f2] # 2 points with 2, 3 points with 4
# will have 6 with frequency of 2 * 3 = 6
for (u,v), z in e_c.items(): # edge adjustment
s = p_c[u] + p_c[v]
t = s - z
cnt_amt[s] -= 1
cnt_amt[t] += 1
cnt_keys = sorted(cnt_amt.keys(), key=lambda x: -x) # accumulate the frequency by descending order
res = defaultdict(int)
tmp = 0
for key in cnt_keys:
if cnt_amt[key]: # if it is 0 then dont bother to keep them
tmp += cnt_amt[key]
res[key] = tmp
res_keys = sorted(res.keys()) # bisection search
for i, q in enumerate(queries):
local = bisect.bisect(res_keys, q)
try:
queries[i] = res[res_keys[local]]
except:
queries[i] = 0 # some test cases are annoying by requesting an unreasonable large number
return queries | class Solution {
public int[] countPairs(int n, int[][] edges, int[] queries) {
Map<Integer, Map<Integer, Integer>> dupMap = new HashMap<>();
Map<Integer, Set<Integer>> map = new HashMap<>();
int[] ans = new int[queries.length];
int[] count = new int[n];
for (int[] e : edges){
int min = Math.min(e[0]-1, e[1]-1);
int max = Math.max(e[0]-1, e[1]-1);
dupMap.computeIfAbsent(min, o -> new HashMap<>()).merge(max, 1, Integer::sum);
map.computeIfAbsent(min, o -> new HashSet<>()).add(max);
count[min]++;
count[max]++;
}
Integer[] indexes = IntStream.range(0, n).boxed().toArray(Integer[]::new);
Arrays.sort(indexes, Comparator.comparingInt(o -> count[o]));
for (int j = 0, hi = n; j < queries.length; j++, hi = n){
for (int i = 0; i < n; i++){
while(hi>i+1&&count[indexes[i]]+count[indexes[hi-1]]>queries[j]){
hi--;
}
if (hi==i){
hi++;
}
ans[j]+=n-hi;
for (int adj : map.getOrDefault(indexes[i], Set.of())){
int ttl = count[indexes[i]] + count[adj];
if (ttl > queries[j] && ttl-dupMap.get(indexes[i]).get(adj) <= queries[j]){
ans[j]--;
}
}
}
}
return ans;
}
} | class Solution {
vector<int> st;
public:
void update(int tind,int tl,int tr,int ind,int val){
if(tl>tr)
return;
if(tl==tr){
st[tind]+=val;
return;
}
int tm=tl+((tr-tl)>>1),left=tind<<1;
if(ind<=tm)
update(left,tl,tm,ind,val);
else
update(left|1,tm+1,tr,ind,val);
st[tind]=st[left]+st[left|1];
}
int query(int tind,int tl,int tr,int ql,int qr){
if(tl>tr or qr<tl or ql>tr)
return 0;
if(ql<=tl and tr<=qr)
return st[tind];
int tm=tl+((tr-tl)>>1),left=tind<<1;
return query(left,tl,tm,ql,qr)+query(left|1,tm+1,tr,ql,qr);
}
vector<int> countPairs(int n,vector<vector<int>>& a,vector<int>& q) {
vector<int> f(n+2,0);
vector<unordered_map<int,int>> mp(n+2); // using a normal map gives TLE
for(auto v:a){
int mx=max(v[0],v[1]),mn=min(v[1],v[0]);
f[mx]++;
f[mn]++;
mp[mx][mn]++;
}
vector<int> ans(q.size(),0);
int m=a.size();
st.resize(4*m+40,0);
for(int i=n;i;i--){
// reducing the common edges between current node and its adjacent
for(auto e:mp[i]){
update(1,0,m,f[e.first],-1);
update(1,0,m,f[e.first]-e.second,1);
}
int curr=f[i];
for(int j=0;j<q.size();j++)
ans[j]+=query(1,0,m,max(0,q[j]-curr+1),m);
// reversing the changes made initially
for(auto e:mp[i]){
update(1,0,m,f[e.first],1);
update(1,0,m,f[e.first]-e.second,-1);
}
update(1,0,m,f[i],1);
}
return ans;
}
}; | var countPairs = function(n, edges, queries) {
const degree = Array(n+1).fill(0)
const edgesMap = new Map()
const countMemo = new Map()
const answer = []
for(let [u, v] of edges) {
degree[u]++
degree[v]++
const key = `${Math.min(u, v)}-${Math.max(u, v)}`;
edgesMap.set(key, (edgesMap.get(key) || 0) + 1);
}
const sortedDegree = [...degree.slice(1)].sort((a, b) => a - b);
for(let num of queries) {
let cnt;
if(countMemo.has(num)) cnt = countMemo.get(num)
else {
cnt = calculateCount(num)
countMemo.set(num, cnt);
}
answer.push(cnt)
}
function calculateCount(num) {
let low = 0, high = sortedDegree.length-1, cnt = 0;
while(low < high) {
const sum = sortedDegree[low] + sortedDegree[high];
if(sum > num) {
cnt += (high - low);
high--;
} else low++;
}
for(let [key, val] of edgesMap) {
const [u, v] = key.split('-').map(Number);
if(degree[u] + degree[v] > num) {
const newSum = degree[u] + degree[v] - val
if(newSum <= num) cnt--;
}
}
return cnt;
}
return answer;
}; | Count Pairs Of Nodes |
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend will sit on.
Example 1:
Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1
Explanation:
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
Example 2:
Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
Output: 2
Explanation:
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
Constraints:
n == times.length
2 <= n <= 104
times[i].length == 2
1 <= arrivali < leavingi <= 105
0 <= targetFriend <= n - 1
Each arrivali time is distinct.
| class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
arrivals = []
departures = []
for ind, (x, y) in enumerate(times):
heappush(arrivals, (x, ind))
heappush(departures, (y, ind))
d = {}
occupied = [0] * len(times)
while True:
if arrivals and departures and arrivals[0][0] < departures[0][0]:
_, ind = heappop(arrivals)
d[ind] = occupied.index(0)
occupied[d[ind]] = 1
if ind == targetFriend:
return d[ind]
elif arrivals and departures and arrivals[0][0] >= departures[0][0]:
_, ind = heappop(departures)
occupied[d[ind]] = 0 | class Solution {
public int smallestChair(int[][] times, int targetFriend) {
int targetStart = times[targetFriend][0];
Arrays.sort(times, (a, b) -> a[0] - b[0]);
PriorityQueue<Integer> available = new PriorityQueue<>();
for (int i = 0; i < times.length; ++ i) {
available.offer(i);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < times.length; ++ i) {
while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) {
available.offer(pq.poll()[1]);
}
if (times[i][0] == targetStart) {
break;
}
pq.offer(new int[]{times[i][1], available.poll()});
}
return available.peek();
}
} | class Solution {
public:
int smallestChair(vector<vector<int>>& times, int targetFriend) {
int n = times.size();
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > busy; //departure time as first , index as second
priority_queue<int, vector<int>, greater<int>> free; //min heap of chair index that are unoccupied
//store friend indexes so that they don't get lost after sorting
for(int i=0;i<n;++i){
times[i].push_back(i);
}
//Sort according to arrival time
sort(times.begin(),times.end());
int new_chair = 0; //chairs alloted till now
for(int i=0;i<n;++i){
int arrival = times[i][0]; //pop chairs before arrival
int leave_time = times[i][1];
int fr = times[i][2]; //friend index
//free chairs accordingly
while(!busy.empty() && busy.top().first <= arrival){
// cout << "Chair free " << busy.top().second << endl;
free.push(busy.top().second);
busy.pop();
}
//No free chair allot new chair
if(free.empty()){
// cout << "Alloting new_chair " << new_chair << "to" << fr << endl;
if(fr == targetFriend) return new_chair;
busy.push({leave_time,new_chair});
new_chair++;
}
else{
int x = free.top();
// cout << "giving chair " << x << "to" << fr << endl;
free.pop();
if( fr == targetFriend) return x;
busy.push({leave_time,x});
}
}
return -1;
}
}; | /**
* @param {number[][]} times
* @param {number} targetFriend
* @return {number}
*/
var smallestChair = function(times, targetFriend) {
const [targetArrival] = times[targetFriend]; // we need only arrival time
const arrivalQueue = times;
const leavingQueue = [...times];
arrivalQueue.sort((a, b) => a[0] - b[0]); // sort by arrival time
leavingQueue.sort((a, b) => (a[1] - b[1]) || (a[0] - b[0])); // sort by leaving time and if they are equal by arrival
const chairsByLeaveTime = new Map(); // key - arrival time, value - chair index
let chairsCount = 0;
let arriving = 0, leaving = 0; // two pointers for keeping track of available chairs
while (arriving < arrivalQueue.length) {
let chairIdx;
const arrival = arrivalQueue[arriving][0];
const leave = leavingQueue[leaving][1];
if (arrival < leave) {
chairIdx = chairsCount++; // if no one is leaving, take a new chair
} else {
let freeChairIdx = leaving;
chairIdx = chairsByLeaveTime.get(leavingQueue[freeChairIdx++][0]); // when arriaval time is less then or equal to the next leaving friend we can take her chair
while (arrival >= leavingQueue[freeChairIdx][1]) { // to avoid situation when a few friends left already and the next chair in leaving queue is not the smallest
const nextChair = chairsByLeaveTime.get(leavingQueue[freeChairIdx][0]);
if (chairIdx > nextChair) {
[leavingQueue[leaving], leavingQueue[freeChairIdx]] = [leavingQueue[freeChairIdx], leavingQueue[leaving]]; // swap the front of the queue with the smallest chair owner
chairIdx = nextChair;
}
++freeChairIdx;
}
++leaving;
}
if (targetArrival === arrival) { // we found the target, no need to continue
return chairIdx;
}
chairsByLeaveTime.set(arrival, chairIdx); // as far as arrival time is distinct, we can use it as a key
arriving++;
}
}; | The Number of the Smallest Unoccupied Chair |
You are given two strings current and correct representing two 24-hour times.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.
Return the minimum number of operations needed to convert current to correct.
Example 1:
Input: current = "02:30", correct = "04:35"
Output: 3
Explanation:
We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes "03:30".
- Add 60 minutes to current. current becomes "04:30".
- Add 5 minutes to current. current becomes "04:35".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.
Example 2:
Input: current = "11:00", correct = "11:01"
Output: 1
Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1.
Constraints:
current and correct are in the format "HH:MM"
current <= correct
| class Solution:
def HHMMToMinutes(self, s: str) -> int:
return int(s[0:2])*60 + int(s[3:5])
def convertTime(self, current: str, correct: str) -> int:
diff = self.HHMMToMinutes(correct) - self.HHMMToMinutes(current)
order = [60,15,5,1]
ops = 0
for i in range(0,4):
ops+=int(diff/order[i])
diff%=order[i]
return ops | class Solution {
public int HHMMToMinutes(String s){
return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;
}
public int convertTime(String current, String correct) {
int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);
int[] order = {60,15,5,1};
int i = 0;
int ops = 0;
while(i < 4){
ops+=(diff/order[i]);
diff%=order[i];
i++;
}
return ops;
}
} | class Solution {
public:
int HHMMToMinutes(string s){
return stoi(s.substr(0,2))*60 + stoi(s.substr(3,2));
}
int convertTime(string current, string correct) {
int diff = - HHMMToMinutes(current) + HHMMToMinutes(correct);
vector<int> order = {60,15,5,1};
int i = 0;
int ans = 0;
while(i < 4){
ans+=(diff/order[i]);
diff%=order[i];
i++;
}
return ans;
}
}; | var getTime = function(time){
var [hrs,mins] = time.split(":");
return parseInt(hrs)*60 + parseInt(mins);
}
var convertTime = function(current, correct) {
var diff = getTime(correct) - getTime(current);
var order = [60,15,5,1];
var ops = 0;
order.forEach(val =>{
ops+=Math.floor((diff/val));
diff%=val;
})
return ops;
}; | Minimum Number of Operations to Convert Time |
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 2:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109
| class Solution:
def minimumOneBitOperations(self, n: int) -> int:
if n <= 1:
return n
def leftmostbit(x):
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
x += 1
x >>= 1
return x
x = leftmostbit(n)
return ((x << 1) - 1) - self.minimumOneBitOperations(n - x) | class Solution {
public int minimumOneBitOperations(int n) {
int inv = 0;
// xor until n becomes zero
for ( ; n != 0 ; n = n >> 1){
inv ^= n;
System.out.println(inv+" "+n);
}
return inv;
}
} | class Solution {
public:
int minimumOneBitOperations(int n) {
int output = 0;
while( n> 0)
{
output ^= n;
n = n >> 1;
}
return output;
}
}; | /**
* @param {number} n
* @return {number}
*/
var minimumOneBitOperations = function(n) {
let answer = 0;
let op = 1;
let bits = 30;
while(bits >= 0) {
if(n & (1 << bits)) {
let tmp = (1 << (bits + 1)) - 1;
answer += tmp * op;
op *= -1;
}
bits--;
}
return answer;
} | Minimum One Bit Operations to Make Integers Zero |
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.
| seen=set()
def dfs(i,j,m,n,grid):
global seen
if (i<0 or i>=m or j<0 or j>=n):return
if (i,j) in seen:return
seen.add((i,j))
if grid[i][j]=="1":
dfs(i,j+1,m,n,grid)
dfs(i,j-1,m,n,grid)
dfs(i+1,j,m,n,grid)
dfs(i-1,j,m,n,grid)
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
global seen
m=len(grid) #no of rows
n=len(grid[0]) #no of columns
count=0
for i in range(m):
for j in range(n):
if (i,j) not in seen and grid[i][j]=="1":
dfs(i,j,m,n,grid)
count+=1
seen.clear()
return count | class Solution {
public int numIslands(char[][] grid) {
int count = 0;
int r = grid.length;
int c = grid[0].length;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(grid[i][j]=='1'){
dfs(grid,i,j);
count++;
}
}
}
return count;
}
public void dfs(char[][] grid,int i,int j){
if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j]=='0'){
return;
}
grid[i][j] = '0';
dfs(grid,i,j+1);
dfs(grid,i,j-1);
dfs(grid,i+1,j);
dfs(grid,i-1,j);
}
} | class Solution {
public:
void calculate(vector<vector<char>>& grid, int i, int j)
{
if(i>=grid.size() || j>=grid[i].size() || i<0 || j<0)
return;
if(grid[i][j]=='0')
return;
grid[i][j] = '0';
calculate(grid,i,j-1);
calculate(grid,i-1,j);
calculate(grid,i,j+1);
calculate(grid,i+1,j);
}
int numIslands(vector<vector<char>>& grid) {
int ans = 0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]=='0')
continue;
else if (grid[i][j]=='1')
{
ans++;
calculate(grid,i,j);
}
}
}
return ans;
}
}; | /**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
let islandCount = 0
for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) {
for (let colIndex = 0; colIndex < grid[0].length; colIndex++) {
const node = grid[rowIndex][colIndex]
// Don't bother with water
if (node === "0") continue
// Once we encounter land, try to get all
// the connected land from the current land.
// Once we get all the land connected from
// the current land, mark them as water so
// that it would disregarded by the main loop.
islandCount++
const connectedLandStack = [[rowIndex, colIndex]]
while(connectedLandStack.length > 0) {
const [row, col] = connectedLandStack.pop()
// change the land to water
grid[row][col] = "0"
for (const direction of directions) {
// To get all the connected land we need to check
// all directions (left, right, top, bottom)
const newNode = [row + direction[0], col + direction[1]]
const newNodeValue = grid[newNode[0]]?.[newNode[1]]
// We only care about the connected lands
if (newNodeValue === undefined || newNodeValue === "0") {
continue
}
connectedLandStack.push(newNode)
}
}
}
}
return islandCount
}; | Number of Islands |
Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for bββββββ to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Example 2:
Input: a = "a", b = "aa"
Output: 2
Constraints:
1 <= a.length, b.length <= 104
a and b consist of lowercase English letters.
| class Solution:
def repeatedStringMatch(self, a: str, b: str) -> int:
res=""
count=0
while len(res)<len(b)+len(a):
count+=1
res=a*count
if b in res:
return count
return -1 | class Solution {
public int repeatedStringMatch(String a, String b) {
String copyA = a;
int count =1;
int repeat = b.length()/a.length();
for(int i=0;i<repeat+2;i++){
if(a.contains(b)){
return count;
}
else{
a+=copyA;
count++;
}
}
return -1;
}
} | class Solution {
public:
int repeatedStringMatch(string a, string b) {
int m=a.size(); int n=b.size();
vector<int>d; int mod=n%m; int h=n/m;
if(mod==0)
{d.push_back(h); d.push_back(h+1); }
else
{ d.push_back(h+1); d.push_back(h+2); }
string s=""; string t="";
for(int i=0;i<d[0];i++)
{s+=a;}
for(int i=0;i<d[1];i++)
{t+=a;}
int i=0; int y1=s.size()-n; int y2=t.size()-n;
while(i<=y1)
{
string x=s.substr(i,n); //cout<<x;
if(x==b){return d[0]; break;}
i++;
}
i=0;
while(i<=y2)
{
string x=t.substr(i,n); //cout<<"ok1"<<x;
if(x==b){return d[1]; break;}
i++;
}
return -1;
}
}; | var repeatedStringMatch = function(a, b) {
const initRepeatTimes = Math.ceil(b.length / a.length);
const isMatch = (times) => a.repeat(times).includes(b);
if (isMatch(initRepeatTimes)) return initRepeatTimes;
if (isMatch(initRepeatTimes + 1)) return initRepeatTimes + 1;
return -1;
}; | Repeated String Match |
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 100].
0 <= Node.val < 100
| # 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 isUnivalTree(self, root: Optional[TreeNode]) -> bool:
val1 = root.val
self.tracker = False
def dfs(root,val1):
if not root:
return
if root.val!=val1:
self.tracker=True
dfs(root.left,val1)
dfs(root.right,val1)
return
dfs(root,val1)
if self.tracker == False:
return True
return False | class Solution {
boolean ans=true;
int firstVal=0;
public boolean isUnivalTree(TreeNode root) {
if(root==null)
return ans;
firstVal=root.val;
traversal(root);
return ans;
}
private void traversal(TreeNode root)
{
if(root==null)
return;
if(root.val!=firstVal)
ans=false;
traversal(root.left);
traversal(root.right);
}
} | class Solution {
public:
bool recur(TreeNode* root, int value){
if(root==NULL)
return true;
if(root->val!=value){
return false;
}
return recur(root->left,value) &&recur(root->right,value);
}
bool isUnivalTree(TreeNode* root) {
if(root==NULL)
return true;
int value=root->val;
return recur(root,value);
}
}; | var isUnivalTree = function(root) {
if (!root) {
return false;
}
const prev = root.val;
const nodes = [root];
for (const node of nodes) {
if (node.val !== prev) {
return false;
}
if (node.left) {
nodes.push(node.left);
}
if (node.right) {
nodes.push(node.right);
}
}
return true;
};
``` | Univalued Binary Tree |
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.
Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Example 1:
Input: nums = [0,4], k = 5
Output: 20
Explanation: Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
Example 2:
Input: nums = [6,3,3,2], k = 2
Output: 216
Explanation: Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
Constraints:
1 <= nums.length, k <= 105
0 <= nums[i] <= 106
| import heapq
class Solution:
def maximumProduct(self, nums, k: int) -> int:
# creating a heap
heap = []
for i in nums:
heapq.heappush (heap,i)
# basic idea here is keep on incrementing smallest number, then only multiplication of that number will be greater
# so basically till I have operations left I will increment my smallest number
while k :
current = heapq.heappop(heap)
heapq.heappush(heap, current+1)
k-=1
result =1
# Just Multiply all the numbers in heap and return the value
while len(heap)>0:
x= heapq.heappop(heap)
result =(result*x )% (10**9+7)
return result | class Solution {
public int maximumProduct(int[] nums, int k) {
Queue<Integer> pq = new PriorityQueue<>();
for (int num : nums) pq.add(num);
while (k-->0) {
int top = pq.poll() + 1 ;
pq.add(top);
}
long res = 1;
while (!pq.isEmpty()) {
res = (res*pq.poll()) % 1000000007;
}
return (int)(res);
}
} | class Solution {
public:
int maximumProduct(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
while(k--) {
int mini = pq.top();
pq.pop();
pq.push(mini + 1);
}
long long ans = 1, mod = 1e9+7;
while(!pq.empty()) {
ans = ((ans % mod) * (pq.top() % mod)) % mod;
pq.pop();
}
return (int)ans;
}
}; | var maximumProduct = function(nums, k) {
let MOD = Math.pow(10, 9) + 7;
// build a new minimum priority queue
// LeetCode loads MinPriorityQueue by default, no need to implement again
let queue = new MinPriorityQueue();
for (let i = 0; i < nums.length; i++) {
queue.enqueue(nums[i], nums[i]);
}
// To maximize the product, take the smallest element out
// add 1 to it and add it back to the queue
let count = 0;
while (count < k && queue.size() > 0) {
let {element, priority} = queue.dequeue();
queue.enqueue(element + 1, priority + 1);
count += 1;
}
// calculate the product
let result = 1;
let elements = queue.toArray().map((a) => a.element);
for (let i = 0; i < elements.length; i++) {
result = (result * elements[i]) % MOD;
}
return result;
}; | Maximum Product After K Increments |
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.
You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.
Return the maximum number of times pattern can occur as a subsequence of the modified text.
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.
Example 1:
Input: text = "abdcdbc", pattern = "ac"
Output: 4
Explanation:
If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.
Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc".
However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal.
It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character.
Example 2:
Input: text = "aabb", pattern = "ab"
Output: 6
Explanation:
Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb".
Constraints:
1 <= text.length <= 105
pattern.length == 2
text and pattern consist only of lowercase English letters.
| class Solution:
def maximumSubsequenceCount(self, text: str, pattern: str) -> int:
total = count_a = count_b = 0
for c in text:
if c == pattern[1]:
total += count_a
count_b += 1
if c == pattern[0]:
count_a += 1
return total + max(count_a, count_b) | class Solution {
public long maximumSubsequenceCount(String text, String pattern) {
//when pattern[0] == pattern[1]
if (pattern.charAt(0) == pattern.charAt(1)) {
long freq = 1;
//O(N)
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == pattern.charAt(0)) {
freq++;
}
}
//number of subsequences : choose any two characters from freq nC2
return (freq * (freq - 1)) / 2;
}
//choice 1
String text1 = pattern.charAt(0) + text;
int freq = 0;
long count1 = 0;
//O(N)
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == pattern.charAt(0)) {
freq++;
} else if (text1.charAt(i) == pattern.charAt(1)) {
count1 += freq;
}
}
//choice 2
String text2 = text + pattern.charAt(1);
freq = 0;
long count2 = 0;
//O(N)
for (int i = text2.length() - 1; i>= 0; i--) {
if (text2.charAt(i) == pattern.charAt(1)) {
freq++;
} else if (text2.charAt(i) == pattern.charAt(0)) {
count2 += freq;
}
}
return Math.max(count1, count2);
}
} | class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
// support variables
int len = text.size();
long long res = 0, aCount = 0, bCount = 0;
char a = pattern[0], b = pattern[1];
// getting the frequencies
for (char c: text) {
if (c == a) aCount++;
else if (c == b) bCount++;
}
// edge case: a == b
if (a == b) return aCount++ * aCount / 2;
// adding our extra character to maximise the occurrences
if (aCount < bCount) res += bCount;
else bCount++;
// computing the occurrences
for (char c: text) {
// first case: spotting the first element of a sequence
if (c == a) {
res += bCount;
}
// second case: we found an ending sequence
else if (c == b) bCount--;
// all the rest: we do nothing
}
return res;
}
}; | /**
* @param {string} text
* @param {string} pattern
* @return {number}
*/
var maximumSubsequenceCount = function(text, pattern) {
const arrText = text.split("")
const lengthP0 = arrText.filter(x => x === pattern[0]).length
const lengthP1 = arrText.filter(x => x === pattern[1]).length
const [c1, c2, lengthmax] = lengthP0 <= lengthP1 ? [...pattern, lengthP1]: [pattern[1], pattern[0], lengthP0]
let newText = lengthP0 <= lengthP1 ? [c1,...arrText]: [...arrText, c1]
newText = lengthP0 <= lengthP1 ? newText : newText.reverse()
let i = 0;
let count = 0;
let countmax = lengthmax
while(i < newText.length) {
if(newText[i] === c1) {
count += countmax
}
if(newText[i] === c2) {
countmax--
}
i++;
}
return count
}; | Maximize Number of Subsequences in a String |
You are given an integer n.
Each number from 1 to n is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
Example 1:
Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].
There are 4 groups with largest size.
Example 2:
Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.
Constraints:
1 <= n <= 104
| def compute(num):
if num < 10:
return num
newVal = 0
while num > 0:
last = num % 10
newVal += last
num /= 10
return newVal
class Solution(object):
def countLargestGroup(self, n):
"""
:type n: int
:rtype: int
"""
myMap = {}
for i in range(1, n + 1):
val = compute(i)
if val in myMap.keys():
myMap.get(val).append(i)
else:
myMap[val] = [i]
maxLen = 0
for n in myMap.values():
maxLen = max(maxLen, len(n))
ans = 0
for n in myMap.values():
if len(n) == maxLen:
ans += 1
return ans | class Solution {
public int countLargestGroup(int n) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=1;i<=n;i++){
int x=sum(i);
map.put(x,map.getOrDefault(x,0)+1);
}
int max=Collections.max(map.values());
int c=0;
for(int i:map.values()){
if(i==max) c++;
}
return c;
}
public int sum(int g){
int summ=0;
while(g!=0){
int rem=g%10;
summ+=rem;
g/=10;
}
return summ;
}
}``` | class Solution {
public:
int cal(int n){
int sum = 0;
while(n > 0){
sum += n%10;
n /= 10;
}
return sum;
}
int countLargestGroup(int n) {
int a[40];
for(int i=0; i<40; i++) a[i] = 0;
for(int i=1; i<=n; i++){
a[cal(i)]++;
}
int max = 0;
int count = 0;
for(int i=0; i<40; i++){
if(a[i] > max){
count = 1;
max = a[i];
}
else if(a[i] == max) count++;
}
return count;
}
}; | var countLargestGroup = function(n) {
const hash = {};
for (let i = 1; i <= n; i++) {
const sum = i.toString().split('').reduce((r, x) => r + parseInt(x), 0);
if (!hash[sum]) {
hash[sum] = 0;
}
hash[sum]++;
}
return Object.keys(hash)
.sort((a, b) => hash[b] - hash[a])
.reduce((res, x) => {
const prev = res[res.length - 1];
if (!prev || prev === hash[x]) {
res.push(hash[x]);
}
return res;
}, []).length;
}; | Count Largest Group |
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In each move, starting from square curr, do the following:
Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].
This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.
The game ends when you reach the square n2.
A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.
For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.
Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.
Example 1:
Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
Output: 4
Explanation:
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
Example 2:
Input: board = [[-1,-1],[-1,3]]
Output: 1
Constraints:
n == board.length == board[i].length
2 <= n <= 20
grid[i][j] is either -1 or in the range [1, n2].
The squares labeled 1 and n2 do not have any ladders or snakes.
| class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# creating a borad map to loop-up the square value
board_map = {}
i = 1
b_rev = board[::-1]
for d, r in enumerate(b_rev):
# reverse for even rows - here d is taken as direction
if d%2 != 0: r = r[::-1]
for s in r:
board_map[i] = s
i += 1
# BFS Algorithm
q = [(1, 0)] # (curr, moves)
v = set()
goal = len(board) * len(board) # end square
while q:
curr, moves = q.pop(0)
# win situation
if curr == goal: return moves
# BFS on next 6 places (rolling a die)
for i in range(1, 7):
# skip square outside board
if curr+i > goal: continue
# get value from mapping
next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i]
if next_pos not in v:
v.add(next_pos)
q.append((next_pos, moves+1))
return -1
| class Solution {
//what if we have changed the dice number, or changing the starting index or changing the ending index
//so i have covered all possible ways in which this question can be asked
//bfs tip:- for better bfs, we can use marking first and then inserting it in the queue which works faster then removing first and then checking
public int [] getans(int dice,HashMap<Integer,Integer> map,int si,int ei){
//if si==ei just directly return
if(si==ei) return new int [] {0,0,0};
LinkedList<int[]> que = new LinkedList<>();
que.addLast(new int[] {si,0,0});
int level = 0;
//to stop visiting cells again
boolean [] vis = new boolean [ei+1];
vis[si]=true;
//starting bfs
while(que.size()!=0){
int size=que.size();
while(size-->0){
int [] rem = que.removeFirst();
int idx= rem[0];
int lad = rem[1];
int sna = rem[2];
for(int i=1;i<=dice;i++){
int x =i+rem[0]; //checking all the steps
if(x<=ei){ //valid points
if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder
if(map.containsKey(x)){
int val = map.get(x);
if(val==ei) return new int[] {level+1,lad+1,sna};
if(!vis[val]){
vis[val]=true;
//if val>x this means we have a ladder and if less, then it is a snake
que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});
}
}
}
else{
//if it is not present in map, then it is a normal cell, so just insert it directly
if(x==ei) return new int [] {level+1,lad,sna};
if(!vis[x]){
vis[x]=true;
que.addLast(new int [] {x,lad,sna});
}
}
}
}
}
level++;
}
return new int [] {-1,0,0};
}
public int snakesAndLadders(int[][] board) {
HashMap<Integer,Integer> map = new HashMap<>();
int count = 1;
int n = board.length;
boolean flag = true;
//traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)
for(int i=n-1;i>=0;i--){
//traversing in the order of the board
if(flag){
for(int j=0;j<n;j++){
if(board[i][j]!=-1){
map.put(count,board[i][j]);
}
count++;
flag=false;
}
}
else{
//reversing the direction
for(int j=n-1;j>=0;j--){
if(board[i][j]!=-1){
map.put(count,board[i][j]);
}
flag=true;
count++;
}
}
}
//if snake on destination then just return -1;
if(board[0][0]!=-1) return -1;
//we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used}
int [] ans = getans(6,map,1,n*n);;
return ans[0];
}
} | class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
unordered_map<int, int> mp;
int n = board.size();
for(int i = n-1; i >= 0; i--) {
for(int j = 0; j < n; j++) {
if(board[i][j] != -1) {
int val;
if((n-i)%2 != 0) val = (n-i-1)*n + j + 1;
else val = (n-i-1)*n + n - j;
mp[val] = board[i][j];
}
}
}
queue<pair<int, int>> q;
vector<int> visited(n*n+1, false);
q.push({1, 0});
while(!q.empty()) {
int node = q.front().first;
int moves = q.front().second;
q.pop();
if(node == n*n) return moves;
if(visited[node]) continue;
visited[node] = true;
for(int k = 1; k <= 6; k++) {
if(node+k > n*n) continue;
int x = node + k;
if(mp.find(x) != mp.end()) x = mp[x];
q.push({x, moves+1});
}
}
return -1;
}
}; | var snakesAndLadders = function(board) {
let n = board.length;
let seen = new Set();
let queue = [[1, 0]];
while (queue.length) {
let [label, step] = queue.shift();
//console.log(label, step);
let [r, c] = labelToPosition(label, n);
//console.log(r, c, n);
if (board[r][c] !== -1) {
label = board[r][c];
}
if (label == n * n) {
return step;
}
for (let x = 1; x < 7; x++) {
let nextLabel = label + x;
if (nextLabel <= n * n && !seen.has(nextLabel)) {
seen.add(nextLabel);
queue.push([nextLabel, step + 1]);
}
}
}
return -1;
};
const labelToPosition = (label, n) => {
let row = Math.floor((label - 1) / n);
let col = (label - 1) % n;
//console.log("label", row, col);
if (row % 2 === 0) {
return [n - 1 - row, col];
} else {
return [n - 1 - row, n - 1 - col];
}
}; | Snakes and Ladders |
Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.
Example 1:
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Example 2:
Input: n = 1
Output: 2
Example 3:
Input: n = 2
Output: 3
Constraints:
1 <= n <= 109
| class Solution:
def findIntegers(self, n: int) -> int:
b=(bin(n).replace("0b",""))
dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)]
def fun(i,last,tight,leading_zeros):
if i==len(str(b)):
return 1
if dp[i][tight][leading_zeros][last]!=-1:
return dp[i][tight][leading_zeros][last]
end=1
if tight==1:
end = int(b[i])
res=0
for j in range(end+1):
if j==0 and leading_zeros==1:
res+=fun(i+1,j,tight&int(j==end),1)
else:
if j==0:
res+=fun(i+1,j,tight&int(j==end),0)
else:
if last!=j:
res+=fun(i+1,j,tight&int(j==end),0)
dp[i][tight][leading_zeros][last] = res
return res
return fun(0,0,1,1) | class Solution {
public int findIntegers(int n) {
int val=0,res=0,cn=n,digi=0,prevdig=0,i;//digi means bin digi
while(cn>0){
cn=cn>>1;
digi++;
}
int dp[]=new int[digi+1];
dp[0]=1;dp[1]=2;
for(i=2;i<=digi;i++)
dp[i]=dp[i-1]+dp[i-2];
digi++;
while(digi-->=0){
if((n&(1<<digi))>0){
res+=dp[digi];
if(prevdig==1)return res;
prevdig=1;
}else prevdig=0;
}
return res+1;
}
} | class Solution {
public:
int dp[31][2];
vector<int> f(){
vector<int> res(31, 1);
dp[1][0]=0;
dp[1][1]=1;
for(int i=2; i<31; i++){
dp[i][0]=dp[i-1][0]+dp[i-1][1];
dp[i][1]=dp[i-1][0];
}
for(int i=1; i<31; i++){
res[i]=res[i-1]+dp[i][0]+dp[i][1];
}
res[1]=2;
return res;
}
int findIntegers(int n) {
int res=0;
int bits=0;
int temp=n;
vector<int> v;
while(temp>0){
bits++;
v.push_back(temp&1);
temp=temp>>1;
}
vector<int> nums=f();
bool valid=true, isValid=true;
for(int i=bits-2;i>=0;i--){
if(v[i]==1 && v[i+1]==1){
res+=nums[i];
isValid=false;
break;
}else if(v[i]==1)
res+=nums[i];
}
res+=nums[bits-1];
return isValid==true ? res+1:res;
}
}; | var findIntegers = function(n) {
let dp = len=>{
if (len<0)
return 0;
if (!len)
return 1;
let _0x = 1; // number of accepted combination when '1' is first
let _1x = 1; // number of accepted combination when '0' is first
while (--len)
[_0x, _1x] = [_0x+_1x, _0x];
return _0x + _1x;
};
let binary = n.toString(2);
let count = 0;
let is_prev_one = false;
for (let i = 0; i<binary.length; i++) {
if (binary[i] === '0') {
is_prev_one = false;
continue;
}
count += dp(binary.length-i-1);
if (is_prev_one)
return count;
is_prev_one = true;
}
return count + 1;
}; | Non-negative Integers without Consecutive Ones |
There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.
A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.
The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.
Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.
Example 1:
Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
Example 2:
Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
Constraints:
1 <= n <= 2 * 104
n - 1 <= edges.length <= 4 * 104
edges[i].length == 3
1 <= ui, vi <= n
ui != vi
1 <= weighti <= 105
There is at most one edge between any two nodes.
There is at least one path between any two nodes.
| class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
dct_nd = {}
dist_to_n = {}
queue = deque() # from n-node to 1-node
visited = set()
# 1 step: create dictionary with nodes and nodes' distances to n
# create dictionary with format (weight, node_to)
# heap will automatically sort weight and node_to in ascending order
for l, r, w in edges:
dct_nd[l] = dct_nd.get(l, []) + [(w, r)]
dct_nd[r] = dct_nd.get(r, []) + [(w, l)]
dist_to_n[n] = 0
queue.append(n)
visited.add(n)
hpf = dct_nd[n].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change
heapify(hpf)
while hpf:
el_w, el_nd = heappop(hpf)
if el_nd in visited: continue
dist_to_n[el_nd] = el_w
visited.add(el_nd)
queue.append(el_nd)
if el_nd == 1: break # you don't need to traverse more if you've reached 1-node
# other distances will be more than distance of 1-node
for (i_w, i_nd) in dct_nd[el_nd]:
if i_nd not in visited:
heappush(hpf, (el_w + i_w, i_nd))
# step 1: end
# add to dictionary one more field: number of routes to n
dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}
dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 1
# step 2: Dynamic Programming
visited.clear()
while queue:
# start from n and traverse futher and futher
nd_prv = queue.popleft()
visited.add(nd_prv)
for (w_cur, nd_cur) in dct_nd[nd_prv]:
if nd_cur not in visited and \
nd_cur in dist_to_n.keys() and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:
# to current node add number of routes from previous node
dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]
# !!! careful !!! you need to add modulo operation (as said in the task)
dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9+7))
# step 2: End
return dist_to_n[1][1] # return number of routes for 1-node | class Solution {
int dp[];
//We use memoization
public int countRestrictedPaths(int n, int[][] edges) {
int[] dist = new int[n+1];
dp = new int[n+1];
Arrays.fill(dp,-1);
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
//Create the graph from input edges
for(int[] e : edges){
graph.putIfAbsent(e[0], new HashMap<>());
graph.putIfAbsent(e[1], new HashMap<>());
graph.get(e[0]).put(e[1],e[2]);
graph.get(e[1]).put(e[0],e[2]);
}
//Single source shortest distance - something like Dijkstra's
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));
int[] base = new int[2];
base[0]=n;
pq.offer(base);
while(!pq.isEmpty()){
int[] currNode = pq.poll();
for(Map.Entry<Integer, Integer> neighbour: graph.get(currNode[0]).entrySet()){
int node = neighbour.getKey();
int d = neighbour.getValue()+currNode[1];
if(node==n) continue;
//Select only those neighbours, whose new distance is less than existing distance
//New distance = distance of currNode from n + weight of edge between currNode and neighbour
if( dist[node]==0 || d < dist[node]){
int[] newNode = new int[2];
newNode[0]=node;
newNode[1]=d;
pq.offer(newNode);
dist[node]= d;
}
}
}
return find(1,graph,n,dist);
}
//This method traverses all the paths from source node to n though it's neigbours
private int find(int node, Map<Integer, Map<Integer, Integer>> graph, int n, int[] dist ){
if(node==n){
return 1;
}
//Memoization avoid computaion of common subproblems.
if(dp[node]!=-1) return dp[node];
int ans = 0;
for(Map.Entry<Integer, Integer> neighbour: graph.get(node).entrySet()){
int currNode = neighbour.getKey();
int d = dist[currNode];
if( dist[node] > d){
ans = (ans + find(currNode, graph, n, dist)) % 1000000007;
}
}
return dp[node] = ans;
}
} | typedef pair<int, int> pii;
class Solution {
public:
int countRestrictedPaths(int n, vector<vector<int>>& edges) {
unordered_map<int, vector<pair<int, int>>> gp;
for (auto& edge : edges) {
gp[edge[0]].push_back({edge[1], edge[2]});
gp[edge[1]].push_back({edge[0], edge[2]});
}
vector<int> dist(n + 1, INT_MAX);
priority_queue<pii, vector<pii>, greater<pii> > pq;
pq.push({0, n});
dist[n] = 0;
int u, v, w;
while (!pq.empty()) {
pii p = pq.top(); pq.pop();
u = p.second;
for (auto& to : gp[u]) {
v = to.first, w = to.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
vector<int> dp(n + 1, -1);
return dfs(gp, n, dp, dist);
}
int dfs(unordered_map<int, vector<pair<int, int>>>& gp, int s, vector<int>& dp, vector<int>& dist) {
int mod = 1e9+7;
if (s == 1) return 1;
if (dp[s] != -1) return dp[s];
int sum = 0, weight, val;
for (auto& n : gp[s]) {
weight = dist[s];
val = dist[n.first];
if (val > weight) {
sum = (sum % mod + dfs(gp, n.first, dp, dist) % mod) % mod;
}
}
return dp[s] = sum % mod;
}
}; | var countRestrictedPaths = function(n, edges) {
// create an adjacency list to store the neighbors with weight for each node
const adjList = new Array(n + 1).fill(null).map(() => new Array(0));
for (const [node1, node2, weight] of edges) {
adjList[node1].push([node2, weight]);
adjList[node2].push([node1, weight]);
}
// using djikstras algorithm
// find the shortest path from n to each node
const nodeToShortestPathDistance = {}
const heap = new Heap();
heap.push([n, 0])
let numNodeSeen = 0;
while (numNodeSeen < n) {
const [node, culmativeWeight] = heap.pop();
if (nodeToShortestPathDistance.hasOwnProperty(node)) {
continue;
}
nodeToShortestPathDistance[node] = culmativeWeight;
numNodeSeen++;
for (const [neighbor, edgeWeight] of adjList[node]) {
if (nodeToShortestPathDistance.hasOwnProperty(neighbor)) {
continue;
}
heap.push([neighbor, edgeWeight + culmativeWeight]);
}
}
// do a DFS caching the number of paths for each node
// so that we don't need to redo the number of paths again
// when we visit that node through another path
const nodeToNumPaths = {};
const dfs = (node) => {
if (node === n) return 1;
if (nodeToNumPaths.hasOwnProperty(node)) {
return nodeToNumPaths[node];
}
let count = 0;
for (const [neighbor, weight] of adjList[node]) {
if (nodeToShortestPathDistance[node] > nodeToShortestPathDistance[neighbor]) {
count += dfs(neighbor);
}
}
return nodeToNumPaths[node] = count % 1000000007;
}
return dfs(1);
};
class Heap {
constructor() {
this.store = [];
}
peak() {
return this.store[0];
}
size() {
return this.store.length;
}
pop() {
if (this.store.length < 2) {
return this.store.pop();
}
const result = this.store[0];
this.store[0] = this.store.pop();
this.heapifyDown(0);
return result;
}
push(val) {
this.store.push(val);
this.heapifyUp(this.store.length - 1);
}
heapifyUp(child) {
while (child) {
const parent = Math.floor((child - 1) / 2);
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
child = parent;
} else {
return child;
}
}
}
heapifyDown(parent) {
while (true) {
let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());
if (this.shouldSwap(child2, child)) {
child = child2
}
if (this.shouldSwap(child, parent)) {
[this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
parent = child;
} else {
return parent;
}
}
}
shouldSwap(child, parent) {
return child && this.store[child][1] < this.store[parent][1];
}
} | Number of Restricted Paths From First to Last Node |
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 105
| class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
sums, i, ans = 0, 0, 0
for j in range(len(nums)):
sums += nums[j]
while nums[j]*(j-i+1) > sums+k:
sums -= nums[i]
i = i+1
ans = max(ans, j-i+1)
return ans | class Solution {
public int maxFrequency(int[] nums, int k) {
//Step-1: Sorting->
Arrays.sort(nums);
//Step-2: Two-Pointers->
int L=0,R=0;
long totalSum=0;
int res=1;
//Iterating over the array:
while(R<nums.length)
{
totalSum+=nums[R];
//The value of "totalSum+k" should be ">=" "windowSize*nums[R]"
//then only the window is possible else decrease the "totalSum"
//till the value "totalSum+k" is ">=" "windowSize*nums[R]"
while(! ((totalSum+k) >= ((R-L+1)*nums[R])) )
{
totalSum-=nums[L];
L++;
}
res=Math.max(res,(R-L+1));
R++;
}
return res;
}
} | #define ll long long
class Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
// sorting so that can easily find the optimal window
sort(nums.begin(), nums.end());
// left - left pointer of window
// right - right pointer of window
int left = 0, right = 0, ans = 1;
ll total = 0, n = nums.size();
while(right < n){
// total - total sum of elements in the window
total += nums[right];
// Checking if the we can achieve elements in this window
// If it exceeds k then shrinking the window by moving left pointer
// For optimal we will make all elements in the array equal to
// the maximum value element
while((1ll)*(right - left + 1)*nums[right] - total > k){
total -= nums[left];
left++;
}
ans = max(ans, right - left + 1);
right++;
}
return ans;
}
}; | var maxFrequency = function(nums, k) {
// We sorted because as we are allowed only to increment the value & we try to increase the smaller el to some larger el
nums.sort((a,b)=>a-b);
let left=0;
let max=Math.max(); // without any args, Math.max() is -Infinity
let curr=0;
// I have used 'for loop' so rightPtr is 'i' here
for(let i=0;i<nums.length;i++){
curr+=nums[i];
// decrement the winSize once the value required to convert could not be achieved even after utilizing K
// (i-left+1) * nums[i] because we are converting every el upto that winSize by current el
while((i-left+1) * nums[i] > curr+k){
curr-=nums[left++]
}
max = Math.max(max,i-left+1);
}
return max;
}; | Frequency of the Most Frequent Element |
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
Example 1:
Input: s = "()())()"
Output: ["(())()","()()()"]
Example 2:
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
Example 3:
Input: s = ")("
Output: [""]
Constraints:
1 <= s.length <= 25
s consists of lowercase English letters and parentheses '(' and ')'.
There will be at most 20 parentheses in s.
| class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
## RC ##
## APPROACH : BACK-TRACKING ##
## Similar to Leetcode 32. Longest Valid Parentheses ##
## LOGIC ##
# 1. use stack to find invalid left and right braces.
# 2. if its close brace at index i , you can remove it directly to make it valid and also you can also remove any of the close braces before that i.e in the range [0,i-1]
# 3. similarly for open brace, left over at index i, you can remove it or any other open brace after that i.e [i+1, end]
# 4. if left over braces are more than 1 say 2 close braces here, you need to make combinations of all 2 braces before that index and find valid parentheses.
# 5. so, we count left and right invalid braces and do backtracking removing them
## TIME COMPLEXITY : O(2^N) ## (each brace has 2 options: exits or to be removed)
## SPACE COMPLEXITY : O(N) ##
def isValid(s):
stack = []
for i in range(len(s)):
if( s[i] == '(' ):
stack.append( (i,'(') )
elif( s[i] == ')' ):
if(stack and stack[-1][1] == '('):
stack.pop()
else:
stack.append( (i,')') ) # pushing invalid close braces also
return len(stack) == 0, stack
def dfs( s, left, right):
visited.add(s)
if left == 0 and right == 0 and isValid(s)[0]: res.append(s)
for i, ch in enumerate(s):
if ch != '(' and ch != ')': continue # if it is any other char ignore.
if (ch == '(' and left == 0) or (ch == ')' and right == 0): continue # if left == 0 then removing '(' will only cause imbalance. Hence, skip.
if s[:i] + s[i+1:] not in visited:
dfs( s[:i] + s[i+1:], left - (ch == '('), right - (ch == ')') )
stack = isValid(s)[1]
lc = sum([1 for val in stack if val[1] == "("]) # num of left braces
rc = len(stack) - lc
res, visited = [], set()
dfs(s, lc, rc)
return res | class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> ans=new ArrayList<>();
HashSet<String> set=new HashSet<String>();
int minBracket=removeBracket(s);
getAns(s, minBracket,set,ans);
return ans;
}
public void getAns(String s, int minBracket, HashSet<String> set, List<String> ans){
if(set.contains(s)) return;
set.add(s);
if(minBracket==0){
int remove=removeBracket(s);
if(remove==0) ans.add(s);
return;
}
for(int i=0;i<s.length();i++){
if(s.charAt(i)!='(' && s.charAt(i)!=')') continue;
String L=s.substring(0,i);
String R=s.substring(i+1);
if(!set.contains(L+R)) getAns(L+R,minBracket-1,set,ans);
}
}
public int removeBracket(String s){
Stack<Character> stack=new Stack<>();
for(int i=0;i<s.length();i++){
char x=s.charAt(i);
if(x=='(') stack.push(x);
else if(x==')'){
if(!stack.isEmpty() && stack.peek()=='(') stack.pop();
else stack.push(x);
}
}
return stack.size();
}
} | class Solution {
public:
void back_tracking(vector<string>& res, string cus, int lp, int rp, int idx) {
if (!lp && !rp) {
int invalid = 0;
bool flag = true;
for (int i = 0; i < cus.size(); i++) {
if (cus[i] == '(')
invalid++;
else if (cus[i] == ')') {
invalid--;
if (invalid < 0) {
flag = false;
break;
}
}
}
if (flag)
res.emplace_back(cus);
return;
}
for (int i = idx; i < cus.size(); i++) {
if (i != idx && cus[i] == cus[i - 1])
continue;
if (lp + rp > cus.size() - i)
return;
if (lp && cus[i] == '(')
back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp - 1, rp, i);
if (rp && cus[i] == ')')
back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp, rp - 1, i);
}
}
vector<string> removeInvalidParentheses(string s) {
int left_p = 0;
int right_p = 0;
for (auto& ch : s) {
if (ch == '(')
left_p++;
else if (ch == ')') {
if (left_p > 0)
left_p--;
else
right_p++;
}
}
vector<string> res;
back_tracking(res, s, left_p, right_p, 0);
return res;
}
}; | var removeInvalidParentheses = function(s) {
const isValid = (s) => {
const stack = [];
for(let c of s) {
if(c == '(') stack.push(c);
else if(c == ')') {
if(stack.length && stack.at(-1) == '(')
stack.pop();
else return false;
}
}
return stack.length == 0;
}
const Q = [s], vis = new Set([s]), ans = [];
let found = false;
while(Q.length) {
const top = Q.shift();
if(isValid(top)) {
ans.push(top);
found = true;
}
if(found) continue;
for(let i = 0; i < top.length; i++) {
if(!'()'.includes(top[i])) continue;
const str = top.slice(0, i) + top.slice(i + 1);
if(!vis.has(str)) {
Q.push(str);
vis.add(str);
}
}
}
if(ans.length == 0) return [''];
return ans;
}; | Remove Invalid Parentheses |
Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
Example 1:
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.
Example 2:
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false
Example 3:
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true
Constraints:
1 <= word1.length, word2.length <= 103
1 <= word1[i].length, word2[i].length <= 103
1 <= sum(word1[i].length), sum(word2[i].length) <= 103
word1[i] and word2[i] consist of lowercase letters.
| class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return True if "".join(word1) == "".join(word2) else False | class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2)
{
return(String.join("", word1).equals(String.join("", word2)));
}
} | class Solution {
public:
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2)
{
int wordIdx1 = 0, wordIdx2 = 0, chIdx1 = 0, chIdx2 = 0;
while(true)
{
char ch1 = word1[wordIdx1][chIdx1];
char ch2 = word2[wordIdx2][chIdx2];
if (ch1 != ch2) return false;
chIdx1++; //incrementing the character index of current word from "word1"
chIdx2++; //incrementing the character index of current word from "word2";
//=========================================================
if (chIdx1 == word1[wordIdx1].size()) //if current word from "word1" is over
{
wordIdx1++; //move to next word in "word1"
chIdx1 = 0; //reset character index to 0
}
if (chIdx2 == word2[wordIdx2].size()) //if current word from "word2" is over
{
wordIdx2++; //move to next word in "word2"
chIdx2 = 0; //reset character index to 0
}
//=================================================================
if (wordIdx1 == word1.size() && wordIdx2 == word2.size()) break; // words in both arrays are finished
if (wordIdx1 == word1.size() || wordIdx2 == word2.size()) return false;
//if words in any onr of the arrays are finished and other still has some words in it
//then there is no way same string could be formed on concatenation
}
return true;
}
}; | var arrayStringsAreEqual = function(word1, word2) {
return word1.join('') === word2.join('')
}; | Check If Two String Arrays are Equivalent |
You are given two string arrays words1 and words2.
A string b is a subset of string a if every letter in b occurs in a including multiplicity.
For example, "wrr" is a subset of "warrior" but is not a subset of "world".
A string a from words1 is universal if for every string b in words2, b is a subset of a.
Return an array of all the universal strings in words1. You may return the answer in any order.
Example 1:
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
Output: ["facebook","google","leetcode"]
Example 2:
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]
Output: ["apple","google","leetcode"]
Constraints:
1 <= words1.length, words2.length <= 104
1 <= words1[i].length, words2[i].length <= 10
words1[i] and words2[i] consist only of lowercase English letters.
All the strings of words1 are unique.
| class Solution:
def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
freq = [0]*26
for w in B:
temp = [0]*26
for c in w: temp[ord(c)-97] += 1
for i in range(26): freq[i] = max(freq[i], temp[i])
ans = []
for w in A:
temp = [0]*26
for c in w: temp[ord(c)-97] += 1
if all(freq[i] <= temp[i] for i in range(26)): ans.append(w)
return ans | class Solution {
public List<String> wordSubsets(String[] words1, String[] words2) {
List<String> list=new ArrayList<>();
int[] bmax=count("");
for(String w2:words2)
{
int[] b=count(w2);
for(int i=0;i<26;i++)
{
bmax[i]=Math.max(bmax[i],b[i]);
}
}
for(String w1:words1)
{
int[] a=count(w1);
for(int i=0;i<26;i++)
{
if(a[i]<bmax[i])
{
break;
}
if(i==25)
{
list.add(w1);
}
}
}
return list;
}
public int[] count(String s)
{
int[] ans=new int[26];
for(char c:s.toCharArray())
{
ans[c-'a']++;
}
return ans;
}
} | class Solution {
public:
// calculate the frequency of string s
vector<int> giveMeFreq(string s)
{
vector<int> freq(26,0);
for(int i = 0; i < s.length(); i++)
{
freq[s[i] - 'a']++;
}
return freq;
}
vector<string> wordSubsets(vector<string>& words1, vector<string>& words2)
{
vector<string> ans; // store ans
vector<int> max_Freq_w2(26, 0); // store max freq of each character present in word2 stirngs
// we will Iterate over word to and try to find max freq for each character present in all strings.
for(auto &x : words2)
{
vector<int> freq = giveMeFreq(x);
for(int i = 0; i < 26; i++)
{
max_Freq_w2[i] = max(freq[i], max_Freq_w2[i]); // upadate freq to max freq
}
}
// we will iterate for each string in words1 ans if it have all charaters present in freq array with freq >= that then we will add it to ans
for(auto &x : words1)
{
vector<int> freq = giveMeFreq(x); // gives freq of characters for word in words1
bool flag = true;
for(int i = 0; i < 26; i++)
{
if(freq[i] < max_Freq_w2[i]) // specifies that word did not have all the characters from word2 array
{
flag = false;
break;
}
}
if(flag) ans.push_back(x); // string x is Universal string
}
return ans;
}
}; | var wordSubsets = function(words1, words2) {
this.count = Array(26).fill(0);
let tmp = Array(26).fill(0);
for(let b of words2){
tmp = counter(b);
for(let i=0; i<26; i++)
count[i] = Math.max(count[i], tmp[i]);
}
let list = []
for(let a of words1)
if(isSub(counter(a)))
list.push(a);
return list;
};
function isSub(tmp){
for(let i=0; i<26; i++)
if(tmp[i] < this.count[i])
return false;
return true;
};
function counter(s){
let tmp = Array(26).fill(0);
for(let c of s)
tmp[c.charCodeAt() - 97]++;
return tmp;
}; | Word Subsets |
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]
Constraints:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
| import heapq
class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
barcodes_counter = Counter(barcodes)
if len(barcodes_counter) == len(barcodes):
return barcodes
barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ]
heapq.heapify(barcodes_heapq)
idx, prev_count, prev_barcode = 0, 0, 0
while barcodes_heapq:
(curr_count, curr_barcode) = heapq.heappop(barcodes_heapq)
barcodes[idx] = curr_barcode
idx += 1
curr_count += 1
if prev_count:
heapq.heappush(barcodes_heapq, (prev_count, prev_barcode))
prev_count, prev_barcode = curr_count, curr_barcode
return barcodes | class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
if(barcodes.length <= 2){
return barcodes ; //Problem says solution always exist.
}
Map<Integer, Integer> count = new HashMap<>();
Integer maxKey = null; // Character having max frequency
for(int i: barcodes){
count.put(i, count.getOrDefault(i, 0) + 1);
if(maxKey == null || count.get(i) > count.get(maxKey)){
maxKey = i;
}
}
int pos = 0;
//Fill maxChar
int curr = count.get(maxKey);
while(curr-- > 0){
barcodes[pos] = maxKey;
pos += 2;
if(pos >= barcodes.length){
pos = 1;
}
}
count.remove(maxKey); // Since that character is done, we don't need to fill it again
//Fill the remaining Characters.
for(int key: count.keySet()){
curr = count.get(key);
while(curr-- > 0){
barcodes[pos] = key;
pos += 2;
if(pos >= barcodes.length){
pos = 1;
}
}
}
return barcodes;
}
} | class Solution {
public:
struct comp{
bool operator()(pair<int,int>&a, pair<int,int>&b){
return a.first < b.first;
}
};
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
unordered_map<int,int> hmap;
int n = barcodes.size();
if(n==1)return barcodes;
for(auto &bar : barcodes){
hmap[bar]++;
}
vector<int> ans;
priority_queue<pair<int,int>, vector<pair<int,int>>, comp> pq;
for(auto &it : hmap){
pq.push({it.second, it.first});
}
while(pq.size()>1){
auto firstBar = pq.top();
pq.pop();
auto secondBar = pq.top();
pq.pop();
ans.push_back(firstBar.second);
ans.push_back(secondBar.second);
--firstBar.first;
--secondBar.first;
if(firstBar.first > 0){
pq.push(firstBar);
}
if(secondBar.first > 0){
pq.push(secondBar);
}
}
if(pq.size()){
ans.push_back(pq.top().second);
pq.pop();
}
return ans;
}
}; | var rearrangeBarcodes = function(barcodes) {
var result = [];
var map = new Map();
barcodes.forEach(n => map.set(n, map.get(n) + 1 || 1));
let list = [...map.entries()].sort((a,b) => {return b[1]-a[1]})
let i = 0; //list[i][0]=>number list[i][1]=>count of this number
while(result.length!==barcodes.length){
if(list[i][1]>0) result.push(list[i][0]), list[i][1]--;
i++;
if(list[i]===undefined) i = 0;
if(list[0][1]-list[i][1]>=1&&result[result.length-1]!==list[0][0]) i = 0;
} //list has sorted, so list[0] appeared most frequent
return result;
}; | Distant Barcodes |
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
| class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
cache = []
for i in range(m):
for j in range(n):
cache.append(grid[i][j])
k %= len(cache)
new_vals = cache[-k:] + cache[:-k]
cur = 0
for i in range(m):
for j in range(n):
grid[i][j] = new_vals[cur]
cur += 1
return grid | class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
// just bruteforce??? O(i*j*k)
// instead we calculate the final position at once!
int m = grid.length; // row
int n = grid[0].length; // column
int[][] arr = new int[m][n];
// Since moving m*n times will result in same matrix, we do this:
k = k % (m*n);
// Then we move each element
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// for calculating column, it back to the original position
// every n steps
int column = (j + k) % n;
// for calculating row, we move to the next row each time
// it exceed the last element on the current row.
// For example when 2 moves k=5 steps it turns to the (+2) row.
// Thus it's original row + ((original column + steps) / n)
// But if 2 moves k=8 steps it turns to the (0,0),
// and row + ((original column + steps) / n) gives 0+(9/3)=3 (out of bounds)
// so we'll need to % number of rows to get 0. (circle back)
int row = (i + ((j + k) / n)) % m;
arr[row][column] = grid[i][j];
}
}
return (List) Arrays.asList(arr);
}
} | class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
deque<int>dq;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[i].size();j++){
dq.push_back(grid[i][j]);
}
}
int last = dq.size()-1;
while(k--){
int a = dq[last];
dq.push_front(a);
dq.pop_back();
}
int p = 0;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[i].size();j++){
grid[i][j] = dq[p];
p++;
}
}
return grid;
}
}; | /**
* @param {number[][]} grid
* @param {number} k
* @return {number[][]}
*/
var shiftGrid = function(grid, k) {
let m = grid.length
let n = grid[0].length
for (let r = 0; r < k; r++) {
const newGrid = Array(m).fill("X").map(() => Array(n).fill("X"))
for (let i = 0; i < m; i++) {
for (let j = 1; j < n; j++) {
newGrid[i][j] = grid[i][j-1]
}
}
for (let i = 1; i < m; i++) {
newGrid[i][0] = grid[i-1][n-1]
}
newGrid[0][0] = grid[m-1][n-1]
//copy the new grid for the next iteration
grid = newGrid
}
return grid
}; | Shift 2D Grid |
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
A string is homogenous if all the characters of the string are the same.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abbcccaa"
Output: 13
Explanation: The homogenous substrings are listed as below:
"a" appears 3 times.
"aa" appears 1 time.
"b" appears 2 times.
"bb" appears 1 time.
"c" appears 3 times.
"cc" appears 2 times.
"ccc" appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
Example 2:
Input: s = "xy"
Output: 2
Explanation: The homogenous substrings are "x" and "y".
Example 3:
Input: s = "zzzzz"
Output: 15
Constraints:
1 <= s.length <= 105
s consists of lowercase letters.
| class Solution:
def countHomogenous(self, s: str) -> int:
res, count, n = 0, 1, len(s)
for i in range(1,n):
if s[i]==s[i-1]:
count+=1
else:
if count>1:
res+=(count*(count-1)//2)
count=1
if count>1:
res+=(count*(count-1)//2)
return (res+n)%(10**9+7) | class Solution {
public int countHomogenous(String s) {
int res = 1;
int carry = 1;
int mod = 1000000007;
for(int i =1;i<s.length();i++){
if(s.charAt(i) == s.charAt(i-1)) carry++;
else carry = 1;
res = (res + carry) % mod;
}
return res;
}
} | class Solution {
public:
int countHomogenous(string s) {
int mod=1e9+7,size=s.size(),i=0,j=0,count=0;
while(j<size){
if(s[j]!=s[j+1]){
long n=j-i+1;
count = count + (n*(n+1)/2)%mod;
i=j+1;
}
j++;
}
return count;
}
}; | var countHomogenous = function(s) {
let mod = 1e9 + 7
let n = s.length
let j=0, res = 0
for(let i=0; i<n; i++){
if(i>0 && s[i-1] != s[i]){
let x = i-j
res += x*(x+1) / 2
j = i
}
}
let x = n-j
res += x*(x+1) / 2
return res%mod
}; | Count Number of Homogenous Substrings |
A web developer needs to know how to design a web page's size. So, given a specific rectangular web pageβs area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
Example 1:
Input: area = 4
Output: [2,2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
Example 2:
Input: area = 37
Output: [37,1]
Example 3:
Input: area = 122122
Output: [427,286]
Constraints:
1 <= area <= 107
| class Solution:
def constructRectangle(self, area: int):
y = Solution.mySqrt(area)
for i in range(y, 0, -1):
if not area%i:
return [int(area/i), i]
def mySqrt(x):
if x == 0:
return 0
n = x
count = 0
while True:
count += 1
root = 0.5 * (n + (x / n))
if abs(root - n) < 0.9:
break
n = root
return int(root) | class Solution {
public int[] constructRectangle(int area) {
int minDiff = Integer.MAX_VALUE;
int[] result = new int[2];
for (int w = 1; w*w <= area; w++) {
if (area % w == 0) {
int l = area / w;
int diff = l - w;
if (diff < minDiff) {
result[0] = l;
result[1] = w;
minDiff = diff;
}
}
}
return result;
}
} | class Solution
{
public:
vector<int> constructRectangle(int area)
{
int sq = sqrt(area);
while (sq > 1)
{
if (area % sq == 0)
break;
sq--;
}
return {area / sq, sq};
}
}; | /**
* @param {number} area
* @return {number[]}
*/
var constructRectangle = function(area) {
let w = Math.floor(Math.sqrt(area))
while(area % w != 0) w--
return [area/w, w]
}; | Construct the Rectangle |
A complex number can be represented as a string on the form "real+imaginaryi" where:
real is the real part and is an integer in the range [-100, 100].
imaginary is the imaginary part and is an integer in the range [-100, 100].
i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Constraints:
num1 and num2 are valid complex numbers.
| class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
i1=num1.index('+')
i2=num2.index('+')
a=int(num1[0:i1])
x=int(num2[0:i2])
b=int(num1[i1+1:len(num1)-1])
y=int(num2[i2+1:len(num2)-1])
ans1=a*x+(-1)*b*y
ans2=a*y+b*x
return str(ans1)+'+'+(str(ans2)+'i') | class Solution {
public String complexNumberMultiply(String num1, String num2) {
int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+')));
int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1));
int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+')));
int val4 = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1));
return "" + (val1*val3 - val2*val4) + "+" + (val1*val4 + val3*val2) + "i";
}
} | class Solution {
public:
pair<int,int> seprateRealAndImg(string &s){
int i = 0;
string real,img;
while(s[i] != '+') real += s[i++];
while(s[++i] != 'i') img += s[i];
return {stoi(real),stoi(img)};
}
string complexNumberMultiply(string num1, string num2) {
pair<int,int> x = seprateRealAndImg(num1);
pair<int,int> y = seprateRealAndImg(num2);
int a1 = x.first,b1 = x.second;
int a2 = y.first,b2 = y.second;
int real = (a1 * a2) - (b1*b2);
int img = (b1*a2) + (a1 * b2);
return to_string(real) + "+" + to_string(img) + "i";
}
}; | var complexNumberMultiply = function(num1, num2) {
let [realA, imaginaryA] = num1.split('+');
let [realB, imaginaryB] = num2.split('+');
imaginaryA = parseInt(imaginaryA);
imaginaryB = parseInt(imaginaryB);
const real = realA * realB - imaginaryA * imaginaryB;
const imaginary = realA * imaginaryB + imaginaryA * realB;
return `${real}+${imaginary}i`;
}; | Complex Number Multiplication |
You are given a string s containing lowercase letters and an integer k. You need to :
First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.
Return the minimal number of characters that you need to change to divide the string.
Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
Example 2:
Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Example 3:
Input: s = "leetcode", k = 8
Output: 0
Constraints:
1 <= k <= s.length <= 100.
s only contains lowercase English letters.
| class Solution:
def palindromePartition(self, s: str, t: int) -> int:
n=len(s)
@lru_cache(None)
def is_palin(s): #This function returns min no of chars to change to make s as a palindrome
cnt=0
for c1,c2 in zip(s,s[::-1]):
if c1!=c2: cnt+=1
if len(s)%2==0:
return cnt//2
return (cnt+1)//2
@lru_cache(None)
def dp(i,j,k): #We analyse string s[i:j+1] with k divisions left
if j==n:
return 0 if k==0 else sys.maxsize
if k==0:
return sys.maxsize
ans=sys.maxsize
cnt=is_palin(s[i:j+1])
#terminate here
ans=min(ans,dp(j+1,j+1,k-1)+cnt)
#dont terminate
ans=min(ans,dp(i,j+1,k))
return ans
return dp(0,0,t)
| class Solution {
public int mismatchCount(String s) {
int n = s.length()-1;
int count = 0;
for(int i=0,j=n;i<j;i++,j--) {
if(s.charAt(i) != s.charAt(j))
count++;
}
return count;
}
public int helper(String s, int n, int i, int j, int k, Integer[][][] dp) {
if(j>=n)
return 105;
if(k<0)
return 105;
if(dp[i][j][k] != null) {
return dp[i][j][k];
}
if(n-j<k)
return dp[i][j][k] = 105;
if(n-j==k)
return dp[i][j][k] = mismatchCount(s.substring(i,j+1));
int stop = mismatchCount(s.substring(i,j+1)) + helper(s,n,j+1,j+1,k-1,dp);
int cont = helper(s,n,i,j+1,k,dp);
return dp[i][j][k] = Math.min(stop, cont);
}
public int palindromePartition(String s, int k) {
int n = s.length();
Integer[][][] dp = new Integer[n][n][k+1];
return helper(s,s.length(),0,0,k,dp);
}
} | class Solution {
public:
int dp[105][105];
/// Count Number of changes to be done
/// to make substring of s from i to j
/// to palindrome
int changes(int i , int j , string& s){
int cnt = 0;
while(i < j){
cnt += (s[i++] != s[j--]);
}
return cnt;
}
int recur(int idx, int k, string &s){
/// If Reached end of s and found partions to be done 0
/// return 0 , otherwise return INT_MAX/any big number
if(idx == s.size()){
return (k == 0) ? 0 : 1e7;
}
/// Partitions to be done have completed , but
/// we are not at the end of the string
/// return INT_MAX/any big number
if(k == 0){
return 1e7;
}
if (dp[idx][k] != -1){
return dp[idx][k];
}
/// Partitioning the String
int ans = INT_MAX;
for (int i = idx ; i < s.size() ; i++){
ans = min(ans , changes(idx , i , s) + recur(i + 1, k - 1, s));
}
return dp[idx][k] = ans;
}
int palindromePartition(string s, int k) {
/// Edge Case
if(k == s.size()){
return 0;
}
memset(dp , -1 , sizeof(dp));
return recur(0 , k , s);
}
}; | var palindromePartition = function(s, k) {
const len = s.length;
const cost = (i = 0, j = 0) => {
let c = 0;
while(i <= j) {
if(s[i] != s[j]) c++;
i++, j--;
}
return c;
}
const dp = Array.from({ length: len }, () => {
return new Array(k + 1).fill(-1);
})
const splitHelper = (idx = 0, sl = k) => {
if(sl < 0) return Infinity;
if(idx == len) {
if(sl == 0) return 0;
return Infinity;
}
if(dp[idx][sl] != -1) return dp[idx][sl];
let ans = Infinity;
for(let i = idx; i < len; i++) {
ans = Math.min(ans, splitHelper(i + 1, sl - 1) + cost(idx, i));
}
return dp[idx][sl] = ans;
}
return splitHelper();
}; | Palindrome Partitioning III |
Given the root of an n-ary tree, return the postorder 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: [5,6,3,2,4,1]
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: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
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?
| """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
ans=[]
def post(root):
nonlocal ans
if not root:
return
for i in root.children:
post(i)
ans.append(root.val)
post(root)
return ans | class Solution {
List<Integer> result = new ArrayList<>();
public List<Integer> postorder(Node root) {
addNodes(root);
return result;
}
void addNodes(Node root) {
if (root == null) return;
for (Node child : root.children) addNodes(child);
result.add(root.val);
}
} | class Solution {
public:
void solve(Node*root,vector<int>&ans){
if(root==NULL)return;
for(int i=0;i<root->children.size();i++){
solve(root->children[i],ans);
}
ans.push_back(root->val);
}
vector<int> postorder(Node* root) {
vector<int>ans;
solve(root,ans);
return ans;
}
| var postorder = function(root) {
const res = [];
function post(node) {
if (!node) return;
for (let child of node.children) {
post(child);
}
res.push(node.val);
}
post(root);
return res;
}; | N-ary Tree Postorder Traversal |
You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i] is a non-decreasing array.
| class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
h = [(nums1[0]+nums2[0],0,0)]
visited = set()
res = []
while h and k > 0:
e, i, j = heappop(h)
if (i,j) in visited: continue
res.append(e)
visited.add((i,j))
if j+1 < len(nums2):
heappush(h,(nums1[i]+nums2[j+1],i,j+1))
if i+1 < len(nums1):
heappush(h,(nums1[i+1]+nums2[j],i+1,j))
k -= 1
return res
res = mat[0]
for i in range(1, len(mat)):
res = kSmallestPairs(res, mat[i], k)
return res[-1] | class Solution {
public int kthSmallest(int[][] mat, int k) {
int[] row = mat[0];
for(int i=1; i<mat.length; i++) {
row = findKthSmallest(row, mat[i], k);
}
return row[k-1];
}
private int[] findKthSmallest(int[] num1, int[] num2, int k) {
List<Integer> list = new ArrayList<>();
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a,b) -> (a[0]+a[1]) - (b[0]+b[1]));
for(int i=0; i<num1.length && i<k; i++) {
minHeap.offer(new int[]{num1[i], num2[0], 0});
}
for(int i=0; i<k && !minHeap.isEmpty(); i++) {
int[] candidate = minHeap.poll();
list.add(candidate[0] + candidate[1]); // SUM;
int num2Idx = candidate[2];
if(num2Idx<num2.length-1) {
minHeap.offer(new int[]{candidate[0], num2[num2Idx+1], num2Idx+1});
}
}
return list.stream().mapToInt(i->i).toArray();
}
} | class Solution {
public:
vector<int> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
auto cmp = [&nums1,&nums2](pair<int,int> a, pair<int,int>b){
return nums1[a.first]+nums2[a.second] >
nums1[b.first]+nums2[b.second];
};
int n = nums1.size();
int m = nums2.size();
vector<int> ans;
if(n==0 || m==0)
return ans;
priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)>pq(cmp);
pq.push({0,0});
while(k-- && !pq.empty())
{
int i = pq.top().first;
int j = pq.top().second;
pq.pop();
if(j+1<m)
pq.push({i,j+1});
if(j==0 && i+1 <n)
pq.push({i+1,j});
ans.push_back(nums1[i]+nums2[j]);
}
return ans;
}
int kthSmallest(vector<vector<int>>& mat, int k) {
vector<int> nums1 = mat[0];
int n = mat.size();
for(int i = 1; i<n; ++i)
{
nums1 = kSmallestPairs(nums1,mat[i],k);
}
return nums1[k-1];
}
}; | /**
* @param {number[][]} mat
* @param {number} k
* @return {number}
*/
var kthSmallest = function(mat, k) {
var m = mat.length;
var n = m ? mat[0].length : 0;
if (!m || !n) return -1;
var sums = [0];
for (var idx = 0; idx < m; idx++) {
var newSums = []
for (var sum of sums) {
for (var i = 0; i < n && i < k; i++) {
var newSum = sum + mat[idx][i];
if (newSums.length < k) {
newSums.push(newSum);
} else if (newSum < newSums[k-1]) {
newSums.pop();
newSums.push(newSum);
} else {
break;
}
newSums.sort((a, b) => a - b);
}
}
sums = newSums;
}
return sums[k-1];
}; | Find the Kth Smallest Sum of a Matrix With Sorted Rows |
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array fruits, return the maximum number of fruits you can pick.
Example 1:
Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.
Example 2:
Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].
Example 3:
Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].
Constraints:
1 <= fruits.length <= 105
0 <= fruits[i] < fruits.length
| class Solution:
def totalFruit(self, fruits: List[int]) -> int:
ans=0
fruitdict=defaultdict()
stack=[]
i,j=0,0
while j<len(fruits):
if fruits[j] not in fruitdict and len(fruitdict)<2:
stack.append(fruits[j])
fruitdict[fruits[j]]=j
j+=1
elif fruits[j] in fruitdict:
fruitdict[fruits[j]]=j
j+=1
else:
if fruitdict[stack[0]]>fruitdict[stack[1]] :
i = fruitdict[stack[1]]+1
del fruitdict[stack[1]]
stack.pop()
else:
i = fruitdict[stack[0]]+1
del fruitdict[stack[0]]
stack.pop(0)
ans=max(ans,j-i)
return ans | class Solution {
public int totalFruit(int[] fruits) {
if (fruits == null || fruits.length == 0) {
return 0;
}
int start = 0, end = 0, res = 0;
HashMap<Integer, Integer> map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit
while (end < fruits.length) {
if (map.size() <= 2) {
map.put(fruits[end], end);
end++;
}
if (map.size() > 2) {
int leftMost = fruits.length;
for (int num : map.values()) {
leftMost = Math.min(leftMost, num);
}
map.remove(fruits[leftMost]);
start = leftMost + 1;
}
res = Math.max(res, end - start);
}
return res;
}
} | class Solution {
public:
int totalFruit(vector<int>& fruits) {
int i=0, j=0, ans = 1;
unordered_map<int, int>mp;
while(j<fruits.size()){
mp[fruits[j]]++;
if(mp.size()<2){
ans = max(ans, j-i+1);
j++;
}
else if(mp.size()==2){
ans = max(ans, j-i+1);
j++;
}
else if(mp.size()>2){
while(mp.size()>2){
mp[fruits[i]]--;
if(mp[fruits[i]]==0)
mp.erase(fruits[i]);
i++;
}
if(mp.size()==2){
ans = max(ans, j-i+1);
}
j++;
}
}
return ans;
}
}; | var totalFruit = function(fruits) {
let myFruits = {};
let n = fruits.length;
let windowStart = 0;
let ans = -Number.MAX_VALUE;
for(let windowEnd = 0; windowEnd < n; windowEnd++) {
let fruit = fruits[windowEnd];
if(fruit in myFruits) {
myFruits[fruit]++;
}
else {
myFruits[fruit] = 1;
}
while(Object.keys(myFruits).length > 2) {
let throwOut = fruits[windowStart];
myFruits[throwOut]--;
if(myFruits[throwOut] == 0) {
delete myFruits[throwOut];
}
windowStart++;
}
ans = Math.max(ans, windowEnd - windowStart + 1);
}
return ans;
}; | Fruit Into Baskets |
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.
The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.
Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Example 1:
Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Explanation: The constructed 2D array should contain 2 rows and 2 columns.
The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.
The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.
Example 2:
Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Explanation: The constructed 2D array should contain 1 row and 3 columns.
Put all three elements in original into the first row of the constructed 2D array.
Example 3:
Input: original = [1,2], m = 1, n = 1
Output: []
Explanation: There are 2 elements in original.
It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.
Constraints:
1 <= original.length <= 5 * 104
1 <= original[i] <= 105
1 <= m, n <= 4 * 104
| class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []
| class Solution {
public int[][] construct2DArray(int[] original, int m, int n) {
if (original.length != m * n) return new int[0][];
int[][] ans = new int[m][n];
int currRow = 0, currCol = 0;
for (int num : original) {
ans[currRow][currCol++] = num;
if (currCol == n) {
currCol = 0;
currRow++;
}
}
return ans;
}
}
// TC: O(n), SC: O(m * n) | class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if (m * n != original.size()) return {};
vector<vector<int>> res;
for (int i = 0; i < m*n; i+=n)
res.push_back(vector<int>(original.begin()+i, original.begin()+i+n));
return res;
}
}; | var construct2DArray = function(original, m, n) {
if (original.length !== (m*n)) return []
let result = []
let arr = []
for (let i = 0; i < original.length; i++){
arr.push(original[i])
if (arr.length === n){
result.push(arr)
arr = []
}
}
return result
}; | Convert 1D Array Into 2D Array |
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
Example 3:
Input: n = 4
Output: 2
Constraints:
1 <= n <= 231 - 1
| class Solution:
def integerReplacement(self, n: int) -> int:
dp = {}
def dfs(num):
if num == 1:
return 0
if num in dp:
return dp[num]
# if num is even, we have only one option -> n / 2
even = odd = 0
if num % 2 == 0:
even = 1 + dfs(num // 2)
else:
# if num is odd, we have two option, either we increment the num or decrement the num
odd1 = 1 + dfs(num - 1)
odd2 = 1 + dfs(num + 1)
# take the min of both operation
odd = min(odd1, odd2)
dp[num] = even + odd
return dp[num]
return dfs(n) | class Solution {
public int integerReplacement(int n) {
return (int)calc(n,0);
}
public long calc(long n,int i){
if(n==1)
return i;
if(n<1)
return 0;
long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE;
if(n%2==0)
a=calc(n/2,i+1);
else{
b=calc(n-1,i+1);
c=calc(n+1,i+1);
}
long d=Math.min(a,Math.min(b,c));
return d;
}
} | class Solution {
public:
int integerReplacement(int n) {
return helper(n);
}
int helper(long n)
{
if(n == 1)
return 0;
if(n % 2)
return 1 + min(helper(n - 1), helper(n + 1));
return 1 + helper(n / 2);
}
}; | var integerReplacement = function(n) {
let count=0;
while(n>1){
if(n%2===0){n/=2;}
else{
if(n!==3 && (n+1)%4===0){n++;}
else{n--;}
}
count++;
}
return count;
}; | Integer Replacement |
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.
Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Example 1:
Input: root = [10,4,6]
Output: true
Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.
10 is equal to 4 + 6, so we return true.
Example 2:
Input: root = [5,3,1]
Output: false
Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.
Constraints:
The tree consists only of the root, its left child, and its right child.
-100 <= Node.val <= 100
| class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == (root.left.val + root.right.val) | class Solution
{
public boolean checkTree(TreeNode root)
{
return root.val == root.left.val + root.right.val; // O(1)
}
} | class Solution {
public:
bool checkTree(TreeNode* root) {
if(root->left->val+root->right->val==root->val){
return true;
}
return false;
}
}; | var checkTree = function(root) {
return root.val === root.left.val + root.right.val;
}; | Root Equals Sum of Children |
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example 1:
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Example 2:
Input: words = ["cat","dog","catdog"]
Output: ["catdog"]
Constraints:
1 <= words.length <= 104
1 <= words[i].length <= 30
words[i] consists of only lowercase English letters.
All the strings of words are unique.
1 <= sum(words[i].length) <= 105
| class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
set_words = set(words)
def check(word, seen):
if word == '':
return True
for i in range(len(word) if seen else len(word) - 1):
if word[:i+1] in set_words:
if check(word[i+1:], seen | {word[:i+1]}):
return True
return False
return [word for word in words if check(word, set())] | class Solution {
Set<String> set = new HashSet<>();
Set<String> res = new HashSet<>();
int index = 0;
public List<String> findAllConcatenatedWordsInADict(String[] words) {
for (String word: words) set.add(word);
for (String word: words) {
int len = word.length();
index = 0;
backtrack(len, word, 0);
}
List<String> list = new ArrayList<>();
for (String word: res) list.add(word);
return list;
}
public void backtrack (int len, String word, int num) {
if (index == len && num >= 2) {
res.add(word);
}
int indexCopy = index;
for (int i = index + 1; i <= len; i++) {
if (set.contains(word.substring(index, i))) {
index = i;
backtrack(len, word, num + 1);
index = indexCopy;
}
}
return;
}
} | class Solution {
public:
int checkForConcatenation( unordered_set<string>& st, string w, int i, vector<int>& dp){
if(i == w.size()) return 1;
if(dp[i] != -1) return dp[i];
for(int j = i; j < w.size(); ++j ){
string t = w.substr(i, j-i+1);
if(t.size() != w.size() && st.find(t) != st.end()){
if(checkForConcatenation(st, w, j+1, dp)) return dp[i] = 1;
}
}
return dp[i] = 0;
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> ans;
unordered_set<string> st;
for(auto w: words) st.insert(w);
for(auto w: words){
vector<int> dp(w.size(), -1);
if(checkForConcatenation(st, w, 0, dp)) ans.push_back(w);
}
return ans;
}
}; | class Node {
val;
children;
isWord = false;
constructor(val) {
this.val = val;
}
}
class Trie {
nodes = Array(26);
addWord(w) {
let idx = this.getIdx(w[0]);
let node = this.nodes[idx] || new Node(w[0]);
this.nodes[idx] = node;
for (let i=1; i < w.length; ++i) {
node.children = node.children || Array(26);
idx = this.getIdx(w[i]);
let childNode = node.children[idx] || new Node(w[i]);
node.children[idx] = childNode;
node = childNode;
}
node.isWord = true;
}
getExistingWords(w, start) {
const rslt = [];
let node = {children: this.nodes};
for (let i=start; i < w.length; ++i) {
node = (node.children || [])[this.getIdx(w[i])];
if (!node) {
break;
}
if (node.isWord) {
rslt.push(i-start+1);
}
}
return rslt;
}
getIdx(ch) {
return ch.charCodeAt(0) - "a".charCodeAt(0);
}
}
var findAllConcatenatedWordsInADict = function(words) {
const rslt = [];
words = words.sort((a,b) => a.length-b.length);
let start = 0;
if (words[0].length === 0) {
++start;
}
const tr = new Trie();
for (let i = start; i < words.length; ++i) {
if (check(words[i], 0, tr, Array(words[i].length))) {
rslt.push(words[i]);
}
tr.addWord(words[i]);
}
return rslt;
};
function check(word, i, trie, dp) {
if (i > word.length || dp[i] === false) {
return false;
}
if (i === word.length || dp[i] === true) {
return true;
}
const lens = trie.getExistingWords(word, i);
if (!lens.length) {
dp[i] = false;
return false;
}
dp[i] = true;
for (let l of lens) {
if (check(word, i+l, trie, dp)) {
return true;
}
}
dp[i] = false;
return false;
} | Concatenated Words |
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
Example 1:
Input: s1 = "ab", s2 = "ba"
Output: 1
Example 2:
Input: s1 = "abc", s2 = "bca"
Output: 2
Constraints:
1 <= s1.length <= 20
s2.length == s1.length
s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
s2 is an anagram of s1.
| class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
n = len(s1)
def helper(i, curr, dp):
if curr == s2:
return 0
if curr not in dp[i]:
if curr[i] == s2[i]:
dp[i][curr] = helper(i+1, curr, dp)
else:
temp = sys.maxsize
for j in range(i+1, n):
if curr[j] == s2[i]:
temp = min(temp, 1+helper(i+1, curr[:i]+curr[j]+curr[i+1:j]+curr[i]+curr[j+1:], dp))
dp[i][curr] = temp
return dp[i][curr]
dp = [{} for _ in range(n)]
return helper(0, s1, dp) | class Solution {
public int kSimilarity(String s1, String s2) {
HashSet<String> vis = new HashSet<>();
ArrayDeque<String> queue = new ArrayDeque<>();
int level = 0;
queue.add(s1);
while(queue.size() > 0){
int size = queue.size();
for(int i=0;i<size;i++){
String rem = queue.remove(); // remove
if(vis.contains(rem)){ // Mark*
continue;
}
vis.add(rem);
if(rem.equals(s2)){ // Work
return level;
}
// Add
for(String s : getNeighbors(rem,s2)){
if(!vis.contains(s)){
queue.add(s);
}
}
}
level++;
}
return -1;
}
public ArrayList<String> getNeighbors(String rem,String s2){
ArrayList<String> res = new ArrayList<>();
int idx = -1;
for(int i=0;i<rem.length();i++){
if(rem.charAt(i) != s2.charAt(i)){
idx = i;
break;
}
}
for(int j=idx+1;j<rem.length();j++){
if(rem.charAt(j) == s2.charAt(idx)){
String s = swap(rem,idx,j);
res.add(s);
}
}
return res;
}
public String swap(String str,int i,int j){
StringBuilder sb = new StringBuilder(str);
char chi = sb.charAt(i);
char chj = sb.charAt(j);
sb.setCharAt(i,chj);
sb.setCharAt(j,chi);
return sb.toString();
}
} | class Solution {
public:
unordered_map<string,int>m;
int solve(string &s1,string &s2,int i)
{
if(i==s1.length())
return 0;
if(m.find(s1)!=m.end())return m[s1];
if(s1[i]==s2[i])
return m[s1]=solve(s1,s2,i+1);
int ans=1e5;
for(int j=i+1;j<s1.length();j++)
{
if(s1[j]==s2[i])
{
swap(s1[j],s1[i]);
ans=min(ans,1+solve(s1,s2,i+1));
swap(s1[j],s1[i]);
}
}
return m[s1]=ans;
}
int kSimilarity(string s1, string s2) {
return solve(s1,s2,0);
}
}; | var kSimilarity = function(s1, s2) {
// abc --> bca
// swap from 0: a !== b, find next b, swap(0,1) --> bac
// swap from 1: a !== c, find next c, swap(1,2) --> bca
return bfs(s1, s2);
};
const bfs = (a,b)=>{
if(a===b)
return 0;
const visited = new Set();
const queue = [];
queue.push([a,0,0]); // str, idx, swapCount
while(queue.length>0)
{
let [s, idx, cnt] = queue.shift();
while(s[idx]===b[idx])
{
idx++;
}
for(let j = idx+1; j<s.length; j++)
{
if(s[j]===b[idx]) {
s = swap(s, idx, j);
if(s===b) {
return cnt+1;
}
if(!visited.has(s))
{
queue.push([s.slice(), idx, cnt+1]);
visited.add(s.slice());
}
// swap back for later index
s = swap(s, idx, j);
}
}
}
return -1;
}
const swap = (s, i, j)=>{
let arr = s.split('');
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr.join('');
} | K-Similar Strings |
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the TimeMap class:
TimeMap() Initializes the object of the data structure.
void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.
String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".
Example 1:
Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]
Explanation
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1); // return "bar"
timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4); // return "bar2"
timeMap.get("foo", 5); // return "bar2"
Constraints:
1 <= key.length, value.length <= 100
key and value consist of lowercase English letters and digits.
1 <= timestamp <= 107
All the timestamps timestamp of set are strictly increasing.
At most 2 * 105 calls will be made to set and get.
| class TimeMap:
def __init__(self):
self.dict = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.dict:
self.dict[key] = ([], [])
self.dict[key][0].append(value)
self.dict[key][1].append(timestamp)
else:
self.dict[key][0].append(value)
self.dict[key][1].append(timestamp)
def bsearch(self, nums, target):
beg = 0
end = len(nums)-1
lastIndex = len(nums)-1
while beg<=end:
mid = (beg+end)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
end = mid-1
elif target > nums[mid]:
beg = mid+1
if target < nums[mid] and mid == 0:
return -1
if target > nums[mid]:
return mid
return mid-1
def get(self, key: str, timestamp: int) -> str:
if key not in self.dict:
return ""
index = self.bsearch(self.dict[key][1], timestamp)
return self.dict[key][0][index] if 0 <= index < len(self.dict[key][0]) else ""
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp) | class TimeMap {
private Map<String, List<Entry>> map;
private final String NOT_FOUND = "";
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
List<Entry> entries = map.getOrDefault(key, new ArrayList<>());
entries.add(new Entry(value, timestamp));
map.put(key, entries);
}
public String get(String key, int timestamp) {
List<Entry> entries = map.get(key);
if (entries == null) {
return NOT_FOUND;
}
return binarySearch(entries, timestamp);
}
private String binarySearch(List<Entry> entries, int timestamp) {
int lo = 0, hi = entries.size() - 1, mid = -1;
String ans = "";
// Base cases - if value is not set, return empty
if (entries.get(lo).timestamp > timestamp) {
return NOT_FOUND;
}
// If timestamp is equal or greater, return the last value saved in map against this key, since that will have the largest timestamp
else if (entries.get(hi).timestamp <= timestamp) {
return entries.get(hi).value;
}
// Else apply binary search to get correct value
while (lo <= hi) {
mid = lo + (hi-lo)/2;
Entry entry = entries.get(mid);
// System.out.println("mid: "+mid);
if (entry.timestamp == timestamp) {
return entry.value;
}
// Save ans, and look for ans on right half to find greater timestamp
else if (entry.timestamp < timestamp) {
ans = entry.value;
lo = mid + 1;
}
else {
hi = mid - 1;
}
}
return ans;
}
}
class Entry {
String value;
int timestamp;
public Entry(String value, int timestamp) {
this.value = value;
this.timestamp = timestamp;
}
} | class TimeMap {
public:
map<string,vector<pair<int,string>>> mp;
string Max;
TimeMap() {
Max = "";
}
void set(string key, string value, int timestamp) {
mp[key].push_back(make_pair(timestamp,value));
Max = max(Max,value);
}
string get(string key, int timestamp) {
pair<int,string> p = make_pair(timestamp,Max);
int l = upper_bound(mp[key].begin(),mp[key].end(),p)-mp[key].begin();
if(l==0){
return "";
}
return mp[key][l-1].second;
}
};
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap* obj = new TimeMap();
* obj->set(key,value,timestamp);
* string param_2 = obj->get(key,timestamp);
*/ | var TimeMap = function() {
this.data = new Map();
};
/**
* @param {string} key
* @param {string} value
* @param {number} timestamp
* @return {void}
*/
TimeMap.prototype.set = function(key, value, timestamp) {
if(!this.data.has(key)){
this.data.set(key, [{timestamp: timestamp, value: value}])
} else {
let temp_store = this.data.get(key);
temp_store.push({timestamp: timestamp, value: value});
this.data.set(key, temp_store);
}
};
/**
* @param {string} key
* @param {number} timestamp
* @return {string}
*/
TimeMap.prototype.get = function(key, timestamp) {
if(this.data.has(key)){
const keyArray = this.data.get(key);
//Optimize with binary search - Ordered by insert time, O(log n) devide and conq method (Like searching a dictionary)
const index = keyArray.binarySearch(timestamp);
if(keyArray[index].timestamp > timestamp){
return ''
}
return keyArray[index].value || prev;
}
return '';
};
Array.prototype.binarySearch = function(key){
let left = 0;
let right = this.length - 1;
while (left < right) {
const i = Math.floor((left + right + 1) / 2);
if (this[i].timestamp > key) {
right = i - 1;
} else {
left = i;
}
}
return left;
}
/**
* Your TimeMap object will be instantiated and called as such:
* var obj = new TimeMap()
* obj.set(key,value,timestamp)
* var param_2 = obj.get(key,timestamp)
*/ | Time Based Key-Value Store |
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.
Constraints:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
| class Solution(object):
def busyStudent(self, startTime, endTime, queryTime):
res = 0
for i in range(len(startTime)):
if startTime[i] <= queryTime <= endTime[i]:
res += 1
else:
pass
return res | class Solution {
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int count = 0;
for (int i = 0; i < startTime.length; ++i) {
if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count;
}
return count;
}
} | class Solution {
public:
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
int ans = 0 ;
for(int i = 0 ; i < size(startTime); ++i )
if(queryTime >= startTime[i] and queryTime <= endTime[i]) ++ans ;
return ans ;
}
}; | var busyStudent = function(startTime, endTime, queryTime) {
let res = 0;
for (let i = 0; i < startTime.length; i++) {
if (startTime[i] <= queryTime && endTime[i] >= queryTime) res++;
}
return res;
}; | Number of Students Doing Homework at a Given Time |
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
| class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
# switch start and destination if destination is before start
if start>destination:
start,destination=destination,start
#find minimum for clockwise and counterclockwise direction
return min(sum(distance[start:destination]),sum(distance[:start]+distance[destination:])) | class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int firstDistance = 0;
int secondDistance = 0;
if (start < destination) {
//check clockwise rotation
for (int i = start; i < destination; i++)
firstDistance += distance[i];
//check clockwise rotation from destination to end
for (int i = destination; i < distance.length; i++)
secondDistance += distance[i];
//continues checking till start (if needed)
for (int i = 0; i < start; i++)
secondDistance += distance[i];
}
else {
for (int i = start; i < distance.length; i++)
firstDistance += distance[i];
for (int i = 0; i < destination; i++)
firstDistance += distance[i];
for (int i = start - 1; i >= destination; i--)
secondDistance += distance[i];
}
return Math.min(firstDistance, secondDistance);
}
} | class Solution {
public:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
int n = distance.size();
if (start == destination)
return 0;
int one_way = 0;
int i = start;
while (i != destination) // find distance of one way
{
one_way += distance[i];
i = (i+1)%n;
}
int second_way = 0;
i = destination;
while (i != start) // find distance of second way
{
second_way += distance[i];
i = (i+1)%n;
}
return one_way<second_way? one_way : second_way; // return the minimum
}
}; | /**
* @param {number[]} distance
* @param {number} start
* @param {number} destination
* @return {number}
*/
let sumArray = (arr) => {
return arr.reduce((prev, curr) => prev + curr, 0)
}
var distanceBetweenBusStops = function(distance, start, destination) {
let dist = sumArray(distance.slice((start < destination)?start:destination, (start < destination)?destination:start));
return Math.min(dist, sumArray(distance) - dist)
}; | Distance Between Bus Stops |
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example 1:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
β β
The above arrows point to positions where the corresponding bits are different.
Example 2:
Input: x = 3, y = 1
Output: 1
Constraints:
0 <= x, y <= 231 - 1
| class Solution:
def hammingDistance(self, x: int, y: int) -> int:
# First, using XOR Bitwise Operator, we take all distinct set bits.
z = x ^ y
# We inicialize our answer with zero.
ans = 0
# Iterate while our z is not zero.
while z:
# Every iteration we add one to our answer.
ans += 1
# Using the expression z & (z - 1), we erase the lowest set bit in z.
z &= z - 1
return ans | class Solution {
public int hammingDistance(int x, int y) {
int ans=x^y;
int count=0;
while(ans>0){
count+=ans&1;
ans>>=1;
}
return count;
}
} | class Solution {
public:
int hammingDistance(int x, int y) {
int val = (x^y);
int ans = 0;
for(int i = 31; i >= 0; --i){
if(val & (1 << i)) ans++;
}
return ans;
}
}; | var hammingDistance = function(x, y) {
x = x.toString(2).split('')
y = y.toString(2).split('')
let count = 0;
const len = Math.max(x.length,y.length);
if (x.length < y.length) {
x = Array(len - x.length).fill('0').concat(x)
} else {
y = Array(len - y.length).fill('0').concat(y)
}
for (let i = 1; i <= len; i++) {
x.at(-i) !== y.at(-i)? count++ : null
}
return count
}; | Hamming Distance |
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].
Example 1:
Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
Example 2:
Input: left = 47, right = 85
Output: [48,55,66,77]
Constraints:
1 <= left <= right <= 104
| class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
res = []
for num in range(left, right + 1):
num_str = str(num)
if '0' in num_str:
continue
elif all([num % int(digit_str) == 0 for digit_str in num_str]):
res.append(num)
return res | class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> ans= new ArrayList<>();
while(left<=right){
if(fun(left))
ans.add(left);
left++;
}
return ans;
}
boolean fun(int x){
int k=x;
while(k>0)
{
int y=k%10;
k=k/10;
if(y==0||x%y!=0)
return false;
}
return true;
}
} | class Solution {
public:
bool check(int n){
vector<bool> isif(10);
for(int i = 1; i <= 9; i++){
if(n % i == 0) isif[i] = 1;
}
while(n > 0){
if(isif[n%10] == 0) return false;
n /= 10;
}
return true;
}
vector<int> selfDividingNumbers(int left, int right) {
vector<int> ans;
for(int i = left; i <= right; i++){
if(check(i)) ans.push_back(i);
}
return ans;
}
}; | /**
* @param {number} left
* @param {number} right
* @return {number[]}
*/
var selfDividingNumbers = function(left, right) {
const selfDivisibles = [];
for (let i = left; i <= right; i++) {
if (checkDivisibility(i)) {
selfDivisibles.push(i);
}
}
return selfDivisibles;
};
function checkDivisibility(num) {
let status = true;
let mod;
let original = num;
while (num !== 0) {
mod = Math.trunc(num % 10);
if (original % mod !== 0) {
status = false;
break;
}
num = Math.trunc(num / 10);
}
return status;
} | Self Dividing Numbers |
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
| class Solution:
def isPalindrome(self, s: str) -> bool:
cleaned = ""
for c in s:
if c.isalnum():
cleaned += c.lower()
return (cleaned == cleaned[::-1])
| class Solution {
public boolean isPalindrome(String s) {
if(s.length()==1 || s.length()==0)
{
return true;
}
s=s.trim().toLowerCase();
//s=s.toLowerCase();
String a="";
boolean bool=false;
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)>='a' && s.charAt(i)<='z') || (s.charAt(i)>='0' && s.charAt(i)<='9'))
{
a=a+s.charAt(i);
}
}
if(a.length()==1 || a.length()==0)
{
return true;
}
for(int i=0;i<a.length()/2;i++)
{
if(a.charAt(i)==a.charAt(a.length()-i-1))
{
bool=true;
}
else{
return false;
}
}
return bool;
}
} | class Solution {
public:
bool isPalindrome(string s) {
auto it = remove_if(s.begin(), s.end(), [](char const &c) {
return !isalnum(c);
});
s.erase(it, s.end());
transform(s.begin(), s.end(), s.begin(), ::tolower);
int i = 0;
int j = s.size()-1;
while(i <= j) {
if(s[i] != s[j]) return false;
i++; j--;
}
return true;
}
}; | var isPalindrome = function(s) {
const toLower = s.toLowerCase().replace(/[\W_\s]+/g, '').replace(/ /g, '')
let m = 0
let n = toLower.length - 1
while (m < n) {
if (toLower[m] !== toLower[n]) {
return false
}
m++
n--
}
return true
} | Valid Palindrome |
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Example 2:
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Example 3:
Input: letters = ["c","f","j"], target = "d"
Output: "f"
Constraints:
2 <= letters.length <= 104
letters[i] is a lowercase English letter.
letters is sorted in non-decreasing order.
letters contains at least two different characters.
target is a lowercase English letter.
| class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
beg = 0
end = len(letters)-1
while beg <= end:
mid = (beg+end)//2
if letters[mid]>target:
end = mid -1
else:
beg = mid +1
return letters[beg] if beg<len(letters) else letters[0] | class Solution {
public char nextGreatestLetter(char[] letters, char target) {
int start=0,end=letters.length-1;
while(start<=end){
int mid=start+(end-start)/2;
if(letters[mid]>target){ //strictly greater is the solution we want
end = mid-1;
}else{
start=mid+1;
}
}
return letters[start % letters.length]; // this is the wrap around condition , we use modulo %
}
} | class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
int siz = letters.size();
bool isPresent = false;
char ans;
char temp = target;
if (target == letters[siz-1]) return letters[0];
for(int i=0; i<siz-1; i++) {
if (target == letters[i] && target != letters[i+1]) {
ans = letters[i+1];
isPresent = true;
break;
}
}
// if target not in letters
while (!isPresent) {
temp = temp +1;
isPresent = binary_search(letters.begin(), letters.end(), temp); // used STL !!
if(isPresent) {
ans=temp;
break;
}
}
return ans;
}
}; | /**
* @param {character[]} letters
* @param {character} target
* @return {character}
*/
var nextGreatestLetter = function(letters, target) {
let result=[]
for (letter of letters){
if (letter>target){
result.push(letter);
}
}
if (result.length){
return result[0];
}
else{
return letters[0];
}
}; | Find Smallest Letter Greater Than Target |
You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
If the element is odd, multiply it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
Example 1:
Input: nums = [1,2,3,4]
Output: 1
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
Example 2:
Input: nums = [4,1,5,20,3]
Output: 3
Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
Example 3:
Input: nums = [2,10,8]
Output: 3
Constraints:
n == nums.length
2 <= n <= 5 * 104
1 <= nums[i] <= 109
| class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
from sortedcontainers import SortedList
for i in range(len(nums)):
if nums[i]%2!=0:
nums[i]=nums[i]*2
nums = SortedList(nums)
result = 100000000000
while True:
min_value = nums[0]
max_value = nums[-1]
if max_value % 2 == 0:
nums.pop()
nums.add(max_value // 2)
max_value = nums[-1]
min_value = nums[0]
result = min(result , max_value - min_value)
else:
result = min(result , max_value - min_value)
break
return result | class Solution {
public int minimumDeviation(int[] nums) {
TreeSet<Integer> temp = new TreeSet<>();
for(int i: nums){
if(i % 2 == 0){
temp.add(i);
}
else{
temp.add(i * 2);
}
}
int md = temp.last() - temp.first();
int m = 0;
while(temp.size() > 0 && temp.last() % 2 == 0){
m = temp.last();
temp.remove(m);
temp.add(m / 2);
md = Math.min(md, temp.last() - temp.first());
}
return md;
}
} | // ππππPlease upvote if it helps ππππ
class Solution {
public:
int minimumDeviation(vector<int>& nums) {
int n = nums.size();
int mx = INT_MIN, mn = INT_MAX;
// Increasing all elements to as maximum as it can and tranck the minimum,
// number and also the resutl
for(int i = 0; i<n; ++i)
{
if((nums[i]%2) != 0) // multiplication by 2 if nums[i] is odd
nums[i] *= 2; // maximising all odd numbers
mx = max(mx,nums[i]);
mn = min(mn,nums[i]);
}
int min_deviation = mx - mn;
priority_queue<int> pq;
// Inserting into Priority queue (Max Heap) and try to decrease as much we can
for(int i = 0; i<n; ++i)
{
pq.push(nums[i]);
}
while((pq.top()) % 2 == 0)
{
int top = pq.top();
pq.pop(); // popped the top element
min_deviation = min(min_deviation, top - mn);
top /= 2;
mn = min(mn, top); // updating min
pq.push(top); // pushing again the top as we have to minimize the max
}
min_deviation = min(min_deviation, pq.top() - mn);
// we are returning mx - mn
return min_deviation;
}
}; | var minimumDeviation = function(nums) {
let pq = new MaxPriorityQueue({priority: x => x})
for (let n of nums) {
if (n % 2) n *= 2
pq.enqueue(n)
}
let ans = pq.front().element - pq.back().element
while (pq.front().element % 2 === 0) {
pq.enqueue(pq.dequeue().element / 2)
ans = Math.min(ans, pq.front().element - pq.back().element)
}
return ans
}; | Minimize Deviation in Array |
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
Follow up:
A straightforward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
| class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
rows = len(matrix)
cols = len(matrix[0])
visited=set()
for r in range(rows):
for c in range(cols):
if matrix[r][c]==0 and (r,c) not in visited :
for t in range(cols):
if matrix[r][t]!=0:
matrix[r][t]=0
visited.add((r,t))
for h in range(rows):
if matrix[h][c]!=0:
matrix[h][c]=0
visited.add((h,c))
##Time Complexity :- O(m*n)
##Space Complexity:- O(m+n)
``` | class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return;
int row = matrix.length;
int col = matrix[0].length;
boolean firstColumnZero = false;
boolean firstRowZero = false;
// Check if first column should be made zero
for (int i = 0; i < row; i++) {
if (matrix[i][0] == 0) {
firstColumnZero = true;
break;
}
}
// Check if first row should be made zero
for (int i = 0; i < col; i++) {
if (matrix[0][i] == 0) {
firstRowZero = true;
break;
}
}
// Traverse the matrix excluding first row and column
// If zero is found, update the same in first row and column
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// Now traverse again and update
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
// Traverse and update first column
if (firstColumnZero) {
for (int i = 0; i < row; i++) {
matrix[i][0] = 0;
}
}
// Traverse and update first row
if (firstRowZero) {
for (int j = 0; j < col; j++) {
matrix[0][j] = 0;
}
}
}
} | class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
unordered_map<int,int>ump;
unordered_map<int,int>mp;
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix[0].size();j++){
if(matrix[i][j]==0){
ump[i]=1;
mp[j]=1;
}
}
}
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix[0].size();j++){
if(ump[i] || mp[j]){
matrix[i][j]=0;
}
}
}
}
}; | var setZeroes = function(matrix) {
let rows = new Array(matrix.length).fill(0); //to store the index of rows to be set to 0
let cols = new Array(matrix[0].length).fill(0);//to store the index of columns to be set to 0
for(let i=0; i<matrix.length; i++){
for(let j=0; j<matrix[i].length; j++){
if(matrix[i][j]===0){//for zero value both row and column will be set to 0
rows[i] = 1;
cols[j] = 1;
}
}
}
for(let i=0; i<matrix.length; i++){
for(let j=0; j<matrix[i].length; j++){
if(rows[i]===1 || cols[j]===1){//if either row or col val is set, poulate it with 0
matrix[i][j] = 0;
}
}
}
}; | Set Matrix Zeroes |
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.
An English letter b is greater than another letter a if b appears after a in the English alphabet.
Example 1:
Input: s = "lEeTcOdE"
Output: "E"
Explanation:
The letter 'E' is the only letter to appear in both lower and upper case.
Example 2:
Input: s = "arRAzFif"
Output: "R"
Explanation:
The letter 'R' is the greatest letter to appear in both lower and upper case.
Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.
Example 3:
Input: s = "AbCdEfGhIjK"
Output: ""
Explanation:
There is no letter that appears in both lower and upper case.
Constraints:
1 <= s.length <= 1000
s consists of lowercase and uppercase English letters.
| class Solution:
def greatestLetter(self, s: str) -> str:
cnt = Counter(s)
return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "") | class Solution
{
public String greatestLetter(String s)
{
Set<Character> set = new HashSet<>();
for(char ch : s.toCharArray())
set.add(ch);
for(char ch = 'Z'; ch >= 'A'; ch--)
if(set.contains(ch) && set.contains((char)('a'+(ch-'A'))))
return ""+ch;
return "";
}
} | class Solution {
public:
string greatestLetter(string s)
{
vector<int> low(26), upp(26); //storing occurences of lower and upper case letters
string res = "";
for(auto it : s) //iterate over each char and mark it in respective vector
{
if(it-'A'>=0 && it-'A'<26)
upp[it-'A']++;
else
low[it-'a']++;
}
for(int i=25; i>=0; i--) //start from greater char
{
if(low[i] && upp[i]) //if char found in upp and low that will be the result
{
res += 'A'+i;
break;
}
}
return res;
}
}; | var greatestLetter = function(s) {
let set=new Set(s.split(""));
// ASCII(A-Z, a-z)=(65-90, 97-122).
for(let i=90; i>=65; i--){
if(set.has(String.fromCharCode(i)) && set.has(String.fromCharCode(i+32))){
return String.fromCharCode(i);
}
}
return "";
}; | Greatest English Letter in Upper and Lower Case |
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Constraints:
0 <= s.length, p.length <= 2000
s contains only lowercase English letters.
p contains only lowercase English letters, '?' or '*'.
| class Solution:
def isMatch(self, s: str, p: str) -> bool:
m= len(s)
n= len(p)
dp = [[False]*(n+1) for i in range(m+1)]
dp[0][0] = True
for j in range(len(p)):
if p[j] == "*":
dp[0][j+1] = dp[0][j]
for i in range(1,m+1):
for j in range(1,n+1):
if p[j-1] == "*":
dp[i][j] = dp[i-1][j] or dp[i][j-1]
elif s[i-1] == p[j-1] or p[j-1] == "?":
dp[i][j] = dp[i-1][j-1]
return dp[-1][-1] | class Solution {
public boolean isMatch(String s, String p) {
int i=0;
int j=0;
int starIdx=-1;
int lastMatch=-1;
while(i<s.length()){
if(j<p.length() && (s.charAt(i)==p.charAt(j) ||
p.charAt(j)=='?')){
i++;
j++;
}else if(j<p.length() && p.charAt(j)=='*'){
starIdx=j;
lastMatch=i;
j++;
}else if(starIdx!=-1){
//there is a no match and there was a previous star, we will reset the j to indx after star_index
//lastMatch will tell from which index we start comparing the string if we encounter * in pattern
j=starIdx+1;
lastMatch++; // we are saying we included more characters in * so we incremented the index
i=lastMatch;
}else{
return false;
}
}
while(j<p.length() && p.charAt(j)=='*') j++;
if(i!=s.length() || j!=p.length()) return false;
return true;
}
} | class Solution {
public:
bool match(int i, int j, string &a, string &b, vector<vector<int>>&dp)
{
if(i<0 && j<0) return true;
if(i>=0 && j<0) return false;
if(i<0 && j>=0)
{
for(;j>-1;j--) if(b[j]!='*') return false;
return true;
}
if(dp[i][j]!=-1) return dp[i][j];
if(a[i]==b[j] || b[j]=='?') return dp[i][j] = match(i-1,j-1,a,b,dp);
if(b[j]=='*') return dp[i][j] = (match(i-1,j,a,b,dp) | match(i,j-1,a,b,dp));
return false;
}
bool isMatch(string s, string p) {
int n=s.size(), m=p.size();
vector<vector<int>>dp(n+1,vector<int>(m+1,-1));
return match(n-1,m-1,s,p,dp);
}
}; | var isMatch = function(s, p) {
const slen = s.length, plen = p.length;
const dp = new Map();
const solve = (si = 0, pi = 0) => {
// both are compared and are equal till end
if(si == slen && pi == plen) return true;
// we have consumed are wildcard string and still s is remaining
if(pi == plen) return false;
// we still have wildcard characters remaining
if(si == slen) {
while(p[pi] == '*') pi++;
return pi == plen;
}
const key = [si, pi].join(':');
if(dp.has(key)) return dp.get(key);
let ans = false;
if(p[pi] == '*') {
// drop * or use it
ans = solve(si, pi + 1) || solve(si + 1, pi);
} else {
const match = s[si] == p[pi] || p[pi] == '?';
if(match) ans = solve(si + 1, pi + 1);
}
dp.set(key, ans);
return ans;
}
return solve();
}; | Wildcard Matching |
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Example 2:
Input: head = [5], left = 1, right = 1
Output: [5]
Constraints:
The number of nodes in the list is n.
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
Follow up: Could you do it in one pass? | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
# revrese api
def reverse(start, end):
prev = None
cur = start
while prev != end:
nextNode = cur.next
cur.next = prev
prev = cur
cur = nextNode
return prev
if not head or not head.next or right <= left:
return head
start, end = head, head
node, afterRight = 0, 0
# At the begining
if left == 1:
# start index
inc = left-1
while inc > 0:
start = start.next
inc -= 1
# end index
inc = right-1
while inc > 0:
end = end.next
inc -= 1
afterRight = end.next
reverse(start, end)
head = end
else: # Left other then begining
# start index
inc = left-2
while inc > 0:
start = start.next
inc -= 1
# end index
inc = right-1
while inc > 0:
end = end.next
inc -= 1
afterRight = end.next
begin = start # node before left
start = start.next
reverse(start, end)
begin.next = end
# If their's ll chain left agter right chain it to the updated ll
if afterRight:
start.next = afterRight
return head
"""
TC : O(n)
Sc : O(1)
""" | class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(left==right) return head;
ListNode last = null;
ListNode present = head;
for(int i=0; present != null && i<left-1;i++){
last = present;
present = present.next;
}
ListNode finalEnd = present;
ListNode prev = last;
ListNode next = present.next;
for(int i=0; present != null && i<right-left+1;i++){
present.next = prev;
prev = present;
present = next;
if(next!= null){
next = next.next;
}
}
if(last != null){
last.next = prev;
}
else{
head = prev;
}
finalEnd.next = present;
return head;
}
} | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head)
{
ListNode* prev = NULL;
while(head != NULL)
{
ListNode* temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
ListNode* reverseN(ListNode* head,int right)
{
ListNode* temp = head;
while(right != 1)
temp = temp->next,right--;
ListNode* temp2 = temp->next;
temp->next = NULL;
ListNode* ans = reverse(head);
head->next = temp2;
return ans;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left == right)
return head;
if(left == 1)
{
return reverseN(head,right);
}
else
{
ListNode* temp = head;
right--;
while(left != 2)
{
temp = temp->next;
left--;
right--;
}
ListNode* temp2 = reverseN(temp->next,right);
temp->next = temp2;
return head;
}
return NULL;
}
}; | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} left
* @param {number} right
* @return {ListNode}
*/
var reverseBetween = function(head, left, right) {
if (!head || !head.next || left === right) {
return head;
}
let dummyHead = new ListNode(-1);
dummyHead.next = head;
let prev = dummyHead;
for (let i = 1; i < left; i++) {
prev = prev.next;
}
let curr = prev.next;
for (let i = left; i < right; i++) {
let next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummyHead.next;
}; | Reverse Linked List II |
You are given two non-negative integers num1 and num2.
In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.
For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.
Return the number of operations required to make either num1 = 0 or num2 = 0.
Example 1:
Input: num1 = 2, num2 = 3
Output: 3
Explanation:
- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.
- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.
- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.
Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.
So the total number of operations required is 3.
Example 2:
Input: num1 = 10, num2 = 10
Output: 1
Explanation:
- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.
Now num1 = 0 and num2 = 10. Since num1 == 0, we are done.
So the total number of operations required is 1.
Constraints:
0 <= num1, num2 <= 105
| class Solution:
def countOperations(self, num1: int, num2: int) -> int:
ct=0
while num2 and num1:
if num1>=num2:
num1=num1-num2
else:
num2=num2-num1
ct+=1
return ct | class Solution {
public int countOperations(int num1, int num2) {
int count=0;
while(num1!=0 && num2!=0){
if(num1<num2){
count+=num2/num1;
num2=num2%num1;
}else{
count+=num1/num2;
num1=num1%num2;
}
}
return count;
}
} | class Solution {
public:
int countOperations(int num1, int num2) {
if(num1==0 || num2==0) return 0;
if(num1>=num2) num1=num1-num2;
else if(num2>num1) num2=num2-num1;
return 1+countOperations(num1,num2);
}
}; | /**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var countOperations = function(num1, num2) {
let count = 0;
while (num1 !== 0 && num2 !== 0) {
if (num1 <= num2) num2 -= num1;
else num1 -= num2;
count++;
}
return count;
}; | Count Operations to Obtain Zero |
You are given an array of n strings strs, all of the same length.
The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as:
abc
bce
cae
You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.
Return the number of columns that you will delete.
Example 1:
Input: strs = ["cba","daf","ghi"]
Output: 1
Explanation: The grid looks as follows:
cba
daf
ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
Example 2:
Input: strs = ["a","b"]
Output: 0
Explanation: The grid looks as follows:
a
b
Column 0 is the only column and is sorted, so you will not delete any columns.
Example 3:
Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: The grid looks as follows:
zyx
wvu
tsr
All 3 columns are not sorted, so you will delete all 3.
Constraints:
n == strs.length
1 <= n <= 100
1 <= strs[i].length <= 1000
strs[i] consists of lowercase English letters.
| class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
cols={}
l=len(strs)
l_s = len(strs[0])
delete = set()
for i in range(l):
for col in range(l_s):
if col in cols:
if cols[col]>strs[i][col]:
delete.add(col)
cols[col] = strs[i][col]
return len(delete) | class Solution {
public int minDeletionSize(String[] strs) {
int count = 0;
for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column
for(int j = 0; j < strs.length-1; j++){
if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(i)){
continue;
}else{
count++;
break;
}
}
}
return count;
}
} | class Solution {
public:
int minDeletionSize(vector<string>& strs) {
int col = strs[0].size();
int row = strs.size();
int count = 0;
for(int c = 0 ; c < col ; c++){
for(int r = 1 ; r < row ; r++){
if(strs[r][c] - strs[r - 1][c] < 0){
count++;
break;
}
}
}
return count;
}
}; | /**
* @param {string[]} strs
* @return {number}
*/
var minDeletionSize = function(strs) {
let count = 0;
for(let i=0; i<strs[0].length; i++){
for(let j=0; j<strs.length-1; j++){
if(strs[j].charAt(i) > strs[j+1].charAt(i)){
count++;
break;
}
}
}
return count;
}; | Delete Columns to Make Sorted |
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
| '''
First of all, I'm making a few tuples using zip function.
Then extracting every created tuple. (for tup in zip())
After that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup)
'''
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [number for tup in zip(nums[:n], nums[n:]) for number in tup] | class Solution {
public int[] shuffle(int[] nums, int n)
{
int[] arr = new int[2*n];
int j = 0;
int k = n;
for(int i =0; i<2*n; i++)
{
if(i%2==0)
{
arr[i] = nums[j];
j++;
}
else
{
arr[i] = nums[k];
k++;
}
}
return arr;
}
} | class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> ans;
int size = nums.size();
int i = 0, j =0;
for(i=0,j=n; i<n && j<size; i++, j++){
ans.push_back(nums[i]);
ans.push_back(nums[j]);
}
return ans;
}
}; | var shuffle = function(nums, n) {
while (n--) {
nums.splice(n + 1, 0, nums.pop());
}
return nums;
}; | Shuffle the Array |
You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.
Return a list answer of size 2 where:
answer[0] is a list of all players that have not lost any matches.
answer[1] is a list of all players that have lost exactly one match.
The values in the two lists should be returned in increasing order.
Note:
You should only consider the players that have played at least one match.
The testcases will be generated such that no two matches will have the same outcome.
Example 1:
Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output: [[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
Example 2:
Input: matches = [[2,3],[1,3],[5,4],[6,4]]
Output: [[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].
Constraints:
1 <= matches.length <= 105
matches[i].length == 2
1 <= winneri, loseri <= 105
winneri != loseri
All matches[i] are unique.
| class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
winners, losers, table = [], [], {}
for winner, loser in matches:
# map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.
# map.get(key, 0) returns map[key] if key exists and 0 if it does not.
table[winner] = table.get(winner, 0) # Winner
table[loser] = table.get(loser, 0) + 1
for k, v in table.items(): # Player k with losses v
if v == 0:
winners.append(k) # If player k has no loss ie v == 0
if v == 1:
losers.append(k) # If player k has one loss ie v == 1
return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays. | class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
int[] won = new int[100001];
int[] loss = new int[100001];
for(int[] match : matches) {
won[match[0]]++;
loss[match[1]]++;
}
// System.out.print(Arrays.toString(won));
// System.out.print(Arrays.toString(loss));
List<List<Integer>> ans = new ArrayList<>();
List<Integer> wonAllMatches = new ArrayList<>();
List<Integer> lostOneMatch = new ArrayList<>();
for(int i = 0; i < won.length; i++) {
if(won[i] > 0 && loss[i] == 0) { //for checking players that have not lost any match.
wonAllMatches.add(i);
}
if(loss[i] == 1) {
lostOneMatch.add(i); //for checking players that have lost exactly one match.
}
}
ans.add(wonAllMatches);
ans.add(lostOneMatch);
return ans;
}
} | class Solution {
public:
vector<vector<int>> findWinners(vector<vector<int>>& matches) {
unordered_map<int,int> umap;
vector<vector<int>> result(2);
for(int i=0;i<matches.size();i++)
{
umap[matches[i][1]]++;
}
for(auto i=umap.begin();i!=umap.end();i++)
{
if(i->second==1)
{
result[1].push_back(i->first);
}
}
for(int i=0;i<matches.size();i++)
{
if(umap[matches[i][0]]==0)
{
result[0].push_back(matches[i][0]);
umap[matches[i][0]]=1;
}
}
sort(result[0].begin(),result[0].end());
sort(result[1].begin(),result[1].end());
return result;
}
}; | /**
* @param {number[][]} matches
* @return {number[][]}
*/
var findWinners = function(matches) {
var looser = {};
var allPlayer={};
for(var i=0; i<matches.length; i++)
{
if(looser[matches[i][1]])
looser[matches[i][1]]++;
else
looser[matches[i][1]]=1
if(!allPlayer[matches[i][0]])
allPlayer[matches[i][0]]=1
if(!allPlayer[matches[i][1]])
allPlayer[matches[i][1]]=1
}
var first=[], second=[];
for(var key in allPlayer)
{
if(!looser[key])
first.push(key);
if(looser[key] == 1)
second.push(key);
}
return [first, second]
}; | Find Players With Zero or One Losses |
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
| class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
ans = []
node = root
q = collections.deque([node])
order = -1
while q:
order = -order
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(level[::order])
return ans | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Queue<TreeNode> q=new LinkedList<TreeNode>();
List<List<Integer>> res=new ArrayList<>();
if(root==null){
return res;
}
q.offer(root);
boolean flag=true;
while(!q.isEmpty()){
int size=q.size();
List<Integer> curr=new ArrayList<>();
for(int i=0;i<size;i++){
if(q.peek().left!=null){
q.offer(q.peek().left);
}
if(q.peek().right!=null){
q.offer(q.peek().right);
}
if(flag==true){
curr.add(q.poll().val);
}else{
curr.add(0,q.poll().val);
}
}
if(flag==true){
flag=false;
}else{
flag=true;
}
res.add(curr);
}
return res;
}
} | class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root) return ans;
vector<int> r;
queue<TreeNode*> q;
int count=1;
q.push(root);
q.push(NULL);
while(1){
if(q.front()==NULL){
q.pop();
if(count%2==0) reverse(r.begin(),r.end());
ans.push_back(r);
if (q.empty()) return ans;
q.push(NULL);
r.resize(0);
count++;
continue;
}
r.push_back((q.front())->val);
if(q.front()->left)q.push((q.front())->left);
if(q.front()->right)q.push((q.front())->right);
q.pop();
}
return ans;
}
}; | var zigzagLevelOrder = function(root) {
let result = []
if(root == null) return result
let queue = []
let leftToRight = true
queue.push(root)
while(queue.length != 0) {
let qSize = queue.length
let ans = []
// Processing level
for(let i=0;i<qSize;i++) {
let front = queue.shift()
let index = leftToRight ? i : qSize-i-1
ans[index] = front.val
if(front.left) queue.push(front.left)
if(front.right) queue.push(front.right)
}
// changing order of operation
leftToRight = !leftToRight
result.push(ans)
}
return result
}; | Binary Tree Zigzag Level Order Traversal |
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.
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.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110"
Output: -1
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
| class Solution:
def minSwaps(self, st: str) -> int:
def swap(st,c):
n = len(st)
mis = 0
for i in range(n):
if i%2==0 and st[i]!=c:
mis+=1
if i%2==1 and st[i]==c:
mis+=1
return mis//2
dic = Counter(st)
z = dic['0']
o = dic['1']
res=0
if abs(z-o)>1:
return -1
elif z>o:
res = swap(st,'0')
elif o>z:
res = swap(st,'1')
else:
res = min(swap(st,'0'),swap(st,'1'))
return res | class Solution {
public int minSwaps(String s) {
int cntZero=0 , cntOne=0;
for(char ch:s.toCharArray()){
if(ch=='0') cntZero++;
else cntOne++;
}
//Invalid
if(Math.abs(cntOne-cntZero)>1) return -1;
if(cntOne>cntZero){ //one must be at even posotion
return countSwaps(s,'1');
}else if(cntOne<cntZero){
return countSwaps(s,'0'); //zero must be at even position
}
return Math.min(countSwaps(s,'0'),countSwaps(s,'1'));
}
//wrong count
private int countSwaps(String s,char start){
int wrongPosition=0;
for(int i=0;i<s.length();i+=2){
if(s.charAt(i)!=start) wrongPosition++;
}
return wrongPosition;
}
} | class Solution {
int minFillPos(string& s, char ch, int current = 0) {
int count = 0;
for(int i=0; i<s.size(); i+=2) {
if(s[i] != ch) count++;
}
return count;
}
public:
int minSwaps(string s) {
int oneCount = count(s.begin(), s.end(), '1');
int zeroCount = count(s.begin(), s.end(), '0');
if(abs(oneCount-zeroCount) > 1) return -1;
if(oneCount > zeroCount) return minFillPos(s,'1');
if(zeroCount > oneCount) return minFillPos(s,'0');
return min(minFillPos(s,'0'), minFillPos(s,'1'));
}
}; | var minSwaps = function(s) {
let ones = 0;
let zeroes = 0;
for(let c of s) {
if(c === "1") ones++
else zeroes++
}
if(Math.abs(ones - zeroes) > 1) return -1
function count(i) {
let res = 0
for(let c of s) {
if(i !== c) res++;
if(i === "1") i = "0";
else i = "1";
}
return res/2;
};
if(ones > zeroes) return count("1")
if(zeroes > ones) return count("0")
return Math.min(count("1"), count("0"));
}; | Minimum Number of Swaps to Make the Binary String Alternating |
There are n flights that are labeled from 1 to n.
You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.
Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.
Example 1:
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
Explanation:
Flight labels: 1 2 3 4 5
Booking 1 reserved: 10 10
Booking 2 reserved: 20 20
Booking 3 reserved: 25 25 25 25
Total seats: 10 55 45 25 25
Hence, answer = [10,55,45,25,25]
Example 2:
Input: bookings = [[1,2,10],[2,2,15]], n = 2
Output: [10,25]
Explanation:
Flight labels: 1 2
Booking 1 reserved: 10 10
Booking 2 reserved: 15
Total seats: 10 25
Hence, answer = [10,25]
Constraints:
1 <= n <= 2 * 104
1 <= bookings.length <= 2 * 104
bookings[i].length == 3
1 <= firsti <= lasti <= n
1 <= seatsi <= 104
| class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
flights = [0]*n
for start,end,seats in bookings:
flights[start-1] += seats
if end < n: flights[end] -= seats
for i in range(n-1):
flights[i+1] += flights[i]
return flights | class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
// nums all equals to zero
int[] nums = new int[n];
// construct the diffs
Difference df = new Difference(nums);
for (int[] booking : bookings) {
// pay attention to the index
int i = booking[0] - 1;
int j = booking[1] - 1;
int val = booking[2];
// increase nums[i..j] by val
df.increment(i, j, val);
}
// return the final array
return df.result();
}
class Difference {
// diff array
private int[] diff;
public Difference(int[] nums) {
assert nums.length > 0;
diff = new int[nums.length];
// construct the diffs
diff[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
diff[i] = nums[i] - nums[i - 1];
}
}
// increase nums[i..j] by val
public void increment(int i, int j, int val) {
diff[i] += val;
if (j + 1 < diff.length) {
diff[j + 1] -= val;
}
}
public int[] result() {
int[] res = new int[diff.length];
// contract the diff array based on the result
res[0] = diff[0];
for (int i = 1; i < diff.length; i++) {
res[i] = res[i - 1] + diff[i];
}
return res;
}
}
} | class Solution {
public:
vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
vector<int> arr(n);
for (const auto& b : bookings) {
int start = b[0] - 1, end = b[1], seats = b[2];
arr[start] += seats;
if (end < n) {
arr[end] -= seats;
}
}
partial_sum(begin(arr), end(arr), begin(arr));
return arr;
}
}; | var corpFlightBookings = function(bookings, n) {
// +1 as dummy guard on the tail, which allow us not to check right boundary every time
let unitStep = Array(n+1).fill(0);
for(const [first, last, seatVector ] of bookings ){
// -1 because booking flight is 1-indexed, given by description
let [left, right] = [first-1, last-1];
unitStep[ left ] += seatVector;
unitStep[ right+1 ] -= seatVector;
}
// Reconstruct booking as drawing combination of retangle signal, built with unit step impulse
for( let i = 1; i < unitStep.length ; i++ ){
unitStep[ i ] += unitStep[ i-1 ];
}
// last one is dummy guard on the tail, no need to return
return unitStep.slice(0, n);
}; | Corporate Flight Bookings |
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
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 = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2:
Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
Constraints:
n == arr.length
1 <= n <= 10
0 <= arr[i] < n
All the elements of arr are unique.
| class Solution(object):
def maxChunksToSorted(self, arr):
n= len(arr)
count=0
currentmax= -2**63
for i in range(0,n):
currentmax=max(currentmax, arr[i])
if (currentmax==i):
count+=1
return count
| class Solution {
public int maxChunksToSorted(int[] arr) {
int max=0, count=0;
for(int i=0; i<arr.length; i++){
max = Math.max(arr[i],max);
if(i==max) count++;
}return count;
}
} | class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
// using chaining technique
int maxi=INT_MIN;
int ans =0;
for(int i=0;i<size(arr);i++)
{
maxi = max(maxi,arr[i]);
if(maxi==i)
{
//.. found partition
ans++;
}
}
return ans;
}
}; | var maxChunksToSorted = function(arr) {
let count = 0, cumSum = 0;
arr.forEach((el, index) => {
cumSum += el-index;
if (cumSum === 0) count++;
});
return count;
}; | Max Chunks To Make Sorted |
Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.
Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: s = "10101"
Output: 4
Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1"
"1|01|01"
"10|10|1"
"10|1|01"
Example 2:
Input: s = "1001"
Output: 0
Example 3:
Input: s = "0000"
Output: 3
Explanation: There are three ways to split s in 3 parts.
"0|0|00"
"0|00|0"
"00|0|0"
Constraints:
3 <= s.length <= 105
s[i] is either '0' or '1'.
| class Solution:
def numWays(self, s: str) -> int:
ones = 0
# Count number of Ones
for char in s:
if char == "1":
ones += 1
# Can't be grouped equally if the ones are not divisible by 3
if ones > 0 and ones % 3 != 0:
return 0
# Ways of selecting two dividers from n - 1 dividers
if ones == 0:
n = len(s)
# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }
return (((n - 1) * (n - 2)) // 2) % ((10 ** 9) + 7)
# Number of ones in each group
ones_interval = ones // 3
# Number of zeroes which lie on the borders
left, right = 0, 0
# Iterator
i = 0
temp = 0
# Finding the zeroes on the left and right border
while i < len(s):
temp += int(s[i]) & 1
if temp == ones_interval:
if s[i] == '0':
left += 1
if temp == 2 * ones_interval:
if s[i] == '0':
right += 1
i += 1
# The result is the product of number of (left + 1) and (right + 1)
# Because let's assume it as we only want to fill up the middle group
# The solution would be if we have zero then there might be a zero in the middle
# Or there might not be the zero, so this might case is added and then
# the events are independent so product of both the events
return ((left + 1) * (right + 1)) % ((10 ** 9) + 7) | class Solution {
public int numWays(String s) {
long n=s.length();
long one=0;//to count number of ones
long mod=1_000_000_007;
char[] c=s.toCharArray();
for(int i=0;i<c.length;i++)
{
if(c[i]=='1')
one++;
}
//there will be 3 cases
// 1.no ones present in the string
// 2.number of ones present in the string isnt divisible by 3(since we need to cut 3 parts)
// 3.number of ones divisible by 3
if(one==0)//case 1
{
return (int)((((n-1)*(n-2))/2)%mod);
}
if(one%3!=0)//case 2,which means we cant split ones equally
return 0;
//case 3
long ones=one/3;//number of ones that should be present in each part
one=0;
long part1=0;//number of ways in which part1 and part2 can be split
long part2=0;
for(int i=0;i<c.length;i++)
{
if(c[i]=='1')
one++;
if(one==ones)
part1++;
if(one==2*ones)
part2++;
}
return (int)((part1*part2)%mod);
}
} | class Solution {
public:
int MOD = 1e9 + 7 ;
int numWays(string s) {
int ones = count(begin(s),end(s),'1') , n = s.size() ;
if(ones % 3) return 0 ;
if(!ones) return (((n-1) * 1LL * (n-2) * 1LL) / 2) % MOD ; /// n- 1 C 2
int left = 0 , right = 0 , count = 0 , i = 0 ;
while(count <= ones / 3){
count += s[i++] == '1' ;
if(count == ones/3) ++left ;
}
i = n - 1 , count = 0 ;
while(count <= ones/3){
count += s[i--] == '1' ;
if(count == ones/3) ++ right ;
}
return (left * 1LL * right * 1LL) % MOD ;
}
}; | var numWays = function(s) {
let one = 0;
let list = [];
for(let i = 0; i < s.length; i++){
if(s[i]==="1") one++, list.push(i);
}
if(one%3!==0) return 0;
if(one===0) return ((s.length-1)*(s.length-2)/2) % 1000000007;
one/=3;
return ((list[one]-list[one-1])*(list[2*one]-list[2*one-1])) % 1000000007;
}; | Number of Ways to Split a String |
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.
Constraints:
1 <= hand.length <= 104
0 <= hand[i] <= 109
1 <= groupSize <= hand.length
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
| #####################################################################################################################
# Problem: Hand of Straights
# Solution : Hash Table, Min Heap
# Time Complexity : O(n logn)
# Space Complexity : O(n)
#####################################################################################################################
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
freq = collections.defaultdict(int)
for num in hand:
freq[num] += 1
min_heap = list(freq.keys())
heapq.heapify(min_heap)
while min_heap:
smallest = min_heap[0]
for num in range(smallest, smallest + groupSize):
if num not in freq:
return False
freq[num] -= 1
if freq[num] == 0:
if num != min_heap[0]:
return False
heapq.heappop(min_heap)
return True | class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if(hand.length % groupSize != 0)
return false;
Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(int card : hand){
if(map.containsKey(card))
map.put(card, map.get(card) + 1);
else {
map.put(card, 1);
minHeap.add(card);
}
}
while(!minHeap.isEmpty()){
int min = minHeap.peek();
for(int i=min; i < min + groupSize; i++){
if(!map.containsKey(i) || map.get(i) == 0)
return false;
map.put(i, map.get(i) - 1);
if(map.get(i) == 0){
if(minHeap.peek() != i)
return false;
minHeap.poll();
}
}
}
return true;
}
} | class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
int n = hand.size();
if(n%groupSize != 0) // We can't rearrange elements of size groupsize so return false
return false;
map<int,int>mp;
for(auto it : hand)
mp[it]++;
while(mp.size() > 0){
int start = mp.begin()->first; // Taking the topmost element of map
for(int i=0; i<groupSize; i++){
if(mp.find(start) != mp.end()){
mp[start]--;
if(mp[start] == 0)
mp.erase(start);
start++; // Increasing for finding next consecutive element of start.
}
else
return false;
}
}
return true;
}
}; | var isNStraightHand = function(hand, groupSize) {
if(hand.length%groupSize!==0) return false;
const map = new Map();
hand.forEach(h=>{
map.set(h,map.get(h)+1||1);
});
// sort based on the key in asc order
const sortedMap = new Map([...map.entries()].sort((a,b)=>a[0]-b[0]));
while(sortedMap.size){
// getting the first key
const firstKey = sortedMap.keys().next().value;
for(let i=firstKey;i<firstKey+groupSize;++i){
if(!sortedMap.has(i)){
return false
}
const freq = sortedMap.get(i);
if(freq===1){
sortedMap.delete(i)
}else{
sortedMap.set(i,sortedMap.get(i)-1);
}
}
}
return true;
}; | Hand of Straights |
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.
Example 1:
Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
Constraints:
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 108
| class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
target,m=divmod(sum(matchsticks),4)
if m:return False
targetLst=[0]*4
length=len(matchsticks)
matchsticks.sort(reverse=True)
def bt(i):
if i==length:
return len(set(targetLst))==1
for j in range(4):
if matchsticks[i]+targetLst[j]>target:
continue
targetLst[j]+=matchsticks[i]
if bt(i+1):
return True
targetLst[j]-=matchsticks[i]
if not targetLst[j]:break
return False
return matchsticks[0]<=target and bt(0) | /*
Time complexity: O(2 ^ n)
Space complexity: O(n)
Inutition:
---------
Same as "Partition to K Equal Sum Subsets"
*/
class Solution {
public boolean backtrack(int[] nums, int idx, int k, int subsetSum, int target, boolean[] vis) {
// base case
if (k == 0)
return true;
if (target == subsetSum) {
// if one of the side is found then keep finding the other k - 1 sides starting again from the beginning
return backtrack(nums, 0, k - 1, 0, target, vis);
}
// hypothesis
for(int i = idx; i < nums.length; i++) {
// if number is already visited or sum if out of range then skip
if (vis[i] || subsetSum + nums[i] > target)
continue;
// Pruning
// if the last position (i - 1) is not visited, that means the current combination didn't work,
// and since this position (i) has the same value, it won't work for it as well. Thus, skip it.
if (i - 1 >= 0 && nums[i] == nums[i - 1] && !vis[i - 1])
continue;
vis[i] = true;
if (backtrack(nums, i + 1, k, subsetSum + nums[i], target, vis))
return true;
// backtrack
vis[i] = false;
}
return false;
}
private void reverse(int[] arr) {
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
public boolean makesquare(int[] matchsticks) {
int sum = 0;
int k = 4;
int n = matchsticks.length;
// sort the array in descending order to make the recursion hit the base case quicker
Arrays.sort(matchsticks);
reverse(matchsticks);
for(int match: matchsticks)
sum += match;
if (sum % k != 0)
return false;
int target = sum / k;
boolean[] vis = new boolean[n];
return backtrack(matchsticks, 0, k, 0, target, vis);
}
} | class Solution {
public:
bool makesquare(vector<int>& matchsticks) {
int goal = 0, totalSum = 0;
for (int i : matchsticks) {
totalSum += i;
}
goal = totalSum / 4;
sort(matchsticks.begin(), matchsticks.end(), [](auto left, auto right) {
return left > right;
});
int b = 0;
if (totalSum % 4) {
return false;
}
return backtrack(0, b, 0, goal, 4, matchsticks);
}
bool backtrack(int start, int &b, int sum, int &goal, int groups, vector<int>& matchsticks) {
if (sum == goal) {
//set sum to 0, groups--
return backtrack(0, b, 0, goal, groups-1, matchsticks);
}
if (groups == 1) {
return true;
}
for (int i = start; i < matchsticks.size(); i++) {
if ((i > 0) && (!(b & (1 << (i - 1)))) && (matchsticks[i] == matchsticks[i-1])) {
continue;
}
//if element not used and element value doesnt go over group sum
if (((b & (1 << i)) == 0) && (sum + matchsticks[i] <= goal)) {
//set element to used, recursion
b ^= (1 << i);
if (backtrack(i + 1, b, sum + matchsticks[i], goal, groups, matchsticks)) {
return true;
}
//if here, received a false, set element to unused again
b ^= (1 << i);
}
}
return false;
}
}; | var makesquare = function(matchsticks) {
const perimeter = matchsticks.reduce((a, b) => a + b, 0);
if(perimeter % 4 != 0 || matchsticks.length < 4) return false;
const sideLen = perimeter / 4;
// find a way to divide the array in 4 group of sum side length
const sides = new Array(4).fill(0);
const len = matchsticks.length;
matchsticks.sort((a, b) => b - a);
const solve = (x = 0) => {
if(x == len) {
return sides.every(side => side == sideLen);
}
for(let i = 0; i < 4; i++) {
if(sides[i] + matchsticks[x] > sideLen) {
continue;
}
sides[i] += matchsticks[x];
if(solve(x + 1)) return true;
sides[i] -= matchsticks[x];
}
return false;
}
return solve();
}; | Matchsticks to Square |
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder and postorder consist of unique values.
Each value of postorder also appears in inorder.
inorder is guaranteed to be the inorder traversal of the tree.
postorder is guaranteed to be the postorder traversal of the tree.
| import bisect
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def buildTree(self, inorder, postorder):
"""
7
2
-8
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
([-4,-10,3,-1], [7]) ((11,-8,2), [7])
"""
currentSplits = [(inorder, [], [])]
nodeDirectory = {}
finalSplits = []
for nodeVal in reversed(postorder):
nodeDirectory[nodeVal] = TreeNode(nodeVal)
for splits, nodes, directions in reversed(currentSplits):
removing = None
if nodeVal in splits:
removing = (splits, nodes, directions)
left = splits[:splits.index(nodeVal)]
right = splits[splits.index(nodeVal)+1:]
currentSplits.append((left, nodes+[nodeVal], directions + ['left']))
if len(left) <= 1:
finalSplits.append((left, nodes+[nodeVal], directions + ['left']))
currentSplits.append((right, nodes+[nodeVal], directions + ['right']))
if len(right) <= 1:
finalSplits.append((right, nodes+[nodeVal], directions + ['right']))
break
if removing:
currentSplits.remove(removing)
finalSplits = [splits for splits in finalSplits if splits[0]]
while finalSplits:
nodeVal, nodes, directions = finalSplits.pop()
bottomNode = nodeDirectory[nodeVal[0]] if nodeVal else None
while nodes:
attachingNode = nodeDirectory[nodes.pop()]
attachingDir = directions.pop()
if attachingDir == 'left':
attachingNode.left = bottomNode
else:
attachingNode.right = bottomNode
bottomNode = attachingNode
return nodeDirectory[postorder[-1]] | class Solution {
int[] io; int[] po;
int n; // nth post order node
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.n = inorder.length-1; this.io = inorder; this.po = postorder;
return buildTree(0, n);
}
public TreeNode buildTree(int low, int high) {
if(n < 0 || low > high) return null;
int currNode = po[n--];
int idxInInorder = low;
TreeNode root = new TreeNode(currNode);
if(low == high) return root; // no more nodes
while(io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder
root.right = buildTree(idxInInorder+1, high);
root.left = buildTree(low, idxInInorder-1);
return root;
}
} | class Solution {
public:
TreeNode* buildTree(vector<int>& ino, vector<int>& post) {
int i1 = post.size()-1;
return solve(i1,ino,post,0,ino.size()-1);
}
TreeNode* solve(int &i,vector<int> &in,vector<int> &post,int l,int r){
if(l>r)return NULL;
int x = r;
while(post[i] != in[x]){
x--;
}
i--;
// cout<<in[x]<<" ";
TreeNode* root = new TreeNode(in[x]);
root->right = solve(i,in,post,x+1,r);
root->left = solve(i,in,post,l,x-1);
return root;
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
let postIndex = postorder.length - 1
const dfs = (left, right) => {
if (left > right) return null
const val = postorder[postIndex--]
const mid = inorder.findIndex(e => e === val)
const root = new TreeNode(val)
root.right = dfs(mid + 1, right)
root.left = dfs(left, mid - 1)
return root
}
return dfs(0, inorder.length - 1)
}; | Construct Binary Tree from Inorder and Postorder Traversal |
Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.
For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not.
Example 1:
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
Example 2:
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".
Example 3:
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Constraints:
1 <= folder.length <= 4 * 104
2 <= folder[i].length <= 100
folder[i] contains only lowercase letters and '/'.
folder[i] always starts with the character '/'.
Each folder name is unique.
| # a TrieNode class for creating new node
class TrieNode():
def __init__(self):
self.children = {}
self.main = False
# the main class
class Solution(object):
def removeSubfolders(self, folder):
node = TrieNode()
res = []
# sort the list to prevent adding the subfolder to the Trie first
folder.sort()
for dir in folder:
name = dir.split("/")
if self.addTrie(name,node):
res.append(dir)
return res
# usign the same addTrie template and modify the else part
def addTrie(self,name,node):
trie = node
for c in name:
if c not in trie.children:
trie.children[c] = TrieNode()
# if char is in trie,
else:
# check if it's the last sub folder.
if trie.children[c].main == True:
return False
trie = trie.children[c]
trie.main = True
return True | class Solution {
TrieNode root;
public List<String> removeSubfolders(String[] folder) {
List<String> res = new ArrayList<>();
Arrays.sort(folder, (a, b) -> (a.length() - b.length()));
root = new TrieNode();
for (String f : folder) {
if (insert(f)) {
res.add(f);
}
}
return res;
}
private boolean insert(String folder) {
TrieNode node = root;
char[] chs = folder.toCharArray();
for (int i = 0; i < chs.length; i++) {
char ch = chs[i];
node.children.putIfAbsent(ch, new TrieNode());
node = node.children.get(ch);
if (node.isFolder && (i+1 < chs.length && chs[i+1] == '/')) {
return false;
}
}
node.isFolder = true;
return true;
}
}
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isFolder;
} | class Solution {
public:
int check(string &s,unordered_map<string,int>&mp)
{
string temp;
temp.push_back(s[0]); //for maintaining prefix string
for(int i=1;i<s.size();i++)
{
if(s[i]=='/')
{
if(mp.count(temp)) //for checking prefix exist in map
return true;
temp+=s[i];
}
else temp+=s[i];
}
mp[s]=1; //if string doesnot exist put it in map
return false;
}
vector<string> removeSubfolders(vector<string>& folder) {
unordered_map<string,int>mp;
sort(folder.begin(),folder.end());
vector<string>ans;
for(auto it:folder)
{
if(!check(it,mp))
ans.push_back(it);
}
return ans;
}
}; | var removeSubfolders = function(folder) {
folder = folder.sort()
const result = [];
for(let i in folder){
const f = folder[i];
if(result.length == 0 || !f.startsWith(result[result.length -1] + "/"))
result.push(f);
}
return result;
}; | Remove Sub-Folders from the Filesystem |