algo_input
stringlengths 240
3.91k
| solution_py
stringlengths 10
6.72k
| solution_java
stringlengths 87
8.97k
| solution_c
stringlengths 10
7.38k
| solution_js
stringlengths 10
4.56k
| title
stringlengths 3
77
|
---|---|---|---|---|---|
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]:
Choosing to remove index 1 results in nums = [6,7,4,1].
Choosing to remove index 2 results in nums = [6,1,4,1].
Choosing to remove index 4 results in nums = [6,1,7,4].
An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.
Return the number of indices that you could choose such that after the removal, nums is fair.
Example 1:
Input: nums = [2,1,6,4]
Output: 1
Explanation:
Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
There is 1 index that you can remove to make nums fair.
Example 2:
Input: nums = [1,1,1]
Output: 3
Explanation: You can remove any index and the remaining array is fair.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: You cannot make a fair array after removing any index.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
| class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
if len(nums) == 1:
return 1
if len(nums) == 2:
return 0
prefixEven = sum(nums[2::2])
prefixOdd = sum(nums[1::2])
result = 0
if prefixEven == prefixOdd and len(set(nums)) == 1:
result += 1
for i in range(1,len(nums)):
if i == 1:
prefixOdd, prefixEven = prefixEven, prefixOdd
if i > 1:
if i % 2 == 0:
prefixEven -= nums[i-1]
prefixEven += nums[i-2]
else:
prefixOdd -= nums[i-1]
prefixOdd += nums[i-2]
if prefixOdd == prefixEven:
result += 1
return result | class Solution {
public int waysToMakeFair(int[] nums) {
/*
Idea -
have left (odd & even) & right (odd & even) odd & even sums separately
as we move each element subtract & add appropriately
*/
int count = 0;
int evenLeft = 0;
int oddLeft = 0;
int evenRight = 0;
int oddRight = 0;
// calculate the right odd & even initially since we move from 0->n
for(int i=0;i<nums.length;i++)
{
if(i%2 == 0)
{
evenRight+=nums[i];
} else{
oddRight+= nums[i];
}
}
// move from 0 -> n
for(int i=0;i<nums.length;i++)
{
// start from 1 since left at 0 index is 0 anyways & array bounds checked
if(i>0)
{
// add previous element to left count
if(i%2 == 0)
{
oddLeft +=nums[i-1];
} else{
evenLeft+=nums[i-1];
}
}
// subtract current element value from right counts so we get right count excluding the current element
if(i%2 == 0)
{
evenRight-=nums[i];
} else{
oddRight-=nums[i];
}
// if at any point we have below condition true increment count
// notice here we are adding even & odd of opposite sides here since on excluding the current element the right counterpart sum switches
// i.e if it was odd before it becomes even, else if it was even becomes odd
if(evenLeft+oddRight == oddLeft+evenRight)
{
count++;
}
}
return count;
}
} | class Solution {
public:
int waysToMakeFair(vector<int>& nums) {
//it looks a quite complicated problem but actually it is not
//the main observation here is when a element is deleted the odd sum after the element becomes the evensum and vice versa
//so we maintain two vectors left and right
vector<int> left(2,0);
vector<int> right(2,0);
//left[0],right[0] stores the sum of even indices elements to the left and right side of the element respectively
//left[1] right[1] stores the sum of odd indices elements to the left and right side of the element respectively
int ans=0; //stores the result
//first store the odd sum and even sum in right
for(int i=0;i<nums.size();i++)
{
if(i%2)
{
//odd index
right[1]+=nums[i];
}
else{
//even index
right[0]+=nums[i];
}
}
//now traverse through every element in the array and try to remove the element and check does it makes a fair array
for(int i=0;i<nums.size();i++)
{
//try to remove the element
int currOdd=right[1];
int currEven=right[0];
if(i%2)
{
//odd index , remove it from currOdd
currOdd-=nums[i];
right[1]-=nums[i]; //since it would be no longer to the right
}
else{
//even index , remove it from currEven
currEven-=nums[i];
right[0]-=nums[i];
}
//now check whether the total oddSum and the evenSum in the array are equal ?
//since we are deleting this element oddSum becomes evenSum and evenSum becomes oddSum
//check leftOdd+rightOdd==rightEven+leftEven
//left[0] is even sum to left of i
//left[1] is the odd sum to left of i
if(left[0]+currOdd==left[1]+currEven)
ans++;
//since we traverse to right add this value to the left array
(i%2) ? left[1]+=nums[i] : left[0]+=nums[i];
}
return ans;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var waysToMakeFair = function(nums) {
let oddSum = 0;
let evenSum = 0 ;
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) {
evenSum += nums[i];
} else {
oddSum += nums[i];
}
}
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) {
evenSum -= nums[i];
if (evenSum === oddSum) {
count++;
}
oddSum += nums[i];
} else {
oddSum -= nums[i];
if (evenSum === oddSum) {
count++;
}
evenSum += nums[i]
}
}
return count;
}; | Ways to Make a Fair Array |
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.
The canonical path should have the following format:
The path starts with a single slash '/'.
Any two directories are separated by a single slash '/'.
The path does not end with a trailing '/'.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Constraints:
1 <= path.length <= 3000
path consists of English letters, digits, period '.', slash '/' or '_'.
path is a valid absolute Unix path.
| class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
i = 0
while i < len(path):
if path[i] == '/':
i += 1
continue
else:
cur = ''
while i < len(path) and path[i] != '/':
cur += path[i]
i += 1
if cur == '..':
if stack:
stack.pop()
elif cur == '.' or cur == '':
i += 1
continue
else:
stack.append(cur)
return '/' + '/'.join(stack) | class Solution {
public String simplifyPath(String path) {
String[] paths = path.split("/");
Stack<String> st=new Stack<>();
for(String dir:paths){
if(dir.equals(".") || dir.length()==0) continue;
else{
if(!st.isEmpty() && dir.equals(".."))
st.pop();
else if(st.isEmpty() && dir.equals(".."))
continue;
else st.push(dir);
}
}
StringBuilder sb=new StringBuilder();
if(st.isEmpty()) return "/";
for(String s:st){
sb.append("/"); sb.append(s);
}
return sb.toString();
}
} | // Please upvote if it helps
class Solution {
public:
string simplifyPath(string path) {
stack<string> st;
string res;
for(int i = 0; i<path.size(); ++i)
{
if(path[i] == '/')
continue;
string temp;
// iterate till we doesn't traverse the whole string and doesn't encounter the last /
while(i < path.size() && path[i] != '/')
{
// add path to temp string
temp += path[i];
++i;
}
if(temp == ".")
continue;
// pop the top element from stack if exists
else if(temp == "..")
{
if(!st.empty())
st.pop();
}
else
// push the directory file name to stack
st.push(temp);
}
// adding all the stack elements to res
while(!st.empty())
{
res = "/" + st.top() + res;
st.pop();
}
// if no directory or file is present
if(res.size() == 0)
return "/";
return res;
}
}; | var simplifyPath = function(path) {
let stack=[];
path=path.split("/")
for(let i=0;i<path.length;i++){
if(path[i]==="" || path[i]===".")continue;
if(path[i]===".."){
stack.pop();
}else{
stack.push(path[i]);
}
}
//edge case
if(stack.length===0)return "/"
//edge case
let string="";
for(let j=0;j<stack.length;j++){
string+="/"+stack[j];
}
return string;
}; | Simplify Path |
You are given an array of integers nums (0-indexed) and an integer k.
The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
Return the maximum possible score of a good subarray.
Example 1:
Input: nums = [1,4,3,7,4,5], k = 3
Output: 15
Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.
Example 2:
Input: nums = [5,5,4,5,4,1,1,1], k = 0
Output: 20
Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 2 * 104
0 <= k < nums.length
| class Solution:
def nextSmallerElement(self, nums):
nextSmaller = [None] * len(nums)
stack = [[-sys.maxsize, -1]]
for i in range(len(nums)-1, -1, -1):
while nums[i] <= stack[-1][0]:
stack.pop()
nextSmaller[i] = stack[-1][1]
stack.append([nums[i], i])
return nextSmaller
def previousSmallerElement(self, nums):
previousSmaller = [None] * len(nums)
stack = [[-sys.maxsize, -1]]
for i in range(len(nums)):
while nums[i] <= stack[-1][0]:
stack.pop()
previousSmaller[i] = stack[-1][1]
stack.append([nums[i], i])
return previousSmaller
def maximumScore(self, nums: List[int], k: int) -> int:
nextSmaller = self.nextSmallerElement(nums)
previousSmaller = self.previousSmallerElement(nums)
score = 0
for idx, num in enumerate(nums):
# previousSmaller[idx] (let's say i) and nextSmaller[idx] (let's say j) ensures that the element present at idx is the minimum in range (i -> j)
i = previousSmaller[idx]
i += 1
j = nextSmaller[idx]
if j == -1:
j = len(nums)
j -= 1
if i <= k <= j:
score = max(score, num * (j-i+1))
return score
| class Solution {
public int maximumScore(int[] nums, int k) {
int n = nums.length;
int i = k - 1, j = k + 1;
int min = nums[k];
int ans = min;
while(i >= 0 || j < n) {
int v1 = 0, v2 = 0;
int min1 = min, min2 = min;
if(i >= 0) {
min1 = Math.min(min, nums[i]);
v1 = min1 * (j - i);
}
if(j < n) {
min2 = Math.min(min, nums[j]);
v2 = min2 * (j - i);
}
if(v1 > v2) {
--i;
ans = Math.max(v1, ans);
min = Math.min(min1, min);
}
else {
++j;
ans = Math.max(ans, v2);
min = Math.min(min, min2);
}
}
return ans;
}
} | class Solution {
public:
int maximumScore(vector<int>& nums, int k) {
nums.push_back(0);
stack<int> st ;
int n = nums.size(), res = 0;
for(int i=0; i<n ; i++){
while(!st.empty() && nums[st.top()] >= nums[i]){
int height = nums[st.top()];
st.pop();
int left = st.empty() ? -1: st.top();
if(k < i && k > left) res = max(height* (i-left-1), res);
}
st.push(i);
}
return res;
}
}; | /*
JAVASCRIPT
*/
var maximumScore = function(nums, k) {
// iterate to the left to update the minimum value at each index
let min = nums[k];
for (let i = k - 1; i >= 0; i--) {
min = Math.min(min, nums[i]);
nums[i] = min;
}
// iterate to the right to update the minimum value at each index
min = nums[k];
for (let i = k + 1; i < nums.length; i++) {
min = Math.min(min, nums[i]);
nums[i] = min;
}
// start with 2 pointers at opposite ends of nums
let left = 0;
let right = nums.length - 1;
let bestScore = 0;
while (left <= right) {
bestScore = Math.max(bestScore, Math.min(nums[left], nums[right]) * (right - left + 1));
// first to check if either pointer is at k
// if it is at k then we must move the other pointer inwards
if (left === k) {
right--;
} else if (right === k) {
left++
// if neither index is at k move the pointer
// that is smaller inwards
} else if (nums[left] < nums[right]) {
left++;
} else {
right--;
}
}
return bestScore;
}; | Maximum Score of a Good Subarray |
Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
| from heapq import heappop, heapify
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
counter = collections.Counter(arr)
min_heap = [(count, num) for num, count in counter.items()]
heapify(min_heap)
while k > 0:
count, num = min_heap[0]
if count > k:
break
heappop(min_heap)
k -= count
return len(min_heap) | class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
Map<Integer,Integer> freqMap = new HashMap<>();
for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1);
PriorityQueue<Integer> pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2)));
pq.addAll(freqMap.keySet());
while(k>0 && !pq.isEmpty()){
int element = pq.poll();
int toBeDeleted = Math.min(k,freqMap.get(element));
k-=toBeDeleted;
if(toBeDeleted<freqMap.get(element))
pq.add(element);
}
return pq.size();
}
} | class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
int ans;
unordered_map<int,int> mp;
for(int i=0; i<arr.size(); i++){
mp[arr[i]]++;
}
priority_queue< int, vector<int>, greater<int>> pq;
for(auto it : mp){
pq.push(it.second);
}
while(k>0){
k-= pq.top();
if(k>=0){
pq.pop();
}
}
return pq.size();
}
}; | var findLeastNumOfUniqueInts = function(arr, k) {
var hsh = {};
var instance = {}; // store set with index # of occurence
var count = 0;
for (var i = 0; i < arr.length; i++)
{
if (hsh[arr[i]] == null)
{
count ++;
hsh[arr[i]] = 1;
if (instance[1] == null)
{
var intro = new Set();
intro.add(arr[i]);
instance[1] = intro;
}
else
{
instance[1].add(arr[i]);
}
}
else
{
hsh[arr[i]] ++;
var numTimes = hsh[arr[i]];
instance[numTimes - 1].delete(arr[i]);
if (instance[numTimes] == null)
{
instance[numTimes] = new Set();
instance[numTimes].add(arr[i]);
}
else
{
instance[numTimes].add(arr[i]);
}
}
}
var removenum = 0;
for (key in instance)
{
var instanceKey = instance[key].size;
if (k == 0)
{
break;
}
else if (k >= key*instanceKey)
{
k -= key*instanceKey;
count -= instanceKey;
}
else
{
count -= Math.floor(k/key);
break;
}
}
return count;
}; | Least Number of Unique Integers after K Removals |
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
Each second, you may perform one of the following operations:
Move the pointer one character counterclockwise or clockwise.
Type the character the pointer is currently on.
Given a string word, return the minimum number of seconds to type out the characters in word.
Example 1:
Input: word = "abc"
Output: 5
Explanation:
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
Example 2:
Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
Example 3:
Input: word = "zjpc"
Output: 34
Explanation:
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
Constraints:
1 <= word.length <= 100
word consists of lowercase English letters.
| class Solution:
def minTimeToType(self, word: str) -> int:
prev = "a"
res = 0
for c in word:
gap = abs(ord(c)-ord(prev))
res += min(gap, 26 - gap)
prev = c
return res + len(word) | class Solution {
public int minTimeToType(String word) {
char prevChar = 'a';
int totalTime = word.length();
for(int i = 0; i < word.length(); i++){
char currChar = word.charAt(i);
int diff = Math.abs(currChar - prevChar);
totalTime += Math.min(diff, 26 - diff);
prevChar = currChar;
}
return totalTime;
}
} | class Solution {
public:
int minTimeToType(string word) {
int res = word.size(), point = 'a';
for (auto ch : word) {
res += min(abs(ch - point), 26 - abs(point - ch));
point = ch;
}
return res;
}
}; | var minTimeToType = function(word) {
let ops = 0;
let cur = 'a';
for(const char of word) {
const diff = Math.abs(cur.charCodeAt(0) - char.charCodeAt(0));
if(diff > 13) {
ops += 26 - diff + 1;
} else {
ops += diff + 1;
}
cur = char;
}
return ops;
}; | Minimum Time to Type Word Using Special Typewriter |
Given a 0-indexed n x n integer matrix grid, return the number of pairs (Ri, Cj) such that row Ri and column Cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
| class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
m = defaultdict(int)
cnt = 0
for row in grid:
m[str(row)] += 1
for i in range(len(grid[0])):
col = []
for j in range(len(grid)):
col.append(grid[j][i])
cnt += m[str(col)]
return cnt | class Solution {
public int equalPairs(int[][] grid) {
HashMap<String, Integer> map = new HashMap<>();
int row = grid.length;
int col = grid.length;
for(int i = 0; i < row; i++){
String res = "";
for(int j = 0; j < col; j++){
res += "-" + grid[i][j];
}
map.put(res, map.getOrDefault(res, 0) + 1);
}
int cnt = 0;
for(int j = 0; j < col; j++){
String res = "";
for(int i = 0; i < row; i++){
res += "-" + grid[i][j];
}
cnt += map.getOrDefault(res, 0);
}
return cnt;
}
} | class Solution {
public:
int equalPairs(vector<vector<int>>& grid)
{
// Number to store the count of equal pairs.
int ans = 0;
map<vector<int>, int> mp;
// Storing each row int he map
for (int i = 0; i < grid.size(); i++)
mp[grid[i]]++;
for (int i = 0; i < grid[0].size(); i++)
{
vector<int> v;
// extracting column in a vector.
for (int j = 0; j < grid.size(); j++)
v.push_back(grid[j][i]);
// Add the number of times that column appeared as a row.
ans += mp[v];
}
// Return the number of count
return ans;
}
}; | var equalPairs = function(grid) {
let n = grid.length
let count = 0;
let map = new Map()
//making rowArray
for(let row = 0; row < n; row++){
let temp = []
for(let col = 0; col < n; col++){
temp.push(grid[row][col])
}
temp = temp.join()
if(map.has(temp)){
let tempCount = map.get(temp)
map.set(temp, tempCount+1)
}
else{
map.set(temp, 1)
}
}
for(let col = 0; col < n; col++){
let temp = []
for(let row = 0; row < n; row++){
temp.push(grid[row][col])
}
temp = temp.join()
if(map.has(temp)){
count += map.get(temp)
}
}
return count;
}; | Equal Row and Column Pairs |
A magical string s consists of only '1' and '2' and obeys the following rules:
The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.
The first few elements of s is s = "1221121221221121122β¦β¦". If we group the consecutive 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the occurrence sequence is s itself.
Given an integer n, return the number of 1's in the first n number in the magical string s.
Example 1:
Input: n = 6
Output: 3
Explanation: The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 105
| class Solution:
def magicalString(self, n: int) -> int:
queue, ans, i = deque([2]), 1, 1
while i <= n - 2:
m = queue.popleft()
ans += (m == 1)
queue.extend([1 + (i % 2 == 0)] * m)
i += 1
return ans | class Solution {
public int magicalString(int n) {
if(n <= 3)
return 1;
Magical m = new Magical();
int ans = 1;
for(int i = 3; i < n; ++i)
if(m.next() == 1)
++ans;
return ans;
}
}
class Magical{
private Deque<Integer> nums;
private int n;
public Magical(){
nums = new ArrayDeque<>();
nums.offerLast(1);
nums.offerLast(1);
n = 1;
}
public int next(){
if(n-- < 0){
int c = nums.pollFirst();
n = c - 2;
int curr = 3 - nums.peekLast();
for(; c > 0; --c)
nums.offerLast(curr);
return curr;
}
return nums.peekLast();
}
} | class Solution {
public:
int magicalString(int n) {
string s="122";
int sz=3;
int start=2,lastDig=2;
while(sz<n){
int cnt=s[start++]-'0';
int currDig=(lastDig==2)?1:2;
for(int i=0;i<cnt;i++){
s.push_back('0'+currDig);
sz++;
}
lastDig=currDig;
}
int ans=0;
for(int i=0;i<n;i++){
if(s[i]=='1'){
ans++;
}
}
return ans;
}
}; | var magicalString = function(n) {
const stack = ['1', '2', '2'];
let magic = 2;
while (stack.length < n) {
const count = stack[magic++];
const last = stack[stack.length - 1];
const addStr = last === '1' ? '2' : '1';
for (let n = 1; n <= count; n++) stack.push(addStr);
}
return stack.slice(0, n).filter(str => str === '1').length;
}; | Magical String |
Design a text editor with a cursor that can do the following:
Add text to where the cursor is.
Delete text from where the cursor is (simulating the backspace key).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.
void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
Example 1:
Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
Constraints:
1 <= text.length, k <= 40
text consists of lowercase English letters.
At most 2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
Follow-up: Could you find a solution with time complexity of O(k) per call?
| class TextEditor:
def __init__(self):
self.s = ''
self.cursor = 0
def addText(self, text: str) -> None:
self.s = self.s[:self.cursor] + text + self.s[self.cursor:]
self.cursor += len(text)
def deleteText(self, k: int) -> int:
new_cursor = max(0, self.cursor - k)
noOfChars = k if self.cursor - k >= 0 else self.cursor
self.s = self.s[:new_cursor] + self.s[self.cursor:]
self.cursor = new_cursor
return noOfChars
def cursorLeft(self, k: int) -> str:
self.cursor = max(0, self.cursor - k)
start = max(0, self.cursor-10)
return self.s[start:self.cursor]
def cursorRight(self, k: int) -> str:
self.cursor = min(len(self.s), self.cursor + k)
start = max(0, self.cursor - 10)
return self.s[start:self.cursor] | class TextEditor {
StringBuilder res;
int pos=0;
public TextEditor() {
res = new StringBuilder();
}
public void addText(String text) {
res.insert(pos,text);
pos += text.length();
}
public int deleteText(int k) {
int tmp = pos;
pos -= k;
if(pos<0) pos=0;
res.delete(pos,tmp);
return tmp-pos;
}
public String cursorLeft(int k) {
pos-=k;
if(pos<0) pos = 0;
if(pos<10) return res.substring(0,pos);
return res.substring(pos-10,pos);
}
public String cursorRight(int k) {
pos+=k;
if(pos>res.length()) pos = res.length();
if(pos<10) return res.substring(0,pos);
return res.substring(pos-10,pos);
}
} | class TextEditor {
stack<char> left;
stack<char> right;
public:
TextEditor() {
}
void addText(string text) {
for(auto &c : text){
left.push(c);
}
}
int deleteText(int k) {
int cnt=0;
while(!left.empty() and k>0){
left.pop();
cnt++;
k--;
}
return cnt;
}
string cursorLeft(int k) {
while(!left.empty() and k>0){
char c = left.top();left.pop();
right.push(c);
k--;
}
// returning the last min(10, len) characters to the left of the cursor
return cursorShiftString();
}
string cursorRight(int k) {
while(!right.empty() and k>0){
char c = right.top();right.pop();
left.push(c);
k--;
}
// returning the last min(10, len) characters to the left of the cursor
return cursorShiftString();
}
// function to return the last min(10, len) characters to the left of the cursor
string cursorShiftString(){
string rtn = "";
int cnt=10;
while(!left.empty() and cnt>0){
char c = left.top();left.pop();
rtn += c;
cnt--;
}
reverse(rtn.begin(),rtn.end());
for(int i=0;i<rtn.size();i++){
left.push(rtn[i]);
}
return rtn;
}
}; | var TextEditor = function() {
this.forward = [];
this.backward = [];
};
/**
* @param {string} text
* @return {void}
*/
TextEditor.prototype.addText = function(text) {
for (let letter of text) {
this.forward.push(letter);
}
};
/**
* @param {number} k
* @return {number}
*/
TextEditor.prototype.deleteText = function(k) {
let deleted = 0;
while (this.forward.length && deleted < k) {
this.forward.pop();
deleted++;
}
return deleted;
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorLeft = function(k) {
let moved = 0;
while (this.forward.length && moved < k) {
this.backward.push(this.forward.pop());
moved++;
}
return toTheLeft(this.forward);
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorRight = function(k) {
let moved = 0;
while (moved < k && this.backward.length) {
this.forward.push(this.backward.pop());
moved++;
}
return toTheLeft(this.forward);
};
function toTheLeft (arr) {
let letters = [];
for (let i = Math.max(0, arr.length - 10); i < arr.length; i++) {
letters.push(arr[i]);
}
let res = letters.join("");
return res;
} | Design a Text Editor |
You are given a 0-indexed integer array nums. In one operation, you may do the following:
Choose two integers in nums that are equal.
Remove both integers from nums, forming a pair.
The operation is done on nums as many times as possible.
Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.
Example 1:
Input: nums = [1,3,2,1,3,2,2]
Output: [3,1]
Explanation:
Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].
Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].
Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].
No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.
Example 2:
Input: nums = [1,1]
Output: [1,0]
Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].
No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.
Example 3:
Input: nums = [0]
Output: [0,1]
Explanation: No pairs can be formed, and there is 1 number leftover in nums.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
| class Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
ans = [0] * 2
c = Counter(nums)
for v in c.values():
ans[0] += (v // 2)
ans[1] += (v % 2)
return ans | class Solution {
public int[] numberOfPairs(int[] nums) {
if(nums.length == 1)
return new int[]{0,1};
HashSet<Integer> set = new HashSet<>();
int pairs=0;
for(int i : nums){
if(!set.contains(i)){
set.add(i); // No pair present
}else{
set.remove(i); // Pair found
pairs++;
}
}
return new int[]{pairs,set.size()};
}
} | class Solution {
public:
//store the frequency of each of the number in the map and
//then return the answer as sum all the values dividing 2 and
//sum all by taking reminder of 2
vector<int> numberOfPairs(vector<int>& nums) {
unordered_map<int, int> mp;
for(auto i: nums) mp[i]++;
int c1 = 0, c2 = 0;
for(auto m: mp){
c1 += m.second/2;
c2 += m.second%2;
}
return {c1, c2};
}
}; | /**
* @param {number[]} nums
* @return {number[]}
*/
var numberOfPairs = function(nums) {
let pairs = 0;
const s = new Set();
for (const num of nums) {
if (s.has(num)) {
pairs += 1;
s.delete(num);
} else {
s.add(num);
}
}
return [pairs, nums.length - pairs * 2];
}; | Maximum Number of Pairs in Array |
You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
Constraints:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
| class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
lookup = {}
def f(ind, buy, lookup):
if ind == n: return 0
if (ind, buy) in lookup: return lookup[(ind, buy)]
profit = 0
if buy:
profit = max(-prices[ind] + f(ind+1,0,lookup), f(ind+1, 1,lookup))
else:
profit = max(prices[ind] + f(ind+1,1,lookup) - fee, f(ind+1, 0,lookup))
lookup[(ind,buy)] = profit
return lookup[(ind,buy)]
return f(0, 1,lookup) | class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] dp = new int[prices.length][2];
for (int[] a : dp) {
a[0] = -1;
a[1] = -1;
}
return profit(prices, fee, 0, 1, dp);
}
public int profit(int[] prices, int fee, int i, int buy, int[][] dp) {
if (i == prices.length) {
return 0;
}
if (dp[i][buy] != -1) {
return dp[i][buy];
}
int maxProfit = 0;
if (buy == 1) {
int yesBuy = profit(prices, fee, i + 1, 0, dp) - prices[i];
int noBuy = profit(prices, fee, i + 1, 1, dp);
maxProfit = Math.max(yesBuy, noBuy);
} else {
int yesSell = prices[i] - fee + profit(prices, fee, i + 1, 1, dp);
int noSell = profit(prices, fee, i + 1, 0, dp);
maxProfit = Math.max(yesSell, noSell);
}
return dp[i][buy] = maxProfit;
}
} | class Solution {
public:
int ans=0;
int f(vector<int>&prices,int i,int buy,vector<vector<int>>&dp,int fee){
if(i==prices.size())return 0;
if(dp[i][buy]!=-1)return dp[i][buy];
int take=0;
if(buy){
take=max(-prices[i]+f(prices,i+1,0,dp,fee),f(prices,i+1,1,dp,fee));
}
else{
take=max(prices[i]+f(prices,i+1,1,dp,fee)-fee,f(prices,i+1,0,dp,fee));
}return dp[i][buy]=take;
}
int maxProfit(vector<int>& prices, int fee) {
vector<vector<int>>dp(prices.size(),vector<int>(2,-1));
return f(prices,0,1,dp,fee);
}
}; | /**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
let purchase = -1*prices[0];//If we purchase on 0th day
let sell=0;//If we sell on 0th day
let prevPurchase;
for(let i=1;i<prices.length;i++){
prevPurchase = purchase;
purchase = Math.max(purchase,sell-prices[i]);//If we purchase on ith day
sell = Math.max(sell,prevPurchase+prices[i]-fee);//If we sell on ith day
}
return sell;//If must return the best price whenever we sold stock because then only we can be at max profit.
}; | Best Time to Buy and Sell Stock with Transaction Fee |
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
For example, the word "apple" becomes "applema".
If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on.
Return the final sentence representing the conversion from sentence to Goat Latin.
Example 1:
Input: sentence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:
Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Constraints:
1 <= sentence.length <= 150
sentence consists of English letters and spaces.
sentence has no leading or trailing spaces.
All the words in sentence are separated by a single space.
| class Solution:
def toGoatLatin(self, sentence: str) -> str:
wordList, result, index = sentence.split(' '), "", 1
for word in wordList:
if index > 1:
result += " "
firstLetter = word[0]
if firstLetter in 'aeiouAEIOU':
result += word + "ma"
else:
result += word[1:] + firstLetter + "ma"
for i in range(index):
result += 'a'
index += 1
return result | class Solution {
public String toGoatLatin(String sentence) {
StringBuffer sb = new StringBuffer();
StringBuffer temp = new StringBuffer("a"); // temporary stringbuffer
for(String str : sentence.split(" ")) {
if(beginsWithConsonant(str)) {
sb.append(str.substring(1)); // removing the first letter
sb.append(str.charAt(0)); // appending it to the end
} else {
sb.append(str);
}
sb.append("ma"); // appending "ma" to the end of the word (common operation)
sb.append(temp); // adding one letter 'a' to the end of each word
// the first word gets "a" added to the end,
// the second word gets "aa" added to the end,
// and so on.
temp.append("a"); // increasing the a's for every word
sb.append(" "); // to put space between words
}
return sb.toString().trim(); // using trim() to remove the one extra space from the end of string.
}
public boolean beginsWithConsonant(String str) {
return "aeiou".indexOf(str.toLowerCase().charAt(0)) == -1;
}
} | class Solution {
public:
string toGoatLatin(string sentence) {
sentence += ' ';
vector<string> Words;
string TEMP, SOL, A = "a";
for (int i = 0; i < sentence.size(); ++i)
{
if (sentence[i] == ' ')
{
Words.push_back(TEMP);
TEMP = "";
}
else
TEMP += sentence[i];
}
for (string V : Words)
{
char TMP = tolower(V[0]);
if (TMP == 'a' || TMP == 'e' || TMP == 'i' || TMP == 'o' || TMP == 'u')
V += "ma";
else
{
TMP = V[0];
V.erase(0, 1);
V += TMP;
V += "ma";
}
V += A;
A += 'a';
SOL += V + ' ';
}
SOL.erase(SOL.size() - 1, 1);
return SOL;
}
}; | /**
* @param {string} S
* @return {string}
*/
var toGoatLatin = function(S) {
let re = /[aeiou]/gi
let word = S.split(' ')
let add = 0
let arr = []
for(let i= 0; i < word.length; i++) {
if(!word[i].substring(0,1).match(re)) {
arr = word[i].split('')
let letter = arr.shift()
arr.push(letter)
word[i] = arr.join('')
}
// have to append 'ma' regardless if it starts with a vowel
word[i] += 'ma'
// append 'a' number of times as the index + 1
add = i+1
while(add >0) {
word[i] += 'a'
add--
}
}
return word.join(' ')
}; | Goat Latin |
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 104].
0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
| class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
cur, stack, minDiff, prev = root, [], 10**5, -10**5
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
node = stack.pop()
minDiff = min(minDiff, node.val - prev)
prev = node.val
cur = node.right
return minDiff | class Solution {
public int getMinimumDifference(TreeNode root) {
Queue<Integer> queue=new PriorityQueue<>();
Queue<TreeNode> nodesQueue=new LinkedList<>();
int min=Integer.MAX_VALUE;
if(root==null)
return 0;
nodesQueue.add(root);
while(!nodesQueue.isEmpty())
{
TreeNode node=nodesQueue.poll();
queue.add(node.val);
if(node.left!=null)
{
nodesQueue.add(node.left);
}
if(node.right!=null)
{
nodesQueue.add(node.right);
}
}
int prev=queue.poll();
while(!queue.isEmpty())
{
int current=queue.poll();
int absValue=Math.abs(current-prev);
prev=current;
min=Math.min(min,absValue);
}
return min;
}
} | class Solution {
TreeNode* pre = nullptr;
int minimum = std::numeric_limits<int>:: max();
public:
void inorder(TreeNode* node) {
if (!node) return;
inorder(node->left);
if(pre) {
minimum = min(node->val - pre->val, minimum);
}
pre = node;
inorder(node->right);
}
int getMinimumDifference(TreeNode* root) {
inorder(root);
return minimum;
}
}; | var getMinimumDifference = function(root) {
let order = inOrder(root, []);
let diff = Math.abs(order[1] - order[0]);
for(let i=0;i<order.length;i++) {
for(let j=i+1;j<order.length;j++) {
if(Math.abs(order[i] - order[j]) < diff) diff = Math.abs(order[i] - order[j])
}
}
return diff;
};
const inOrder = (root, order) => {
if(!root) return null;
inOrder(root.left, order);
order.push(root.val);
inOrder(root.right, order);
return order;
} | Minimum Absolute Difference in BST |
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Example 1:
Input: root = [2,1,3]
Output: [2,1,3]
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The input tree is guaranteed to be a binary search tree.
| class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string.
"""
if not root:
return ""
res = []
def dfs(node):
res.append(str(node.val))
if node.left:
dfs(node.left)
if node.right:
dfs(node.right)
dfs(root)
return ','.join(res)
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree.
"""
if len(data) == 0:
return []
splitdata = data.split(",")
preorder = []
for item in splitdata:
preorder.append(int(item))
inorder = sorted(preorder)
hash_map = {}
for i in range(len(inorder)):
hash_map[inorder[i]] = i
def helper(preorder, pstart, pend, inorder, istart, iend):
if pstart > pend:
return None
elif pstart == pend:
return TreeNode(preorder[pstart])
root = TreeNode(preorder[pstart])
rootindex = hash_map[preorder[pstart]]
numleft = rootindex - istart
root.left = helper(preorder, pstart+1, pstart + numleft, inorder, istart,rootindex-1 )
root.right = helper(preorder, pstart + numleft +1, pend, inorder, rootindex +1, iend)
return root
return (helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1)) | public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder string = new StringBuilder();
traverse(root, string);
return string.toString();
}
private void traverse(TreeNode root, StringBuilder string){
if(root == null) return;
string.append(root.val).append(",");
traverse(root.left, string);
traverse(root.right, string);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.isEmpty()) return null;
String[] dataArr = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(dataArr[0]));
for(int i = 1; i < dataArr.length; i++)
insert(Integer.parseInt(dataArr[i]), root);
return root;
}
private void insert(int digit, TreeNode root){
if(digit > root.val){
if(root.right != null)
insert(digit, root.right);
else
root.right = new TreeNode(digit);
} else {
if(root.left != null)
insert(digit, root.left);
else
root.left = new TreeNode(digit);
}
}
} | class Codec
{
public:
string pre(TreeNode * root)
{
if(root==NULL)
return "";
int temp = root->val;
string tempz = to_string(temp);
string l = pre(root->left);
string r = pre(root->right);
return (tempz + "," + l + "," + r);
}
vector<int> parse_string(string data)
{
vector<int> ans;
string temp = "";
int n=data.size();
for(int i=0;i<n; ++i)
{
if(data[i]==',')
{
if(temp.size()==0)
continue;
else
{
int val = stoi(temp);
ans.push_back(val);
temp="";
}
}
else
temp += data[i];
}
return ans;
}
TreeNode * make_tree(vector<int>& preorder, int min_val, int max_val, int& preorder_idx, int n)
{
if(preorder_idx == n)
return NULL;
int val = preorder[preorder_idx];
if(min_val <= val and val <= max_val)
{
TreeNode * curr = new TreeNode(val);
preorder_idx++;
curr->left = make_tree(preorder, min_val, val-1, preorder_idx, n);
curr->right = make_tree(preorder, val+1, max_val, preorder_idx, n);
return curr;
}
else
return NULL;
}
string serialize(TreeNode* root)
{
string traversal = pre(root);
//cout<<traversal<<endl;
return traversal;
}
TreeNode* deserialize(string data)
{
if(data.size()==0)
return NULL;
vector<int> traversal = parse_string(data);
// for(auto x:traversal)
// cout<<x<<" ";
int preorder_idx = 0;
TreeNode * root = make_tree(traversal, INT_MIN, INT_MAX, preorder_idx, traversal.size());
return root;
}
}; | ;/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root) {
// Using Preorder traversal to create a string of BST
// Preorder works in following way
// root -> left -> right
let preorder = [];
function dfs(node) {
if (node === null) return;
// Get root value
preorder.push(node.val);
// Get All the Left values
dfs(node.left);
// Get all the right values
dfs(node.right);
}
// call it with root
dfs(root)
// Turn into string and return it
return preorder.join(',')
};
/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
if (data === "") return null;
// Get numbers array from a string
const preorder = data.split(',').map(Number);
// using -Infinity and +Infinity as placeholder check
function recur(lower = -Infinity, upper = Infinity) {
// This condition useful for when we are filling left side of tree it'll avoid all the values greater then then its upper value by putting null init.
if (preorder[0] < lower || preorder[0] > upper) return null;
// If preorder become empty
if (preorder.length === 0) return null;
// Create a root node [shift method will change the original array]
const root = new TreeNode(preorder.shift());
// Here for left side of tree, we are using current root node's value as 'upper bound' (so higher values ignored).
root.left = recur(lower, root.val);
// Same as above for right side we are using root node's values as 'lower bound' (so lower values ignored);
root.right = recur(root.val, upper);
return root;
}
// Final root will be out BST
return recur();
};
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/ | Serialize and Deserialize BST |
You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:
The ith (0-indexed) request arrives.
If all servers are busy, the request is dropped (not handled at all).
If the (i % k)th server is available, assign the request to that server.
Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.
You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.
Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.
Example 1:
Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]
Output: [1]
Explanation:
All of the servers start out available.
The first 3 requests are handled by the first 3 servers in order.
Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.
Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.
Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.
Example 2:
Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
Output: [0]
Explanation:
The first 3 requests are handled by first 3 servers.
Request 3 comes in. It is handled by server 0 since the server is available.
Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.
Example 3:
Input: k = 3, arrival = [1,2,3], load = [10,12,11]
Output: [0,1,2]
Explanation: Each server handles a single request, so they are all considered the busiest.
Constraints:
1 <= k <= 105
1 <= arrival.length, load.length <= 105
arrival.length == load.length
1 <= arrival[i], load[i] <= 109
arrival is strictly increasing.
| class Solution:
def busiestServers(self, k: int, A: List[int], B: List[int]) -> List[int]:
available = list(range(k)) # already a min-heap
busy = []
res = [0] * k
for i, a in enumerate(A):
while busy and busy[0][0] <= a: # these are done, put them back as available
_, x = heapq.heappop(busy)
heapq.heappush(available, i + (x-i)%k) # invariant: min(available) is at least i, at most i+k-1
if available:
j = heapq.heappop(available) % k
heapq.heappush(busy, (a+B[i],j))
res[j] += 1
a = max(res)
return [i for i in range(k) if res[i] == a] | class Solution {
public List<Integer> busiestServers(int k, int[] arrival, int[] load) {
// use a tree to track available servers
TreeSet<Integer> availableServerIdxs = new TreeSet<Integer>();
for (int num = 0; num < k; num++) {
availableServerIdxs.add(num);
}
// use a PQ to maintain the availability based on curTime + loadTime and the server index = idx%k
Queue<int[]> runningServers = new PriorityQueue<>((a, b)->(a[0] - b[0]));
int[] serverHandledReqCount = new int[k];
for (int idx = 0; idx < arrival.length; idx++) {
int newTaskCompletionTime = arrival[idx];
// peek if the server's work time is less than or equal to the next task completion time, if it is poll those servers from the running servers queue and add the index of that server to the availableServerIdxs treeSet
while (!runningServers.isEmpty() && runningServers.peek()[0] <= newTaskCompletionTime) {
int freedServer = runningServers.poll()[1];
availableServerIdxs.add(freedServer);
}
if (availableServerIdxs.size() == 0) continue; // all busy
// to always get the last freed server
Integer serverIdx = availableServerIdxs.ceiling(idx % k);
if (serverIdx == null) {
serverIdx = availableServerIdxs.first();
}
serverHandledReqCount[serverIdx]++;
availableServerIdxs.remove(serverIdx);
runningServers.offer(new int[] {newTaskCompletionTime + load[idx], serverIdx});
}
int max = Arrays.stream(serverHandledReqCount).max().getAsInt();
return IntStream.range(0, k).filter(i -> serverHandledReqCount[i] == max).boxed().collect(Collectors.toList());
//return findMaxesInCounter(counter);
}
/*
private List<Integer> findMaxesInCounter(int[] counter) {
int max = 0;
for (int i = 0; i < counter.length; i++) {
max = Math.max(max, counter[i]);
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < counter.length; i++) {
if (counter[i] == max) {
result.add(i);
}
}
return result;
}
*/
} | class Solution {
public:
vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {
int n = (int)arrival.size();
set<int> freeServers;
for (int i = 0; i < k; i++) freeServers.insert(i);
vector<int> serverTaskCount(k, 0);
set<pair<int, int>> workingServers; // [end time, server index]
for (int i = 0; i < n; i++) {
int startTime = arrival[i];
while (!workingServers.empty() && workingServers.begin()->first <= startTime) {
auto s = *workingServers.begin();
workingServers.erase(workingServers.begin());
freeServers.insert(s.second);
}
if (freeServers.empty()) continue;
int serverIndex = -1;
auto it = freeServers.lower_bound(i % k);
if (it == freeServers.end()) {
serverIndex = *freeServers.begin();
freeServers.erase(freeServers.begin());
} else {
serverIndex = *it;
freeServers.erase(it);
}
workingServers.insert({startTime + load[i], serverIndex});
serverTaskCount[serverIndex]++;
//printf("Task %d (%d, %d) assigned to server %d\n", i, startTime, load[i], serverIndex);
}
// for (auto x : serverTaskCount) cout << x << " ";
// cout << endl;
vector<int> ret;
int maxVal = *max_element(serverTaskCount.begin(), serverTaskCount.end());
for (int i = 0; i < k; i++)
if (maxVal == serverTaskCount[i]) ret.push_back(i);
return ret;
}
}; | var busiestServers = function(k, arrival, load) {
let loadMap = {};
let pq = new MinPriorityQueue({ compare: (a,b) => a[1] - b[1] });
let availableServers = new Set(new Array(k).fill(0).map((_, index) => index));
for (let i = 0; i < arrival.length; i++) {
// calc end time
let end = arrival[i] + load[i];
// bring server back
while (pq.front()?.[1] <= arrival[i]) {
const [server] = pq.dequeue();
availableServers.add(server);
}
let server = i % k;
// drop if no available server
if (availableServers.size === 0) continue;
// find the next avaiable sever
while (!availableServers.has(server)) {
server++;
if (server === k + 1) {
server = 0;
}
}
// record the load
if (!loadMap[server]) {
loadMap[server] = 0;
}
loadMap[server]++;
availableServers.delete(server);
pq.enqueue([server, end]);
}
let res = [];
let sorted = Object.entries(loadMap).sort((a,b) => b[1] - a[1]);
let max = sorted[0][1];
let i = 0;
while (sorted[i]?.[1] === max) {
res.push(+sorted[i++][0]);
}
return res;
}; | Find Servers That Handled Most Number of Requests |
You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].
Return any rearrangement of nums that meets the requirements.
Example 1:
Input: nums = [1,2,3,4,5]
Output: [1,2,4,5,3]
Explanation:
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
Example 2:
Input: nums = [6,2,0,9,7]
Output: [9,7,6,2,0]
Explanation:
When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
Constraints:
3 <= nums.length <= 105
0 <= nums[i] <= 105
| class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums) -1):
pre = nums[i-1]
current = nums[i]
next = nums[i+1]
# If block will run when we meet 1 2 3 or 6 4 2
if (pre < current < next) or (pre > current > next):
# Swap next and current
# For example:
# 1 2 3 -> 1 3 2
# 6 4 2 -> 6 2 4
nums[i+1], nums[i] = nums[i], nums[i+1]
return nums | class Solution {
public int[] rearrangeArray(int[] nums) {
Arrays.sort(nums);
// sort in wave format
for(int i = 0;i<nums.length-1;i+=2){
int temp = nums[i];
nums[i] = nums[i+1];
nums[i+1] = temp;
}
return nums;
}
} | //Approach-1 (Using sorting O(nlogn))
/*
If you make sure that
nums[i-1] < nums[i] > nums[i+1]
You are good to go.
So, just sort the input and choose wisely to satisfy above condition.
Example :
[6,2,0,9,7]
sort it : [0, 2, 6, 7, 9]
result : [0, _, 2, _, 6] - 1st loop (fill alternaltely)
result : [0, 7, 2, 9, 6] - 2nd loop (fill next larger numbers from nums to result in spaces left)
*/
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int n = nums.size();
sort(begin(nums), end(nums));
vector<int> result(n);
int j = 0;
int i = 0;
for(; i < n && j < n; i++, j += 2) //alternately fill so that you leave one space in between for large number
result[j] = nums[i];
j = 1;
for(; i < n && j < n; i++, j += 2) //filter the large number in spaces between that we left above
result[j] = nums[i];
return result;
}
}; | var rearrangeArray = function(nums) {
let arr=[], res=[]
for(let q of nums) arr[q]= 1
let l=0, r=arr.length-1
while(l<=r){
while(!arr[l])l++
while(!arr[r])r--
if(l<=r)res.push(l++)
if(l<=r)res.push(r--)
}
return res
}; | Array With Elements Not Equal to Average of Neighbors |
Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.
You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.
Return the maximum number of consecutive floors without a special floor.
Example 1:
Input: bottom = 2, top = 9, special = [4,6]
Output: 3
Explanation: The following are the ranges (inclusive) of consecutive floors without a special floor:
- (2, 3) with a total amount of 2 floors.
- (5, 5) with a total amount of 1 floor.
- (7, 9) with a total amount of 3 floors.
Therefore, we return the maximum number which is 3 floors.
Example 2:
Input: bottom = 6, top = 8, special = [7,6,8]
Output: 0
Explanation: Every floor rented is a special floor, so we return 0.
Constraints:
1 <= special.length <= 105
1 <= bottom <= special[i] <= top <= 109
All the values of special are unique.
| class Solution:
def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:
special.sort()
special.insert(0, bottom - 1)
special.append(top + 1)
ans = 0
for i in range(len(special)-1):
ans = max(ans, special[i+1] - special[i] - 1)
return ans | class Solution {
public int maxConsecutive(int bottom, int top, int[] special) {
int max = Integer.MIN_VALUE;
Arrays.sort(special);
// from bottom to the first special floor
max = Math.max(max, special[0] - bottom);
// middle floors
for(int i = 1; i < special.length; i++) {
max = Math.max(max, special[i] - special[i - 1] - 1);
}
// from last special floor to the top
max = Math.max(max, top - special[special.length - 1]);
return max;
}
} | class Solution {
public:
int maxConsecutive(int bottom, int top, vector<int>& special) {
int res(0), n(size(special));
sort(begin(special), end(special));
for (int i=1; i<n; i++) {
res = max(res, special[i]-special[i-1]-1);
}
return max({res, special[0]-bottom, top-special[n-1]});
}
}; | /**
* @param {number} bottom
* @param {number} top
* @param {number[]} special
* @return {number}
*/
var maxConsecutive = function(bottom, top, special) {
special.push(top+1);
special.push(bottom-1);
special.sort((a, b) => a - b);
let specialMax = 0;
for (let i = 1; i < special.length; i++){
specialMax = Math.max(specialMax, special[i] - special[i-1] - 1)
}
return specialMax;
}; | Maximum Consecutive Floors Without Special Floors |
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of capitals in it is right.
Example 1:
Input: word = "USA"
Output: true
Example 2:
Input: word = "FlaG"
Output: false
Constraints:
1 <= word.length <= 100
word consists of lowercase and uppercase English letters.
| class Solution:
def detectCapitalUse(self, word: str) -> bool:
l=len(word)
if l==1:
return True
if word[0]==word[0].lower() and word[1]==word[1].upper():
return False
u=False
if word[0]==word[0].upper():
if word[1]==word[1].upper():
u=True
for i in word[2:]:
if i==i.upper() and u==False:
return False
elif i==i.lower() and u==True:
return False
return True | class Solution {
public boolean detectCapitalUse(String word) {
int count = 0;
for(int i=0; i < word.length(); i++){
if('A' <= word.charAt(i) && word.charAt(i) <= 'Z')
count++;
}
if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt(0) && word.charAt(0) <= 'Z')))
return true;
else
return false;
}
} | class Solution {
public:
bool detectCapitalUse(string word) {
int n = word.size();
//if the first letter of the string is lower-case
if(islower(word[0])){
int c = 0;
for(int i=0; i<n; i++){
if(islower(word[i])){
c++;
}
}
//total lower-case count must be equal to the size of the string
if(c == n){
return true;
}
return false;
}
//if the first letter of the string is upper-case.
else{
int c = 0;
for(int i=0; i<n; i++){
if(isupper(word[i])){
c++;
}
}
//count of total upper-case letters must be equal to 1 or to the size of the string.
if(c == 1 or c == n){
return true;
}
//in all other cases, return false.
return false;
}
}
}; | var detectCapitalUse = function(word) {
if((word.charAt(0)==word.charAt(0).toUpperCase() && word.slice(1)==word.slice(1).toLowerCase()) || (word == word.toUpperCase()
|| word == word.toLowerCase()))
{
return true
}
else{
return false
}
}; | Detect Capital |
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
For example, s = "||**||**|*", and a query [3, 8] denotes the substring "*||**|". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the ith query.
Example 1:
Input: s = "**|**|***|", queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:
Input: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
Constraints:
3 <= s.length <= 105
s consists of '*' and '|' characters.
1 <= queries.length <= 105
queries[i].length == 2
0 <= lefti <= righti < s.length
| class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1)
res = []
for i, ch in enumerate(s):
psum[i + 1] = psum[i] + (ch == '|')
prev[i + 1] = i if ch == '|' else prev[i]
for i, ch in reversed(list(enumerate(s))):
next[i] = i if ch == '|' else next[i + 1]
for q in queries:
l, r = next[q[0]], prev[q[1] + 1]
res.append(r - l - (psum[r] - psum[l]) if l < r else 0)
return res | class Solution {
// O(sLen + queries.length) time, O(sLen) space
public int[] platesBetweenCandles(String s, int[][] queries) {
int sLen = s.length();
// cumulative number of plates from the left
int[] numberOfPlates = new int[sLen+1];
for (int i=0; i<sLen; i++) {
numberOfPlates[i+1] = numberOfPlates[i] + (s.charAt(i) == '*' ? 1 : 0);
}
// closest candle to the left
int[] candleToTheLeft = new int[sLen];
int cand = -1;
for (int i=0; i<sLen; i++) {
if (s.charAt(i) == '|') {
cand = i;
}
candleToTheLeft[i] = cand;
}
// closest candle to the right
int[] candleToTheRight = new int[sLen];
cand = -1;
for (int i=sLen-1; i>=0; i--) {
if (s.charAt(i) == '|') {
cand = i;
}
candleToTheRight[i] = cand;
}
// for each query - count the number of plates between closest candles
int[] res = new int[queries.length];
for (int i=0; i<queries.length; i++) {
int left = candleToTheRight[queries[i][0]];
int right = candleToTheLeft[queries[i][1]];
if (left == -1 || right == -1 || left >= right) {
res[i] = 0;
} else {
res[i] = numberOfPlates[right+1] - numberOfPlates[left];
}
}
return res;
}
} | class Solution {
public:
vector<int> platesBetweenCandles(string s, vector<vector<int>>& queries) {
vector<int> candlesIndex;
for(int i=0;i<s.length();i++){
if(s[i] == '|')
candlesIndex.push_back(i);
}
vector<int> ans;
for(auto q : queries){
int firstCandleIndex = lower_bound(candlesIndex.begin() , candlesIndex.end() , q[0]) - candlesIndex.begin();
int lastCandleIndex = upper_bound(candlesIndex.begin() , candlesIndex.end() , q[1]) - candlesIndex.begin() - 1;
if(lastCandleIndex <= firstCandleIndex){
ans.push_back(0);
continue;
}
int tempAns = candlesIndex[lastCandleIndex] - candlesIndex[firstCandleIndex] - (lastCandleIndex - firstCandleIndex);
ans.push_back(tempAns);
}
return ans;
}
}; | // time O(N + M) Space O(N) N = s.length M = query.length
var platesBetweenCandles = function(s, queries) {
let platPreFixSum = [...Array(s.length + 1)];
let leftViewCandle = [...Array(s.length + 1)];
let rightViewCandle = [...Array(s.length + 1)];
platPreFixSum[0] = 0;
leftViewCandle[0] = -1;
rightViewCandle[s.length] = -1;
for(let i = 1; i <= s.length; i++){
platPreFixSum[i] = s[i-1] == '*' ? platPreFixSum[i - 1] + 1 : platPreFixSum[i - 1];
leftViewCandle[i] = s[i - 1] == '|' ? i - 1 : leftViewCandle[i - 1];
rightViewCandle[s.length - i] = s[s.length - i] == '|' ? s.length - i : rightViewCandle[s.length - i + 1];
}
let result = [];
queries.forEach(([left, right]) => {
if(rightViewCandle[left] >= 0 && leftViewCandle[right + 1] >= 0 &&
rightViewCandle[left] < leftViewCandle[right + 1]) {
result.push(platPreFixSum[leftViewCandle[right + 1]] - platPreFixSum[rightViewCandle[left]]);
} else {
result.push(0);
}
});
return result;
}; | Plates Between Candles |
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Constraints:
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case letters.
1 <= sentence.length <= 106
sentence consists of only lower-case letters and spaces.
The number of words in sentence is in the range [1, 1000]
The length of each word in sentence is in the range [1, 1000]
Every two consecutive words in sentence will be separated by exactly one space.
sentence does not have leading or trailing spaces.
| class Solution {
public:
class trii{
public:
char data;
trii* dict[26];
bool isTerminal;
trii(){
}
trii(char d){
data=d;
for(int i=0;i<26;i++){
dict[i]=NULL;
}
isTerminal=false;
}
};
class tree{
public:
trii* root;
tree(){
root=new trii('\0');
}
void insert(string str,trii* node){
if(str.size()==0){
node->isTerminal=true;
return;
}
int index=str[0]-'a';
if(node->dict[index]==NULL ){
node->dict[index]=new trii(str[0]);
}
insert(str.substr(1),node->dict[index]);
}
string find(string str,trii* node,string pre){
if( node->isTerminal==true ){
return pre;
}
int index=str[0]-'a';
if(str.size()==0 || node->dict[index]==NULL){
return "\0";
}
return find(str.substr(1),node->dict[index],pre+str[0]);
}
string replaceWith(string word ,trii* node){
string temp=find(word,node,"");
if(temp!="\0"){
word=temp;
}
return word;
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
tree* t=new tree();
for(int i=0;i<dictionary.size();i++){
t->insert(dictionary[i],t->root);
}
string ans=sentence;
sentence="";
for(int i=0;i<ans.size();i++){
string word="";
while(i<ans.size()&&ans[i]!=' '){
word+=ans[i];
i++;
}
sentence+=t->replaceWith(word,t->root)+" ";
}
sentence.pop_back();
return sentence;
}
}; | class Solution {
public:
class trii{
public:
char data;
trii* dict[26];
bool isTerminal;
trii(){
}
trii(char d){
data=d;
for(int i=0;i<26;i++){
dict[i]=NULL;
}
isTerminal=false;
}
};
class tree{
public:
trii* root;
tree(){
root=new trii('\0');
}
void insert(string str,trii* node){
if(str.size()==0){
node->isTerminal=true;
return;
}
int index=str[0]-'a';
if(node->dict[index]==NULL ){
node->dict[index]=new trii(str[0]);
}
insert(str.substr(1),node->dict[index]);
}
string find(string str,trii* node,string pre){
if( node->isTerminal==true ){
return pre;
}
int index=str[0]-'a';
if(str.size()==0 || node->dict[index]==NULL){
return "\0";
}
return find(str.substr(1),node->dict[index],pre+str[0]);
}
string replaceWith(string word ,trii* node){
string temp=find(word,node,"");
if(temp!="\0"){
word=temp;
}
return word;
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
tree* t=new tree();
for(int i=0;i<dictionary.size();i++){
t->insert(dictionary[i],t->root);
}
string ans=sentence;
sentence="";
for(int i=0;i<ans.size();i++){
string word="";
while(i<ans.size()&&ans[i]!=' '){
word+=ans[i];
i++;
}
sentence+=t->replaceWith(word,t->root)+" ";
}
sentence.pop_back();
return sentence;
}
}; | class Solution {
public:
class trii{
public:
char data;
trii* dict[26];
bool isTerminal;
trii(){
}
trii(char d){
data=d;
for(int i=0;i<26;i++){
dict[i]=NULL;
}
isTerminal=false;
}
};
class tree{
public:
trii* root;
tree(){
root=new trii('\0');
}
void insert(string str,trii* node){
if(str.size()==0){
node->isTerminal=true;
return;
}
int index=str[0]-'a';
if(node->dict[index]==NULL ){
node->dict[index]=new trii(str[0]);
}
insert(str.substr(1),node->dict[index]);
}
string find(string str,trii* node,string pre){
if( node->isTerminal==true ){
return pre;
}
int index=str[0]-'a';
if(str.size()==0 || node->dict[index]==NULL){
return "\0";
}
return find(str.substr(1),node->dict[index],pre+str[0]);
}
string replaceWith(string word ,trii* node){
string temp=find(word,node,"");
if(temp!="\0"){
word=temp;
}
return word;
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
tree* t=new tree();
for(int i=0;i<dictionary.size();i++){
t->insert(dictionary[i],t->root);
}
string ans=sentence;
sentence="";
for(int i=0;i<ans.size();i++){
string word="";
while(i<ans.size()&&ans[i]!=' '){
word+=ans[i];
i++;
}
sentence+=t->replaceWith(word,t->root)+" ";
}
sentence.pop_back();
return sentence;
}
}; | class Solution {
public:
class trii{
public:
char data;
trii* dict[26];
bool isTerminal;
trii(){
}
trii(char d){
data=d;
for(int i=0;i<26;i++){
dict[i]=NULL;
}
isTerminal=false;
}
};
class tree{
public:
trii* root;
tree(){
root=new trii('\0');
}
void insert(string str,trii* node){
if(str.size()==0){
node->isTerminal=true;
return;
}
int index=str[0]-'a';
if(node->dict[index]==NULL ){
node->dict[index]=new trii(str[0]);
}
insert(str.substr(1),node->dict[index]);
}
string find(string str,trii* node,string pre){
if( node->isTerminal==true ){
return pre;
}
int index=str[0]-'a';
if(str.size()==0 || node->dict[index]==NULL){
return "\0";
}
return find(str.substr(1),node->dict[index],pre+str[0]);
}
string replaceWith(string word ,trii* node){
string temp=find(word,node,"");
if(temp!="\0"){
word=temp;
}
return word;
}
};
string replaceWords(vector<string>& dictionary, string sentence) {
tree* t=new tree();
for(int i=0;i<dictionary.size();i++){
t->insert(dictionary[i],t->root);
}
string ans=sentence;
sentence="";
for(int i=0;i<ans.size();i++){
string word="";
while(i<ans.size()&&ans[i]!=' '){
word+=ans[i];
i++;
}
sentence+=t->replaceWith(word,t->root)+" ";
}
sentence.pop_back();
return sentence;
}
}; | Replace Words |
In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Example 1:
Input: n = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Constraints:
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
All the pairs of trust are unique.
ai != bi
1 <= ai, bi <= n
| class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
possible = set([i for i in range(1,n+1)])
in_edges = [0] * (n+1)
for first, second in trust:
possible.discard(first)
in_edges[second] += 1
if len(possible) != 1:
return -1
i = possible.pop()
if in_edges[i] == n-1:
return i
return -1 | class Solution {
public int findJudge(int n, int[][] trust) {
int count=0;
int x[]=new int[n+1];
int y[]=new int[n+1];
Arrays.fill(x, 0);
Arrays.fill(y, 0);
for(int i=0;i<trust.length;i++)
{
x[trust[i][0]]=1;
}
for(int i=1;i<=n;i++)
{
if(x[i]!=0)
count++;
if(x[i]==0)
y[i]=1;
}
if(count==n)
return -1;
for(int i=1;i<=n;i++)
System.out.println(y[i]);
int jud=0;
for(int i=1;i<=n;i++)
{
if(y[i]==1)
jud=i;
}
int c=0;
for(int i=0;i<trust.length;i++)
{
if(trust[i][1]==jud)
c++;
}
if(c==n-1)
return jud;
return -1;
}
} | class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
vector<pair<int,int>> v(n+1,{0,0});
for(auto i : trust){
v[i[0]].first++;
v[i[1]].second++;
}
int ans = -1;
for(int i=1;i<=n;i++){
auto p = v[i];
if(p.first == 0 && p.second == n-1){
ans = i;
break;
}
}
return ans;
}
}; | var findJudge = function(n, trust) {
const length = trust.length;
let possibleJudge = [], judgeMap = new Map(), value, judge = -1;
for(let i = 0; i < length; i++) {
if(judgeMap.has(trust[i][0])){
value = judgeMap.get(trust[i][0]);
value.push(trust[i][1]);
judgeMap.set(trust[i][0], value);
}
else {
judgeMap.set(trust[i][0], [trust[i][1]]);
}
}
value = [];
for(let i = 1; i <= n; i++) {
if(!judgeMap.has(i)) {
possibleJudge.push(i);
}
else {
value.push([i,judgeMap.get(i)]);
}
}
if(!value.length || value.length !== n-1) {
if(possibleJudge.length === 1) return possibleJudge[0];
return judge;
}
for(let i = 0; i < possibleJudge.length; i++) {
judge = possibleJudge[i];
for(let j = 0; j < value.length; j++) {
if(value[j][1].indexOf(judge) < 0) {
judge = -1;
break;
}
}
if(judge !== -1) break;
}
return judge;
}; | Find the Town Judge |
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.
A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.
Example 1:
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
Example 2:
Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
Output: "aaaaaaaa"
Constraints:
1 <= str1.length, str2.length <= 1000
str1 and str2 consist of lowercase English letters.
| class Solution:
def shortestCommonSupersequence(self, A, B):
n, m = len(A), len(B)
dp = [B[:i] for i in range(m + 1)]
for i in range(n):
prev = A[:i]
dp[0] = A[:i + 1]
for j in range(m):
if A[i] == B[j]:
prev, dp[j + 1] = dp[j + 1], prev + A[i]
else:
prev, dp[j + 1] = dp[j + 1], min(dp[j] + B[j], dp[j + 1] + A[i], key = len)
return dp[-1] | class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
int m=str1.length();
int n=str2.length();
int[][] dp=new int[m+1][n+1];
for(int i=1;i<m+1;i++){
for(int j=1;j<n+1;j++){
if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j]=1+dp[i-1][j-1];
}else{
dp[i][j]=Math.max(dp[i][j-1],dp[i-1][j]);
}
}
}
int i=m,j=n;
String res="";
while(i>0 && j>0){
if(str1.charAt(i-1)==str2.charAt(j-1)){
res=str1.charAt(i-1)+res;
i--;
j--;
}else if(dp[i-1][j]>dp[i][j-1]){
res=str1.charAt(i-1)+res;
i--;
}else{
res=str2.charAt(j-1)+res;
j--;
}
}
while(i>0){
res=str1.charAt(i-1)+res;
i--;
}
while(j>0){
res=str2.charAt(j-1)+res;
j--;
}
return res;
}
} | class Solution
{
string LCS(string str1, string str2, int m, int n)
{
int t[m+1][n+1];
string ans = "";
for(int i = 0;i < m+1; ++i)
{
for(int j = 0; j< n+1; ++j)
{
if(i == 0 || j == 0)
t[i][j] = 0;
}
}
for(int i = 1; i < m+1; ++i)
{
for(int j = 1; j < n+1; ++j)
{
if(str1[i-1] == str2[j-1])
t[i][j] = 1 + t[i-1][j-1];
else
t[i][j] = max(t[i-1][j], t[i][j-1]);
}
}
int i = m, j = n;
while(i > 0 && j > 0)
{
if(str1[i-1] == str2[j-1])
{
ans.push_back(str1[i-1]);
--i;
--j;
}
else if(t[i][j-1] > t[i-1][j])
{
ans.push_back(str2[j-1]);
--j;
}
else
{
ans.push_back(str1[i-1]);
--i;
}
}
while( i > 0)
{
ans.push_back(str1[i-1]);
--i;
}
while( j > 0)
{
ans.push_back(str2[j-1]);
--j;
}
reverse(ans.begin(),ans.end());
return ans;
}
public:
string shortestCommonSupersequence(string str1, string str2) {
int m = str1.length();
int n = str2.length();
return LCS(str1, str2, m ,n);
}
}; | var shortestCommonSupersequence = function(str1, str2) {
const lcs = getLCS(str1, str2)
let i = 0
let j = 0
let result = ''
for (const c of lcs) {
while(i < str1.length && str1[i] !== c) {
result += str1[i]
i++
}
while(j < str2.length && str2[j] !== c) {
result += str2[j]
j++
}
result += c
i++
j++
}
while(i < str1.length) {
result += str1[i]
i++
}
while(j < str2.length) {
result += str2[j]
j++
}
return result
};
function getLCS (a, b) {
const t = new Array(a.length + 1).fill(0).map(() => new Array(b.length + 1).fill(0))
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) {
t[i][j] = 1 + t[i - 1][j - 1]
} else {
t[i][j] = Math.max(t[i - 1][j], t[i][j - 1])
}
}
}
let i = a.length
let j = b.length
let result = ''
while(i > 0 && j > 0) {
if (a[i-1] === b[j-1]) {
result += a[i-1]
i--
j--
} else {
if (t[i-1][j] > t[i][j-1]) {
i--
} else {
j--
}
}
}
return result.split('').reverse().join('')
} | Shortest Common Supersequence |
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Example 1:
Input: dist = [1,3,2], hour = 6
Output: 1
Explanation: At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
Example 2:
Input: dist = [1,3,2], hour = 2.7
Output: 3
Explanation: At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
Example 3:
Input: dist = [1,3,2], hour = 1.9
Output: -1
Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
Constraints:
n == dist.length
1 <= n <= 105
1 <= dist[i] <= 105
1 <= hour <= 109
There will be at most two digits after the decimal point in hour.
| class Solution:
def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
# the speed upper is either the longest train ride: max(dist),
# or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).
# notice: "hour will have at most two digits after the decimal point"
upper = max(max(dist), ceil(dist[-1] / 0.01))
#
# the function to calcute total time consumed
total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)
# the case of impossible to arrive office on time
if total(upper) > hour:
return -1
#
# binary search: find the mimimal among "all" feasible answers
left, right = 1, upper
while left < right:
mid = left + (right - left) // 2
if total(mid) > hour:
left = mid + 1 # should be larger
else:
right = mid # should explore a smaller one
return right | class Solution {
public int minSpeedOnTime(int[] dist, double hour) {
int left = 1;
int right = (int) 1e8;
while (left < right) {
int middle = (left + right) / 2;
if (arriveOnTime(dist, hour, middle))
right = middle;
else left = middle + 1;
}
return right == (int) 1e8 ? -1 : right;
}
private boolean arriveOnTime(int[] dist, double hour, int speed) {
int time = 0;
for (int i = 0; i < dist.length - 1; i++) {
time += Math.ceil((double) dist[i] / speed);
}
return time + (double) dist[dist.length - 1] / speed <= hour;
}
} | class Solution
{
bool canReachInTime(const vector<int>& dist, const double hour, int speed)
{
double time = 0;
for (int i = 0; i < dist.size() - 1; ++i)
time += ((dist[i] + speed - 1) / speed);
time += ((double)dist.back()) / speed;
return time <= hour;
}
public:
int minSpeedOnTime(vector<int>& dist, double hour)
{
int N = dist.size();
if (hour <= (double)(N - 1))
return -1;
int lo = 1, hi = 1e7, mi;
while (lo < hi)
{
mi = (lo + hi) / 2;
if (canReachInTime(dist, hour, mi))
hi = mi;
else
lo = mi + 1;
}
return hi;
}
}; | var minSpeedOnTime = function(dist, hour) {
let left=1,right=10000000,speed,sum,ans=-1;
while(left<=right){
//We need to return the minimum positive integer speed (in kilometers per hour) that all the trains must travel. So speed will always be an integer ranging from 1 to 10000000 as per the question description.
speed = left + Math.floor((right-left)/2);
sum=0;
for(let i=0;i<dist.length-1;i++){
sum += Math.ceil((dist[i]/speed));
}
sum += (dist[dist.length-1]/speed);//For the last train we need not to do Math.ceil
if(sum<=hour){//sum(time taken is less than the required time, so it can be our answer, but we will keep looking for the another smaller speed until left<=right)
ans=speed;
right = speed-1;
}else{
left=speed+1;
}
}
return ans;
}; | Minimum Speed to Arrive on Time |
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
| class Solution:
def smallerNumbersThanCurrent(self, nums):
sortify = sorted(nums)
return (bisect_left(sortify, i) for i in nums) | class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] sorted = nums.clone();
int[] res = new int[nums.length];//result array
Arrays.sort(sorted);
for (int i = 0; i < nums.length; ++i) {
//binary search it, if there is no duplicates the idx will be how many smaller are there
int idx = binarySearch(sorted, nums[i]);
//if there are duplicates, then we need to find the first one presented in the array
if (idx-1>=0 && sorted[idx-1] == nums[i]) {
while (idx >= 0 && sorted[idx] == nums[i]) {
--idx;
}
++idx;
}
//As I said before, array of indices(indexes) will be the answer
res[i] = idx;
}
return res;
}
//Just simple iterative binary search
public static int binarySearch(int[] arr, int target) {
int s = 0;
int e = arr.length-1;
int m = (s+e)/2;
while (s<=e) {
if (arr[m] == target) {
return m;
} else if (arr[m] > target) {
e = m-1;
} else {
s = m+1;
}
m = (s+e)/2;
}
return -1;
}
} | class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> ans;
int i,j,size,count;
size = nums.size();
for(i = 0; i<size; i++){
count = 0;
for(j = 0;j<size;j++){
if(nums[j]<nums[i]) count++;
}
ans.push_back(count);
}
return ans;
}
}; | var smallerNumbersThanCurrent = function(nums) {
let count, ans=[];
/*Run a loop on each element excluding nums[i]
and compare it with nums[j] if it's large, then count++
else break;*/
for(let i=0; i<nums.length; i++){
let temp=nums[i], count=0;
for(let j=0; j<nums.length; j++){
if(i===j) continue;
if(temp>nums[j]) count++;
}
ans.push(count);
}
return ans;
};
//second way using objects:--->
var smallerNumbersThanCurrent = function(nums) {
let arr=[...nums], ans=[];
arr.sort((a,b)=>a-b);
let map={};
map[arr[0]]=0;
for(let i=1; i<arr.length; i++){
if(arr[i-1]!==arr[i]) map[arr[i]]=i;
}
for(let i=0; i<nums.length; i++){
ans.push(map[nums[i]]);
}
return ans;
}; | How Many Numbers Are Smaller Than the Current Number |
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.
Example 1:
Input: nums = [5,6,2,7,4]
Output: 34
Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
Example 2:
Input: nums = [4,2,5,9,7,4,8]
Output: 64
Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
Constraints:
4 <= nums.length <= 104
1 <= nums[i] <= 104
| class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max_1 = 0
max_2 = 0
min_1 = 10001
min_2 = 10001
for i in nums:
if i >= max_1:
max_2,max_1 = max_1,i
elif i > max_2:
max_2 = i
if i <= min_1:
min_2,min_1 = min_1,i
elif i < min_2:
min_2 = i
return max_1*max_2 - min_1*min_2 | class Solution {
public int maxProductDifference(int[] nums) {
int max1 = Integer.MIN_VALUE;
int max2 = max1;
int min1 = Integer.MAX_VALUE;
int min2 = min1;
for (int i = 0; i < nums.length; i++) {
if (max1 < nums[i]) {
max2 = max1;
max1 = nums[i];
} else if(nums[i] > max2)
max2 = nums[i];
if(min1 > nums[i]){
min2 = min1;
min1 = nums[i];
}else if (nums[i] < min2)
min2 = nums[i];
}
return (max1 * max2) - (min1 * min2);
}
} | class Solution {
public:
int maxProductDifference(vector<int>& nums) {
//we have to return the result of
// (firstMax*secondMax) - (firstMin*secondMin)
int max1=INT_MIN;
int max2=INT_MIN;
int min1=INT_MAX;
int min2=INT_MAX;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>max1)
{
//assign the second max to max2
max2=max1;
max1=nums[i];
}
else if(nums[i]>max2)
{
//it can become second max
max2= nums[i];
}
//check for the minimum
if(nums[i]<min1)
{
//it can become first minimum
min2=min1;
min1=nums[i];
}
else if(nums[i]<min2)
{
//it can become second minimum
min2=nums[i];
}
}
return (max1*max2)- (min1*min2);
}
}; | var maxProductDifference = function(nums) {
nums.sort((a,b) => a-b);
return nums.slice(nums.length - 2).reduce((a,b) => a*b, 1) - nums.slice(0, 2).reduce((a,b) => a*b, 1);
}; | Maximum Product Difference Between Two Pairs |
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
| # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return None
slow = fast = entry = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
while slow != entry:
slow = slow.next
entry = entry.next
return entry
return None | public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode tortoise = head;
ListNode hare = new ListNode();
hare.next = head.next;
while (hare != null && hare.next != null && hare != tortoise) {
tortoise = tortoise.next;
hare = hare.next.next;
}
if (hare == null || hare.next == null) return null;
tortoise = head;
while (tortoise != hare) {
tortoise = tortoise.next;
hare = hare.next;
}
return hare;
}
} | class Solution {
public:
ListNode *detectCycle(ListNode *head) {
map<ListNode*, int> m;
int index = 0;
while (head)
{
if (m.find(head) == m.end())
m[head] = index;
else
return (head);
head = head->next;
index++;
}
return (NULL);
}
}; | var detectCycle = function(head) {
let slowRunner = head
let fastRunner = head
while(fastRunner) {
fastRunner = fastRunner.next?.next
slowRunner = slowRunner.next
if (fastRunner === slowRunner) {
fastRunner = slowRunner
slowRunner = head
while (slowRunner !== fastRunner) {
slowRunner = slowRunner.next
fastRunner = fastRunner.next
}
return slowRunner
}
}
return null
}; | Linked List Cycle II |
You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.
In one move, you can either:
Increment the current integer by one (i.e., x = x + 1).
Double the current integer (i.e., x = 2 * x).
You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.
Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.
Example 1:
Input: target = 5, maxDoubles = 0
Output: 4
Explanation: Keep incrementing by 1 until you reach target.
Example 2:
Input: target = 19, maxDoubles = 2
Output: 7
Explanation: Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19
Example 3:
Input: target = 10, maxDoubles = 4
Output: 4
Explanation: Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10
Constraints:
1 <= target <= 109
0 <= maxDoubles <= 100
| class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
c=0
while(maxDoubles>0 and target>1):
c += target%2
target //= 2
c += 1
maxDoubles -=1
return c + target-1 | class Solution {
public int minMoves(int target, int maxDoubles) {
int ans = 0;
for(int i=0;i<maxDoubles;i++){
if(target==1)break;
if(target%2==0){
ans+=1;
target=(target)/2;
}else{
ans+=2;
target=(target-1)/2;
}
}
return ans+target-1;
}
} | class Solution {
public:
int minMoves(int target, int maxDoubles) {
int cnt = 0;
while(target>1 && maxDoubles>0){
if(target%2==0){
cnt++;
maxDoubles--;
target = target/2;
}
else{
cnt++;
target--;
}
}
return cnt + (target-1);
}
}; | var minMoves = function(target, maxDoubles) {
if (maxDoubles === 0) return target - 1;
let count = 0;
while (target > 1) {
if (target % 2 === 0 && maxDoubles > 0) {
target /= 2;
maxDoubles--;
} else {
target--;
}
count++;
}
return count;
}; | Minimum Moves to Reach Target Score |
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:
Eat one orange.
If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.
You can only choose one of the actions per day.
Given the integer n, return the minimum number of days to eat n oranges.
Example 1:
Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange, 10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange 1 - 1 = 0.
You need at least 4 days to eat the 10 oranges.
Example 2:
Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange 1 - 1 = 0.
You need at least 3 days to eat the 6 oranges.
Constraints:
1 <= n <= 2 * 109
| from collections import deque
from math import log2, ceil
class Solution:
def minDays(self, n: int) -> int:
maxd = 2*ceil(log2(n))
que = deque([(1,1)])
seen = set()
while que:
v, d = que.popleft()
seen.add(v)
if v == n:
return d
for w in [v+1, 2*v, 3*v]:
if w not in seen and d <= maxd and w <= n:
que.append((w,d+1)) | class Solution {
HashMap<Integer,Integer>map;
public int minDays(int n) {
map = new HashMap<>();
map.put(0,0);
map.put(1,1);
return dp(n);
}
public int dp(int n){
if(map.get(n)!=null)
return map.get(n);
int one = 1+(n%2)+dp(n/2);
int two = 1+(n%3)+dp(n/3);
map.put(n,Math.min(one,two));
return map.get(n);
}
}
// int one = 1+(n%2)+cache(n/2);
// int two = 1+(n%3)+cache(n/3); | class Solution {
public:
// approach: BFS
int minDays(int n) {
int cnt=0;
queue<int>q;
q.push(n);
unordered_set<int>s;
s.insert(n);
while(!q.empty()){
int l=q.size();
while(l--){
int a=q.front();
q.pop();
if(a==0)
break;
if(s.find(a-1)==s.end()){
q.push(a-1);
s.insert(a-1);
}
if(!(a&1) && s.find(a>>1)==s.end()){ // if divisible by 2 and a/2 not present in set
q.push(a>>1);
s.insert(a>>1);
}
if(a%3==0 && s.find(a/3)==s.end()){ // if divisible by 3 and a/3 not present in set
q.push(a/3);
s.insert(a/3);
}
}
cnt++;
if(s.find(0)!=s.end())
break;
}
return cnt;
}
}; | var minDays = function(n) {
const queue = [ [n,0] ];
const visited = new Set();
while (queue.length > 0) {
const [ orangesLeft, days ] = queue.shift();
if (visited.has(orangesLeft)) continue;
if (orangesLeft === 0) return days;
visited.add(orangesLeft);
queue.push([orangesLeft - 1, days + 1]);
if (orangesLeft % 2 === 0) {
queue.push([orangesLeft - orangesLeft / 2, days + 1]);
}
if (orangesLeft % 3 === 0) {
queue.push([orangesLeft - 2 * (orangesLeft / 3), days + 1])
}
}
}; | Minimum Number of Days to Eat N Oranges |
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num after any number of swaps.
Example 1:
Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
Example 2:
Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
Constraints:
1 <= num <= 109
| class Solution:
def largestInteger(self, num: int):
n = len(str(num))
arr = [int(i) for i in str(num)]
odd, even = [], []
for i in arr:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
odd.sort()
even.sort()
res = 0
for i in range(n):
if arr[i] % 2 == 0:
res = res*10 + even.pop()
else:
res = res*10 + odd.pop()
return res | class Solution {
public int largestInteger(int num) {
PriorityQueue<Integer> opq = new PriorityQueue<>();
PriorityQueue<Integer> epq = new PriorityQueue<>();
int bnum = num;
while(num>0){
int cur = num%10;
if(cur%2==1){
opq.add(cur);
}else{
epq.add(cur);
}
num /= 10;
}
StringBuilder sb = new StringBuilder();
num = bnum;
while(num>0){
int cur = num%10;
if(cur%2==1)
sb.insert(0, opq.poll());
else
sb.insert(0, epq.poll());
num /= 10;
}
return Integer.parseInt(sb.toString());
}
} | class Solution {
public:
int largestInteger(int num) {
priority_queue<int> p; // priority queue to store odd digits in descending order
priority_queue<int> q; // priority queue to store even digits in descending order
string nums=to_string(num); // converting num to a string for easy access of the digits
int n=nums.size(); // n stores the number of digits in num
for(int i=0;i<n;i++){
int digit=nums[i]-'0';
if((digit)%2) // if digit is odd, push it into priority queue p
p.push(digit);
else
q.push(digit); // if digit is even, push it into priority queue q
}
int answer=0;
for(int i=0; i<n; i++){
answer=answer*10;
if((nums[i]-'0')%2) // if the digit is odd, add the largest odd digit of p into the answer
{answer+=p.top();p.pop();}
else
{answer+=q.top();q.pop();} // if the digit is even, add the largest even digit of q into the answer
}
return answer;
}
}; | /**
* @param {number} num
* @return {number}
*/
var largestInteger = function(num) {
var nums = num.toString().split("");//splitting the numbers into an array
var odd=[];//helps keep a track of odd numbers
var even =[];//helps keep a track of even numbers
for(var i=0;i<nums.length;i++){
if(nums[i]%2===0) //pushing even numbers to even array
even.push(nums[i]);
else//pushing odd numbers to odd array
odd.push(nums[i]);
}
odd.sort((a,b)=>a-b);//sorting the arrays in ascending order
even.sort((a,b)=>a-b);
var ans =[];
for(var i=0;i<nums.length;i++){
if(nums[i]%2===0){//replacing even with even
ans.push(even[even.length-1]);//pushing the greatest even number in the ans
even.pop();//popping the used number
}
else{//replacing odd with odd
ans.push(odd[odd.length-1]);//pushing the greatest odd number in the ans
odd.pop();//popping the used number
}
}
var ans2 = parseInt(ans.join(""));//converting the ans array into an int number
return ans2;
}; | Largest Number After Digit Swaps by Parity |
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.
Example 1:
Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (0, 0) to other cells are: [0,1]
Example 2:
Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1
Output: [[0,1],[0,0],[1,1],[1,0]]
Explanation: The distances from (0, 1) to other cells are: [0,1,1,2]
The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.
Example 3:
Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2
Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]
There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
Constraints:
1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
| class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
# create a r, c matrix given the rows & cols
# each element represents a list [r, c] where r is the row & c the col
# find find the distances of all cells from the center (append to res)
# sort the result by distance function
# Time O(M + N) Space O(M + N)
def distance(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
matrix = [[i, j] for i in range(rows) for j in range(cols)]
center = [rCenter, cCenter]
matrix.sort(key=lambda c: distance(c, center))
return matrix | //--------------------Method 1----------------------
class Solution {
public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
int [][]res=new int[rows*cols][2];
int idx=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
res[idx][0]=i;
res[idx][1]=j;
idx++;
}
}
Arrays.sort(res,(a,b)->{
int d1=Math.abs(a[0]-rCenter)+Math.abs(a[1]-cCenter);
int d2=Math.abs(b[0]-rCenter)+Math.abs(b[1]-cCenter);
return d1-d2;
});
return res;
}
}
//--------------------Method 2--------------------
// class Solution {
// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
// boolean [][]vis=new boolean[rows][cols];
// int [][]ans=new int[rows*cols][2];
// Queue<Pair> q=new LinkedList<>();
// q.add(new Pair(rCenter,cCenter));
// int idx=0;
// vis[rCenter][cCenter]=true;
// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};
// while(!q.isEmpty()){
// Pair curr=q.remove();
// ans[idx][0]=curr.r;
// ans[idx][1]=curr.c;
// idx++;
// for(int []d:dir){
// int nr=curr.r+d[0];
// int nc=curr.c+d[1];
// if(nr>=0 && nr<rows && nc>=0 && nc<cols && !vis[nr][nc]){
// vis[nr][nc]=true;
// q.add(new Pair(nr,nc));
// }
// }
// }
// return ans;
// }
// }
// class Pair{
// int r;
// int c;
// public Pair(int r, int c){
// this.r=r;
// this.c=c;
// }
// } | class Solution {
public:
vector<vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
vector<vector<int>> ans;
multimap<int,vector<int>> mp;
for(int i = 0;i<rows;i++){
for(int j = 0;j<cols;j++){
mp.insert(pair<int,vector<int>>(abs(i-rCenter)+abs(j-cCenter),{i,j})); //map will sort the value based on key(distance)
}
}
for(auto itr = mp.begin();itr != mp.end();itr++){
ans.push_back(itr->second);
}
return ans;
}
}; | var allCellsDistOrder = function(rows, cols, rCenter, cCenter) {
let distances = []
let result = []
//create a new "visited" cells matrix
let visited = new Array(rows).fill([])
for(i=0;i<visited.length;i++){
visited[i] = new Array(cols).fill(0)
}
const computeDistances = (row, col, rCenter, cCenter) => {
if(row >= rows || col >= cols) return
if(visited[row][col]) return // don't compute distance again if cell already visited
visited[row][col] = 1
let distance = Math.abs(rCenter - row) + Math.abs(cCenter - col)
if(distances[distance]){
distances[distance].add([row,col])
}else{
distances[distance] = new Set()
distances[distance].add([row,col])
}
computeDistances(row + 1, col, rCenter, cCenter)
computeDistances(row, col + 1, rCenter, cCenter)
}
computeDistances(0, 0, rCenter, cCenter)
distances.forEach(distance => {
result.push(...distance)
})
return result
}; | Matrix Cells in Distance Order |
You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.
In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.
For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can:
place stamp at index 0 of s to obtain "abc??",
place stamp at index 1 of s to obtain "?abc?", or
place stamp at index 2 of s to obtain "??abc".
Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).
We want to convert s to target using at most 10 * target.length turns.
Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.
Example 1:
Input: stamp = "abc", target = "ababc"
Output: [0,2]
Explanation: Initially s = "?????".
- Place stamp at index 0 to get "abc??".
- Place stamp at index 2 to get "ababc".
[1,0,2] would also be accepted as an answer, as well as some other answers.
Example 2:
Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]
Explanation: Initially s = "???????".
- Place stamp at index 3 to get "???abca".
- Place stamp at index 0 to get "abcabca".
- Place stamp at index 1 to get "aabcaca".
Constraints:
1 <= stamp.length <= target.length <= 1000
stamp and target consist of lowercase English letters.
| class Solution:
def movesToStamp(self, S: str, T: str) -> List[int]:
if S == T: return [0]
S, T = list(S), list(T)
slen, tlen = len(S), len(T) - len(S) + 1
ans, tdiff, sdiff = [], True, True
while tdiff:
tdiff = False
for i in range(tlen):
sdiff = False
for j in range(slen):
if T[i+j] == "*": continue
if T[i+j] != S[j]: break
sdiff = True
else:
if sdiff:
tdiff = True
for j in range(i, i + slen): T[j] = "*"
ans.append(i)
for i in range(len(T)):
if T[i] != "*": return []
return reversed(ans) | class Solution {
public int[] movesToStamp(String stamp, String target) {
/*
* Intitution:
* Instead of creating target string from intial state,
* create the intial state from the target string.
* - take a window of stamp length
* - reverse that window to the intail state
* current state -> abcdefgh, window = def,
* next state -> abc???gh
*
*/
int sLen = stamp.length();
int tLen = target.length();
//it save the index of reversed charcacter
Queue<Integer> reversedCharIndices= new LinkedList();
//it mark Character of target, as reversed
boolean[] isReversedCharOfThisIndex = new boolean[tLen];
Stack<Integer> stack = new Stack();
List<Window> widowList = new ArrayList();
for(int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++){
Set<Integer> matched = new HashSet();
Set<Integer> notMatched = new HashSet();
for(int j = 0; j < sLen; j++){
//char index of current window of the target
int charIndex = windowStartIndex + j;
if(stamp.charAt(j) == target.charAt(charIndex)){
matched.add(charIndex);
} else {
notMatched.add(charIndex);
}
}
//add the window
widowList.add(new Window(matched, notMatched));
//when all char of current window is matched with
if(notMatched.isEmpty()){
stack.push(windowStartIndex);
for(int index : matched){
if(!isReversedCharOfThisIndex[index]){
//add in queue, so that we can process,
//another window which is affected by its character get reversed
reversedCharIndices.add(index);
//mark it reversed
isReversedCharOfThisIndex[index] = true;
}
}
}
}
//get all char index, one by once
//see the impact of reverse char of this index, in ano
while(!reversedCharIndices.isEmpty()){
int reversedCharIndex = reversedCharIndices.remove();
int start = Math.max(0, reversedCharIndex - sLen + 1);
int end = Math.min(reversedCharIndex, tLen - sLen);
for(int windowIndex = start; windowIndex <= end; windowIndex++){
if(widowList.get(windowIndex).notMatched.contains(reversedCharIndex)){
//as this char is reversed in another window
//remove this char index from current window,
widowList.get(windowIndex).notMatched.remove(reversedCharIndex);
if(widowList.get(windowIndex).notMatched.isEmpty()){
//as all of charcater reversed of current window
//now add current window index
stack.push(windowIndex);
for(int index : widowList.get(windowIndex).matched){
if(!isReversedCharOfThisIndex[index]){
//add in queue, so that we can process,
//another window which is affected by its character get reversed
reversedCharIndices.add(index);
//mark it reversed
isReversedCharOfThisIndex[index] = true;
}
}
}
}
}
}
for(boolean reversed : isReversedCharOfThisIndex){
if(!reversed){
return new int[0];
}
}
int i = 0;
int[] result = new int[stack.size()];
while(!stack.empty()){
result[i++] = stack.pop();
}
return result;
}
}
class Window {
Set<Integer> matched;
Set<Integer> notMatched;
public Window(Set<Integer> matched, Set<Integer> notMatched){
this.matched = matched;
this.notMatched = notMatched;
}
} | class Solution {
public:
vector<int> movesToStamp(string stamp, string target) {
auto isUndone = [](auto it, auto endIt) {
return all_of(it, endIt, [](char c) { return c == '?'; });
};
vector<int> res;
while (!isUndone(begin(target), end(target))) {
auto prevResSize = size(res);
for (size_t i = 0; i < size(target) - size(stamp) + 1; ++i) {
auto it = begin(target) + i, endIt = it + size(stamp);
if (isUndone(it, endIt))
continue;
size_t j = 0;
for (; j < size(stamp) && (*(it + j) == stamp[j] || *(it + j) == '?'); ++j);
if (j == size(stamp)) {
fill(it, endIt, '?');
res.push_back(i);
}
}
if (prevResSize == size(res))
return {};
}
reverse(begin(res), end(res));
return res;
}
}; | var movesToStamp = function(stamp, target) {
var s = target.replace(/[a-z]/g,"?")
var repl = s.substr(0,stamp.length)
let op = []
let s1 = target
while(s1 !== s){
let idx = getIndex()
if(idx === -1) return []
op.push(idx)
}
return op.reverse()
function getIndex(){
for(let i=0; i<target.length; i++){
let match = 0
let j=0
for(; j<stamp.length; j++){
if(target.substr(i+j,1) === stamp.substr(j,1)) match++
else
if(target.substr(i+j,1) === "?") continue
else break
}
if(j===stamp.length && match!==0){
let k=i
for(let j=0; j<stamp.length; j++){
if(k===0){ s1 = "?"+target.substr(1)}
else { s1 = target.substr(0,k)+"?"+target.substr(k+1)}
k++
target = s1
}
return i
}
}
return -1
}
};
``` | Stamping The Sequence |
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.
Example 1:
Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8).
Example 2:
Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 12 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].
Example 3:
Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].
Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].
Constraints:
1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 105
| class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
sqr1, sqr2 = defaultdict(int), defaultdict(int)
m, n = len(nums1), len(nums2)
for i in range(m):
sqr1[nums1[i]**2] += 1
for j in range(n):
sqr2[nums2[j]**2] += 1
res = 0
for i in range(m-1):
for j in range(i+1, m):
if nums1[i]*nums1[j] in sqr2:
res += sqr2[nums1[i]*nums1[j]]
for i in range(n-1):
for j in range(i+1, n):
if nums2[i]*nums2[j] in sqr1:
res += sqr1[nums2[i]*nums2[j]]
return res | class Solution {
public int numTriplets(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
return count(nums1 , nums2) + count(nums2 , nums1);
}
public int count(int a[] , int b[]){
int n = a.length;
int m = b.length;
int count = 0;
for(int i=0;i<n;i++){
long x = (long)a[i]*a[i];
int j = 0;
int k = m-1;
while(j<k){
long prod = (long)b[j]*b[k];
if(prod<x)
j++;
else if(prod>x)
k--;
else if(b[j] != b[k]){
int jNew = j;
int kNew = k;
while(b[j] == b[jNew])
jNew++;
while(b[k] == b[kNew])
kNew--;
count += (jNew-j)*(k-kNew);
j = jNew;
k = kNew;
}
else{
int q = k-j+1;
count += (q)*(q-1)/2;
break;
}
}
}
return count;
}
} | class Solution {
public:
int numTriplets(vector<int>& nums1, vector<int>& nums2) {
unordered_map<long, int> m1, m2;
for(int i : nums1) m1[(long long)i*i]++;
for(int i : nums2) m2[(long long)i*i]++;
int ans = 0;
for(int i=0; i<nums2.size()-1; i++){
for(int j=i+1; j<nums2.size(); j++){
if(m1[(long long)nums2[i] * nums2[j]]){
ans += m1[(long long)nums2[i] * nums2[j]];
}
}
}
for(int i=0; i<nums1.size()-1; i++){
for(int j=i+1; j<nums1.size(); j++){
if(m2[(long long)nums1[i] * nums1[j]]){
ans += m2[(long long)nums1[i] * nums1[j]];
}
}
}
return ans;
}
}; | var numTriplets = function(nums1, nums2) {
const nm1 = new Map(), nm2 = new Map();
const n = nums1.length, m = nums2.length;
for(let i = 0; i < n; i++) {
for(let j = i + 1; j < n; j++) {
const product = nums1[i] * nums1[j];
if(!nm1.has(product)) nm1.set(product, 0);
const arr = nm1.get(product);
nm1.set(product, arr + 1);
}
}
for(let i = 0; i < m; i++) {
for(let j = i + 1; j < m; j++) {
const product = nums2[i] * nums2[j];
if(!nm2.has(product)) nm2.set(product, 0);
const arr = nm2.get(product);
nm2.set(product, arr + 1);
}
}
let ans = 0;
for(let num of nums1) {
const sq = num * num;
if(nm2.has(sq)) {
ans += nm2.get(sq);
}
}
for(let num of nums2) {
const sq = num * num;
if(nm1.has(sq)) {
ans += nm1.get(sq);
}
}
return ans;
}; | Number of Ways Where Square of Number Is Equal to Product of Two Numbers |
You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
Example 2:
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2nd factor is 7.
Example 3:
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
Constraints:
1 <= k <= n <= 1000
Follow up:
Could you solve this problem in less than O(n) complexity?
| class Solution:
def kthFactor(self, n: int, k: int) -> int:
start=[1]
end=[n]
for i in range(2,math.ceil(math.sqrt(n))+1):
if n%i==0:
start.append(i)
if i!=n//i:
end.append(n//i)
start=sorted(set(start).union(set(end)))
if k<=len(start):
return start[k-1]
else:
return -1 | class Solution {
public int kthFactor(int n, int k) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (n % i == 0){
list.add(i);
}
}
if (list.size() < k){
return -1;
}
return list.get(k-1);
}
} | class Solution {
public:
int kthFactor(int n, int k) {
vector<int> sol;
sol.push_back(1);
for(int i = 2; i <= n / 2; i++) {
if(n % i == 0) sol.push_back(i);
}
if(n != 1) sol.push_back(n);
if(k > sol.size()) return -1;
return sol[k - 1];
}
}; | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var kthFactor = function(n, k) {
const res = [1]
for(let i=2; i<n; i++){
if(n%i === 0){
res.push(i)
}
}
res.push(n)
return res[k-1] || -1
}; | The kth Factor of n |
Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.
The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example 1:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: true
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Example 2:
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: false
Example 3:
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: true
Constraints:
1 <= sx, sy, tx, ty <= 109
| from collections import defaultdict
class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
def nextNum(ta,tb,s):
if ta % tb == s % tb:
return min(ta, s)
return ta % tb
visited = defaultdict(bool)
while tx >= sx and ty >= sy and (sx != tx or sy != ty):
if tx > ty:
tx, ty = nextNum(tx, ty, sx), ty
else:
tx, ty = tx, nextNum(ty, tx, sy)
if visited[(tx,ty)]:
break
visited[(tx,ty)] = True
return (sx == tx) and (sy == ty) | class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
if (sx==tx && sy==ty){
return true;
}
if (tx < sx || ty < sy){
return false;
}
return tx<ty?
reachingPoints(sx, sy, tx, Math.min(ty%tx+sy/tx*tx,ty-tx))
: reachingPoints(sx, sy, Math.min(tx%ty+sx/ty*ty,tx-ty), ty);
}
} | /*
Explanation:
Let's say at some point we have coordinates as (a,b)
if(a>b) then at the previous step coordinate must be (a-b,b)
as it can't be (a,b-a) because all the coordinates are positive and for a>b... b-a<0
this continues till the point when a becomes <=b
we can run a loop till there but its time taking
we can observe that the above phenomeon occurs till it becomes (a%b,b)
example :
for (50,7) it would have been like this:
(50,7)...(43,7)...(36,7)...........(8,7)..(1,7)
1 = 50%7
By repeating this procedure, after the loop, we have to test if sx == tx or sy == ty. There is still a condition to test.
Let see we got sy = ty = 5 and have the following result
sx,sy = (16,5)
tx,ty = (21,5)
now if we run our program then it will stop at (1,5) which is not equal to sx,sy and will return false
however during our iteration we will encounter (16,5) infact after the first iteration only but according to our current code it won't detect it
so at the end we apply another condition:
check if (tx - sx) % ty == 0. In our case, (21 - 16) mod 5 = 0 so we can return true.
*/
class Solution
{
public:
// METHOD - 1
bool reachingPoints_recursive(int sx, int sy, int tx, int ty)
{
if (sx > tx || sy > ty)
{
return false;
}
if (sx == tx && sy == ty)
{
return true;
}
bool canReach = reachingPoints_recursive(sx, sx+sy, tx, ty);
if (!canReach)
{
canReach = reachingPoints_recursive(sx+sy, sy, tx, ty);
}
return canReach;
}
// METHOD - 2
bool reachingPoints_internal(int sx, int sy, int tx, int ty)
{
if (sx > tx || sy > ty)
{
return false;
}
else if (sx == tx && sy == ty)
{
return true;
}
while (tx > sx && ty > sy)
{
if (tx > ty)
{
// implies previous path to this tx, ty should have to be tx-ty, ty
// and this could continue till either tx < ty i.e difference would be tx % ty
// so instead of doing that repeatedly just go the final point where
// tx would have started before started adding ty to it repeatedly
tx = tx % ty;
}
else
{
// implies previous path to this tx, ty should have to be (tx, ty-tx)
// and this could continue till either tx > ty i.e difference would be tx % ty
// so instead of doing that repeatedly just go the final point where
// ty would have started before started adding tx to it repeatedly
ty = ty % tx;
}
}
if ((tx == sx) && ((ty - sy) % sx == 0) )
{
return true;
}
else if ((ty == sy) && ((tx - sx) % sy == 0))
{
return true;
}
return false;
}
bool reachingPoints(int sx, int sy, int tx, int ty)
{
// Method-1 : recurssion - will not work for larger numbers as stack will use up all the memory
// return reachingPoints_recursive(sx, sy, tx, ty);
// Method-2 : Effecient non recursive solution
return reachingPoints_internal(sx, sy, tx, ty);
}
}; | /**
* @param {number} sx
* @param {number} sy
* @param {number} tx
* @param {number} ty
* @return {boolean}
*/
var reachingPoints = function(sx, sy, tx, ty) {
while (tx >= sx && ty >= sy) {
if (tx == ty) break;
if (tx > ty) {
if (ty > sy) tx %= ty;
else return (tx - sx) % ty == 0;
} else {
if (tx > sx) ty %= tx;
else return (ty - sy) % tx == 0;
}
}
return (tx == sx && ty == sy);
}; | Reaching Points |
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Example 2:
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
Constraints:
The number of nodes in the list is n.
1 <= k <= n <= 105
0 <= Node.val <= 100
| class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
tot = 0 # initialise total
Head = head
while Head: # count total nodes
Head = Head.next # move forward
tot += 1 # incerse count by one for each node
one, two = None, None # two pointers of one and two
count = 1 # we're initialising to one because we have one based index for swapping
Head = head # regain original head to traverse
while Head:
if one and two: break # if we have both one and two then break loop to save time
if count == k: # if from forward we reach at node k then it's our first node
one = Head
if count == (tot-k+1): # if from backward we reach to node k then save it
two = Head
Head = Head.next # move further
count += 1 # increse count
one.val, two.val = two.val, one.val # now swap values
return head # return head | class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
ListNode first = head, second = head;
// Put fast (k-1) nodes after slow
for(int i = 0; i < k - 1; ++i)
fast = fast.next;
// Save the node for swapping
first = fast;
// Move until the end of the list
while(fast.next != null) {
slow = slow.next;
fast = fast.next;
}
// Save the second node for swapping
// Note that the pointer second isn't necessary: we could use slow for swapping as well
// However, having second improves readability
second = slow;
// Swap values
int temp = first.val;
first.val = second.val;
second.val = temp;
return head;
}
} | class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
// declare a dummy node
ListNode* dummy = new ListNode(0);
// point dummy -> next to head
dummy -> next = head;
// declare a tail pointer and point to dummy
ListNode* tail = dummy;
// move the curr pointer (k - 1) times
// this will maintain a gap of (k - 1) between curr and tail pointer
ListNode* curr = head;
while(k > 1)
{
curr = curr -> next;
k--;
}
// store the address in start pointer
ListNode* start = curr;
// maintaing a gap of (k - 1) between curr and tail, move both pointer
while(curr)
{
tail = tail -> next;
curr = curr -> next;
}
// store the address of kth node from end
ListNode* end = tail;
// swap the values
swap(start -> val, end -> val);
// dummy -> next will be head
return dummy -> next;
}
}; | var swapNodes = function(head, k) {
let A = head, B = head, K, temp
for (let i = 1; i < k; i++) A = A.next
K = A, A = A.next
while (A) A = A.next, B = B.next
temp = K.val, K.val = B.val, B.val = temp
return head
}; | Swapping Nodes in a Linked List |
You are given a 0-indexed integer array nums whose length is a power of 2.
Apply the following algorithm on nums:
Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.
For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).
For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).
Replace the array nums with newNums.
Repeat the entire process starting from step 1.
Return the last number that remains in nums after applying the algorithm.
Example 1:
Input: nums = [1,3,5,2,4,8,2,2]
Output: 1
Explanation: The following arrays are the results of applying the algorithm repeatedly.
First: nums = [1,5,4,2]
Second: nums = [1,4]
Third: nums = [1]
1 is the last remaining number, so we return 1.
Example 2:
Input: nums = [3]
Output: 3
Explanation: 3 is already the last remaining number, so we return 3.
Constraints:
1 <= nums.length <= 1024
1 <= nums[i] <= 109
nums.length is a power of 2.
| class Solution:
def minMaxGame(self, a: List[int]) -> int:
def solve(n):
if n==1:
return
for i in range(n//2):
if i%2:
a[i] = max (a[2*i], a[2*i+1])
else:
a[i] = min (a[2*i], a[2*i+1])
solve(n//2)
return
solve(len(a))
return a[0] | class Solution {
public int minMaxGame(int[] nums) {
var isMin = true;
var n=1;
while(n<nums.length) {
for(int i=0; i<nums.length; i+= n*2) {
nums[i] = isMin ?
Math.min(nums[i], nums[i+n]) :
Math.max(nums[i], nums[i+n]);
isMin = !isMin;
}
n *= 2;
}
return nums[0];
}
} | class Solution {
public:
int minMaxGame(vector<int>& nums) {
int n = nums.size();
if(n==1) return nums[0]; // Base case
vector<int> newNum(n/2);
for(int i=0; i<n/2; i++) {
if(i%2==0) newNum[i] = min(nums[2 * i], nums[2 * i + 1]);
else newNum[i] = max(nums[2 * i], nums[2 * i + 1]);
}
int res = minMaxGame(newNum); // Recursive call
return res;
}
}; | var minMaxGame = function(nums) {
while (nums.length > 1) {
let half = nums.length / 2;
for (let i = 0; i < half; i++)
nums[i] = i % 2 === 0 ? Math.min(nums[2 * i], nums[2 * i + 1]) : Math.max(nums[2 * i], nums[2 * i + 1]);
nums.length = half;
}
return nums[0];
}; | Min Max Game |
The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Input: nums = [1,1,1], k = 2
Output: 0
Example 3:
Input: nums = [1,6,1], k = 3
Output: 5
Constraints:
n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
| from heapq import heappush, heappop, heapify
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
# pairs = list(combinations(nums, 2))
maxHeap = []
heapify(maxHeap)
for idx, val1 in enumerate(nums):
for val2 in nums[idx + 1:]:
pair = [val1, val2]
heappush(maxHeap, [-1*abs(pair[0] - pair[1]), pair])
if len(maxHeap) > k:
heappop(maxHeap)
return -1*maxHeap[0][0] | class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int low = 0, high = nums[nums.length-1] - nums[0];
while(low<=high){
int mid = low + (high-low)/2;
if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1;
else low = mid + 1;
}
return low;
}
private int noOfDistancesLessThan(int dist,int[] nums){
int count = 0,i = 0, j = 0;
while(i<nums.length){
while(j<nums.length && nums[j]-nums[i]<=dist){ // sliding window
j++;
}
count += j-i-1;
i++;
}
return count;
}
} | class Solution {
public:
int count(vector<int> &temp,int mid){
int i=0,j=0,n=temp.size();
int len=0;
while(i<n){
while(j<n && (temp[j]-temp[i])<=mid) j++;
len+=j-i-1;
i++;
}
return len;
}
int smallestDistancePair(vector<int>& nums, int k) {
int s=0,e=1e6;
int ans=0;
vector<int> temp=nums;
sort(temp.begin(),temp.end());
while(s<=e){
int mid=s+(e-s)/2;
if(count(temp,mid)>=k){
ans=mid;
e=mid-1;
}else {
s=mid+1;
}
}
return ans;
}
}; | var smallestDistancePair = function(nums, k) {
nums.sort((a,b) => a - b);
let left = 0, right = nums[nums.length-1] - nums[0], mid = null, total = 0;
while (left < right) {
mid = left + Math.floor((right - left) / 2);
total = 0;
for (var i = 0, j = 1; i < nums.length - 1 && total <= k; i++) {
for ( ; j < nums.length && nums[j] - nums[i] <= mid; j++) {}
total += j - i - 1;
}
if (total >= k) {right = mid;}
else {left = mid+1;}
}
return left;
}; | Find K-th Smallest Pair Distance |
A Bitset is a data structure that compactly stores bits.
Implement the Bitset class:
Bitset(int size) Initializes the Bitset with size bits, all of which are 0.
void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs.
void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs.
void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.
boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.
boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.
int count() Returns the total number of bits in the Bitset which have value 1.
String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.
Example 1:
Input
["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"]
[[5], [3], [1], [], [], [0], [], [], [0], [], []]
Output
[null, null, null, null, false, null, null, true, null, 2, "01010"]
Explanation
Bitset bs = new Bitset(5); // bitset = "00000".
bs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010".
bs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010".
bs.flip(); // the value of each bit is flipped, so bitset = "10101".
bs.all(); // return False, as not all values of the bitset are 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101".
bs.flip(); // the value of each bit is flipped, so bitset = "11010".
bs.one(); // return True, as there is at least 1 index with value 1.
bs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010".
bs.count(); // return 2, as there are 2 bits with value 1.
bs.toString(); // return "01010", which is the composition of bitset.
Constraints:
1 <= size <= 105
0 <= idx <= size - 1
At most 105 calls will be made in total to fix, unfix, flip, all, one, count, and toString.
At least one call will be made to all, one, count, or toString.
At most 5 calls will be made to toString.
| class Bitset(object):
def __init__(self, size):
self.a = 0
self.size = size
self.cnt = 0
def fix(self, idx):
if self.a & (1 << idx) == 0:
self.a |= 1 << idx
self.cnt += 1
def unfix(self, idx):
if self.a & (1 << idx):
self.a ^= 1 << idx
self.cnt -= 1
def flip(self):
self.a ^= (1 << self.size) - 1
self.cnt = self.size - self.cnt
def all(self):
return self.cnt == self.size
def one(self):
return self.a > 0
def count(self):
return self.cnt
def toString(self):
a = bin(self.a)[2:]
return a[::-1] + '0' * (self.size - len(a)) | class Bitset {
int size;
Set<Integer> one = new HashSet<>();
Set<Integer> zero = new HashSet<>();
public Bitset(int size) {
this.size = size;
for(int i=0;i<size;i++) zero.add(i);
}
public void fix(int idx) {
one.add(idx);
zero.remove(idx);
}
public void unfix(int idx) {
one.remove(idx);
zero.add(idx);
}
//swapping object's referrence is O(1)
public void flip() {
Set<Integer> s = one;
one = zero;
zero = s;
}
public boolean all() {
return one.size() == size;
}
public boolean one() {
return one.size()>=1;
}
public int count() {
return one.size();
}
public String toString() {
StringBuilder sb= new StringBuilder();
for(int i=0;i<size;i++) {
if(one.contains(i)) sb.append("1");
else if(zero.contains(i)) sb.append("0");
}
return sb.toString();
}
} | class Bitset {
public:
vector<int>arr;
int cnt,cntflip;
Bitset(int size) {
arr.resize(size,0);
cnt=0,cntflip=0;
}
void fix(int idx) {
// means current bit is 0 ,so set it to 1
if((arr[idx]+cntflip)%2==0){
arr[idx]++;
cnt++;
}
}
void unfix(int idx) {
// means current bit is 1,so set it to 0
if((arr[idx]+cntflip)%2!=0){
arr[idx]--;
cnt--;
}
}
void flip() {
// cnt will flip ,if we flip all the bits
cnt=arr.size()-cnt;
cntflip++;
}
bool all() {
if(cnt==arr.size())
return true;
return false;
}
bool one() {
if(cnt>=1)
return true;
return false;
}
int count() {
return cnt;
}
string toString() {
string ans;
for(auto &ele :arr){
if((cntflip+ele)%2==0)
ans.push_back('0');
else
ans.push_back('1');
}
return ans;
}
}; | var Bitset = function(size) {
//this.bits = new Array(size).fill(0);
//this.bitsOp = new Array(size).fill(1);
this.set0 = new Set();
this.set1 = new Set();
for (let i = 0; i<size; i++) this.set0.add(i);
};
/**
* @param {number} idx
* @return {void}
*/
Bitset.prototype.fix = function(idx) {
//this.bits[idx] = 1;
//this.bitsOp[idx] = 0;
if (this.set0.has(idx)) {
this.set1.add(idx);
this.set0.delete(idx);
}
};
/**
* @param {number} idx
* @return {void}
*/
Bitset.prototype.unfix = function(idx) {
//this.bits[idx] = 0;
//this.bitsOp[idx] = 1;
if (this.set1.has(idx)) {
this.set0.add(idx);
this.set1.delete(idx);
}
};
/**
* @return {void}
*/
Bitset.prototype.flip = function() {
//this.bits = this.bits.map(x=>(x)?0:1);
//this.bits.forEach(x=>x=(x)?0:1);
[this.set0, this.set1] = [this.set1, this.set0];
};
/**
* @return {boolean}
*/
Bitset.prototype.all = function() {
//return (this.bits.filter(x=>x).length == this.bits.length)
//return !this.bits.includes(0);
//for (let i = 0; i<this.bits.length; i++)
//if (this.bits[i] === 0) return false;
//return true;
return this.set0.size===0
};
/**
* @return {boolean}
*/
Bitset.prototype.one = function() {
//return this.bits.filter(x=>x).length>0
//return this.bits.includes(1);
//for (let i = 0; i<this.bits.length; i++)
//if (this.bits[i] === 1) return true;
//return false;
return this.set1.size>0;
};
/**
* @return {number}
*/
Bitset.prototype.count = function() {
//return this.bits.filter(x=>x).length
//return this.bits.reduce((sum, cur)=>sum+cur);
return this.set1.size;
};
/**
* @return {string}
*/
Bitset.prototype.toString = function() {
//return this.bits.join('');
let set = new Array(this.set0.size+this.set1.size);
for (let i=0; i<set.length; i++) {
set[i] = this.set0.has(i)?0:1;
}
return set.join('');
}; | Design Bitset |
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
t is a subsequence of the string s.
The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.
Return the length of the longest ideal string.
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.
Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
Example 1:
Input: s = "acfgbd", k = 2
Output: 4
Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned.
Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.
Example 2:
Input: s = "abcd", k = 3
Output: 4
Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.
Constraints:
1 <= s.length <= 105
0 <= k <= 25
s consists of lowercase English letters.
| class Solution:
def longestIdealString(self, s: str, k: int) -> int:
DP = [0 for _ in range(26)]
ans = 1
for ch in s:
i = ord(ch) - ord('a')
DP[i] = DP[i] + 1
for j in range(max(0, i - k), min(25, i + k) + 1):
if j != i:
DP[i] = max(DP[i], DP[j] + 1)
ans = max(ans, DP[i])
return ans | class Solution {
public int longestIdealString(String s, int k) {
int DP[] = new int[26], ans = 1;
for (int ch = 0, n = s.length(); ch < n; ch++) {
int i = s.charAt(ch) - 'a';
DP[i] = DP[i] + 1;
for (int j = Math.max(0, i - k); j <= Math.min(25, i + k); j++)
if (j != i)
DP[i] = Math.max(DP[i], DP[j] + 1);
ans = Math.max(ans, DP[i]);
}
return ans;
}
} | class Solution {
public:
int longestIdealString(string s, int k) {
int DP[26] = {0}, ans = 1;
for (char &ch: s) {
int i = ch - 'a';
DP[i] = DP[i] + 1;
for (int j = max(0, i - k); j <= min(25, i + k); j++)
if (j != i)
DP[i] = max(DP[i], DP[j] + 1);
ans = max(ans, DP[i]);
}
return ans;
}
}; | var longestIdealString = function(s, k) {
let n = s.length
let dp = Array(26).fill(0);
let ans = 0;
for(let i=0; i<n; i++){
const cur = s.charCodeAt(i)-97;
dp[cur] += 1;
for(let j=Math.max(0, cur-k); j<=Math.min(cur+k, 25); j++){
if(j !== cur){
dp[cur] = Math.max(dp[cur], dp[j]+1);
}
}
ans = Math.max(dp[cur], ans)
}
return ans;
}; | Longest Ideal Subsequence |
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
| class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
for i in range(0, 10001):
if head == None: return False
head = head.next
return True | public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
boolean result = false;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
result = true;
break;
}
}
return result;
}
} | class Solution {
public:
bool hasCycle(ListNode *head) {
// if head is NULL then return false;
if(head == NULL)
return false;
// making two pointers fast and slow and assignning them to head
ListNode *fast = head;
ListNode *slow = head;
// till fast and fast-> next not reaches NULL
// we will increment fast by 2 step and slow by 1 step
while(fast != NULL && fast ->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
// At the point if fast and slow are at same address
// this means linked list has a cycle in it.
if(fast == slow)
return true;
}
// if traversal reaches to NULL this means no cycle.
return false;
}
}; | /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
function hasCycle(head){
let fast = head;
while (fast && fast.next) {
head = head.next;
fast = fast.next.next;
if (head === fast) return true;
}
//head and first pointers value in
//each iteration with head=[3,2,0,-4], pos = 1
//1st iteration: 3 3
//2nd iteration: 2 0
//3rd iteration: 0 2
//final iteration: -4 -4
return false;
}; | Linked List Cycle |
Given a binary tree with the following rules:
root.val == 0
If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2
Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.
Implement the FindElements class:
FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.
bool find(int target) Returns true if the target value exists in the recovered binary tree.
Example 1:
Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]);
findElements.find(1); // return False
findElements.find(2); // return True
Example 2:
Input
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
Output
[null,true,true,false]
Explanation
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False
Example 3:
Input
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Output
[null,true,false,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True
Constraints:
TreeNode.val == -1
The height of the binary tree is less than or equal to 20
The total number of nodes is between [1, 104]
Total calls of find() is between [1, 104]
0 <= target <= 106
| # 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 FindElements:
def __init__(self, root: Optional[TreeNode]):
def recoverTree(root):
if not root:
return None
self.vals.add(root.val)
if root.left:
root.left.val = 2 * root.val + 1
recoverTree(root.left)
if root.right:
root.right.val = 2 * root.val + 2
recoverTree(root.right)
self.vals = set()
root.val = 0
recoverTree(root)
def find(self, target: int) -> bool:
return target in self.vals
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target) | class FindElements {
TreeNode tree,nodept;
public FindElements(TreeNode root) {
tree=root;
tree.val=0;
go(tree);
}
void go(TreeNode node){
if(node.left!=null){
node.left.val=node.val*2+1;
go(node.left);
}
if(node.right!=null){
node.right.val=node.val*2+2;
go(node.right);
}
}
public boolean find(int target) {
return doit(target);
}
boolean doit(int target){
if(target==0){
nodept=tree;
return true;
}
boolean f=doit((target-1)/2);
if(!f)return false;
if(nodept.left!=null && nodept.left.val==target)
nodept=nodept.left;
else if(nodept.right!=null && nodept.right.val==target)
nodept=nodept.right;
else f=false;
return f;
}
} | /**
* 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 FindElements {
public:
void initialize(TreeNode* root,unordered_set<int> &s){
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
auto t = q.front();
q.pop();
s.insert(t->val);
if(t->left != NULL){
t->left->val = 2*(t->val)+1;
q.push(t->left);
}
if(t->right != NULL){
t->right->val= 2*(t->val)+2;
q.push(t->right);
}
}
}
unordered_set<int> s;
FindElements(TreeNode* root) {
root->val = 0;
initialize(root,s);
}
bool find(int target) {
if(s.find(target) != s.end())
return true;
return false;
}
};
/**
* Your FindElements object will be instantiated and called as such:
* FindElements* obj = new FindElements(root);
* bool param_1 = obj->find(target);
*/``` | /**
* 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
*/
var FindElements = function(root) {
this.st = new Set()
recover = (root, val) =>{
this.st.add(val);
if(root.left != null) recover(root.left, val * 2 + 1)
if(root.right != null) recover(root.right, val * 2 + 2)
}
recover(root, 0)
};
/**
* @param {number} target
* @return {boolean}
*/
FindElements.prototype.find = function(target) {
return this.st.has(target)
};
/**
* Your FindElements object will be instantiated and called as such:
* var obj = new FindElements(root)
* var param_1 = obj.find(target)
*/ | Find Elements in a Contaminated Binary Tree |
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity) Initializes the object with the capacity of the data structure.
int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.
void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.
To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.
The functions get and put must each run in O(1) average time complexity.
Example 1:
Input
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
Explanation
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
Constraints:
0 <= capacity <= 104
0 <= key <= 105
0 <= value <= 109
At most 2 * 105 calls will be made to get and put.
| class Node:
def __init__(self, key, val, cnt=1, nxxt=None, prev=None):
self.key = key
self.val = val
self.cnt = cnt
self.nxxt = nxxt
self.prev = prev
class NodeList(Node):
def __init__(self):
self.head = Node(0,0)
self.tail = Node(0,0)
self.head.nxxt = self.tail
self.tail.prev = self.head
self.size = 0
def addFront(self, node):
temp = self.head.nxxt
self.head.nxxt = node
node.prev = self.head
node.nxxt = temp
temp.prev = node
self.size += 1
def removeNode(self, node):
delprev = node.prev
delnxxt = node.nxxt
delprev.nxxt = delnxxt
delnxxt.prev = delprev
self.size -= 1
class LFUCache(NodeList):
def __init__(self, capacity: int):
self.keyNode = {}
self.freqNodeList = {}
self.maxSizeCache = capacity
self.currSize = 0
self.minFreq = 0
def updateFreqNodeList(self, node):
del self.keyNode[node.key]
nodelist = self.freqNodeList[node.cnt]
nodelist.removeNode(node)
if node.cnt == self.minFreq and self.freqNodeList[node.cnt].size == 0:
self.minFreq += 1
if (node.cnt+1) in self.freqNodeList:
nextHigherFreqNodeList = self.freqNodeList[node.cnt+1]
else:
nextHigherFreqNodeList = NodeList()
node.cnt += 1
nextHigherFreqNodeList.addFront(node)
self.freqNodeList[node.cnt] = nextHigherFreqNodeList
self.keyNode[node.key] = node
def get(self, key: int) -> int:
if key in self.keyNode:
node = self.keyNode[key]
ans = node.val
self.updateFreqNodeList(node)
return ans
else:
return -1
def put(self, key: int, value: int) -> None:
if self.maxSizeCache == 0:
return
if key in self.keyNode:
node = self.keyNode[key]
node.val = value
self.updateFreqNodeList(node)
return
else:
if self.currSize == self.maxSizeCache:
nodelist = self.freqNodeList[self.minFreq]
del self.keyNode[nodelist.tail.prev.key]
nodelist.removeNode(nodelist.tail.prev)
self.currSize -= 1
self.currSize += 1
self.minFreq = 1
if self.minFreq in self.freqNodeList:
nodelist = self.freqNodeList[self.minFreq]
else:
nodelist = NodeList()
node = Node(key, value)
nodelist.addFront(node)
self.keyNode[key] = node
self.freqNodeList[self.minFreq] = nodelist
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) | class LFUCache {
// Declare Node class for Doubly Linked List
class Node{
int key,value,freq;// to store key,value and frequency
Node prev,next;// Next and Previous Pointers
Node(int k,int v){
// initializing in constructor
key=k;
value=v;
freq=1;
}
}
// Declare class for List of Doubly Linked List
class List{
int size;
Node head,tail;
List(){
// initializing in constructor
size=0;
head=new Node(-1,-1);// Default values
tail=new Node(-1,-1);
head.next=tail;
tail.prev=head;
}
// To insert at the start of the list
void ins(Node newNode){
Node temp=head.next;
head.next=newNode;
newNode.prev=head;
newNode.next=temp;
temp.prev=newNode;
size++;
}
// To delete specific node
void del(Node newNode){
Node pr=newNode.prev;
Node nx=newNode.next;
pr.next=nx;
nx.prev=pr;
size--;
}
}
Map<Integer,Node>mp;// to store key and Node
Map<Integer,List>listMap;// to store frequency and Doubly Linked List
int maxSize,minFreq,currSize;// to store total size , minimum frequency and current size of the list
public LFUCache(int capacity) {
// initializing in constructor
maxSize=capacity;
minFreq=0;
currSize=0;
mp=new HashMap<Integer,Node>();
listMap=new HashMap<Integer,List>();
}
public int get(int key) {
// if map contains the specific key
if(mp.containsKey(key)){
Node node=mp.get(key);
int val=node.value;
updateFreq(node);// to update the frequency of the node
return val;
}
//otherwise
return -1;
}
public void put(int key, int value) {
// one of the corner case
if(maxSize==0)
return;
// if map contains the specific key
if(mp.containsKey(key)){
Node node=mp.get(key);
node.value=value; // update the value of the node
updateFreq(node);// to update the frequency of the node
}
else{
// if current size is equal to spcified capacity of the LFU list
if(maxSize==currSize){
List list=listMap.get(minFreq);
mp.remove(list.tail.prev.key);// to remove the LRU of the LFU from key-node map
// here LFU is list and even if its is a single element or multiple tail.prev(LRU) is the required element
list.del(list.tail.prev);// to remove the LRU of the LFU from freq-list map
currSize--;
}
currSize++;
minFreq=1;// reset minFreq to 1 because of adding new node
List list= new List();
// If listMap already contains minFreq list
if(listMap.containsKey(minFreq)){
list=listMap.get(minFreq);
}
Node node = new Node(key,value);// creating a new node
list.ins(node); // inserting new node to the list
mp.remove(key);
mp.put(key,node); // inserting updated new node to the key-node map
listMap.remove(minFreq);
listMap.put(minFreq,list);// inserting updated list to the listMap
}
}
public void updateFreq(Node newNode){
mp.remove(newNode.key);// to remove the node from key-node map
listMap.get(newNode.freq).del(newNode);// to remove the node from listmap
// If node's freq was minimum and after removing it from the listMap, size is 0
if(newNode.freq==minFreq && listMap.get(newNode.freq).size==0){
minFreq++;
}
List higherFreqList= new List();
// If listMap already contains node's freq +1 th list
if(listMap.containsKey(newNode.freq+1)){
higherFreqList= listMap.get(newNode.freq+1);
}
newNode.freq++; // updating node's frequency
higherFreqList.ins(newNode); // inserting node to list
listMap.remove(newNode.freq);
listMap.put(newNode.freq,higherFreqList);// reinserting list to listMap
mp.remove(newNode.key);
mp.put(newNode.key,newNode);// reinserting node to key-node map
}
} | class list_node {
public:
int key, val, cnt;
list_node* next;
list_node* prev;
list_node(int k, int v, list_node* n, list_node* p) {
key = k; val = v; cnt = 1;
next = n; prev = p;
}
};
class LFUCache {
public:
int min_cnt;
bool zero;
unordered_map<int, list_node*> key2node;
unordered_map<int, pair<list_node*, list_node*>> cnt2list;
LFUCache(int capacity) {
cin.tie(0); ios_base::sync_with_stdio(0);
min_cnt = 0;
c = capacity;
zero = (c == 0);
}
int get(int key) {
if(zero) return -1;
auto it = key2node.find(key);
if(it == key2node.end() || it->second == NULL) return -1;
addcnt(key);
return it->second->val;
}
void put(int key, int value) {
if(zero) return;
auto it = key2node.find(key);
if(it != key2node.end() && it->second != NULL) {
addcnt(key);
it->second->val = value;
return;
}
if(c) --c;
else {
key2node[cnt2list[min_cnt].first->key] = NULL;
list_node* tmp = cnt2list[min_cnt].first;
if(tmp->next) tmp->next->prev = NULL;
cnt2list[min_cnt].first = tmp->next;
if(cnt2list[min_cnt].second == tmp) cnt2list[min_cnt].second = NULL;
}
min_cnt = 1;
list_node* node = new list_node(key, value, NULL, NULL);
key2node[key] = node;
if(cnt2list.find(1) == cnt2list.end() || cnt2list[1].first == NULL) {
cnt2list[1].first = cnt2list[1].second = node;
}
else {
node->prev = cnt2list[1].second;
cnt2list[1].second->next = node;
cnt2list[1].second = node;
}
}
private:
int c;
void addcnt(int key) {
if(cnt2list[key2node[key]->cnt].first == key2node[key])
cnt2list[key2node[key]->cnt].first = key2node[key]->next;
if(cnt2list[key2node[key]->cnt].second == key2node[key])
cnt2list[key2node[key]->cnt].second = key2node[key]->prev;
if(min_cnt == key2node[key]->cnt && cnt2list[key2node[key]->cnt].first == NULL) min_cnt++;
key2node[key]->cnt++;
if(key2node[key]->prev) key2node[key]->prev->next = key2node[key]->next;
if(key2node[key]->next) key2node[key]->next->prev = key2node[key]->prev;
key2node[key]->next = NULL;
auto lit = cnt2list.find(key2node[key]->cnt);
if(lit == cnt2list.end() || lit->second.first == NULL) {
cnt2list[key2node[key]->cnt].first = cnt2list[key2node[key]->cnt].second = key2node[key];
key2node[key]->prev = NULL;
}
else {
key2node[key]->prev = cnt2list[key2node[key]->cnt].second;
cnt2list[key2node[key]->cnt].second->next = key2node[key];
cnt2list[key2node[key]->cnt].second = key2node[key];
}
}
}; | /**
* @param {number} capacity
*/
var LFUCache = function(capacity) {
this.capacity = capacity;
this.cache = [];
};
/**
* @param {number} key
* @return {number}
*/
LFUCache.prototype.get = function(key) {
let val = -1;
if (!this.capacity) return val;
const existIndex = this.cache.findIndex(item => item.key === key);
if (existIndex > -1) {
const item = this.cache[existIndex];
val = item.value;
item.count++;
this.cache.splice(existIndex, 1);
this.cache.unshift(item);
}
return val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LFUCache.prototype.put = function(key, value) {
if (!this.capacity) return;
const existIndex = this.cache.findIndex(item => item.key === key);
if (existIndex > -1) {
// new item already existsοΌrewrite the value and increase count
const existItem = this.cache[existIndex];
existItem.value = value;
existItem.count++;
this.cache.splice(existIndex, 1);
this.cache.unshift(existItem);
} else {
// new item doesn't exist
if (this.cache.length === this.capacity) {
// reach the capacity, need to clear LFU
let lfuIndex = 0;
let leastCount = this.cache[lfuIndex].count;
for (let i = 1; i < this.cache.length; i++) {
const item = this.cache[i];
if (item.count <= leastCount) {
leastCount = item.count;
lfuIndex = i;
}
}
this.cache.splice(lfuIndex, 1);
// after clear LFU, push the new item
this.cache.unshift({
key,
value,
count: 1
});
} else {
// new item can be pushed
this.cache.unshift({
key,
value,
count: 1
});
}
}
};
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = new LFUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/ | LFU Cache |
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
| class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
cmp=strs[0]
for i in range(1,len(strs)):
l=0
if (len(cmp)>len(strs[i])):
l+=len(strs[i])
else:
l+=len(cmp)
ans=""
for j in range(l):
if (cmp[j]!=strs[i][j]):
if (j==0):
return ""
else:
break
else:
ans+=strs[i][j]
cmp=ans
return cmp
Upvote If you Like!!! | class TrieNode{
TrieNode[] childs;
int frequency;
TrieNode(){
childs = new TrieNode[26];
this.frequency = 1;
}
}
class Solution {
TrieNode root = new TrieNode();
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) return "";
if(strs.length == 1) return strs[0];
for(String str : strs){
insertIntoTrie(str.toLowerCase());
}
return findCommonPrefix(strs[0], strs.length);
}
private void insertIntoTrie(String str) {
TrieNode ptr = root;
for(int i=0; i<str.length(); i++){
if(ptr.childs[str.charAt(i)-'a'] == null){
ptr.childs[str.charAt(i)-'a'] = new TrieNode();
} else {
ptr.childs[str.charAt(i)-'a'].frequency++;
}
ptr = ptr.childs[str.charAt(i)-'a'];
}
}
private String findCommonPrefix(String str, int n) {
String ans = "";
for(int i=0; i<str.length(); i++){
if(root.childs[str.charAt(i) -'a'].frequency != n){
return ans;
}
ans += str.charAt(i);
root = root.childs[str.charAt(i)-'a'];
}
return ans;
}
} | class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
//brute
string ans="";
string ref=strs[0];
for(int i=0;i<ref.size();i++)
{
int j=1;
for(;j<strs.size();j++)
{
if(ref[i]!=strs[j][i])
break;
}
if(j==strs.size())
ans+=ref[i];
else
break;
}
return ans;
}
}; | var longestCommonPrefix = function(strs) {
let commonStr=strs[0];
for(let i=1; i<strs.length;i++){
let currentStr= strs[i]
for(let j=0; j<commonStr.length;j++){
if (commonStr[j]!==currentStr[j]){
commonStr=currentStr.slice(0,j)
break;
}
}
}
return commonStr | Longest Common Prefix |
You have a RecentCounter class which counts the number of recent requests within a certain time frame.
Implement the RecentCounter class:
RecentCounter() Initializes the counter with zero recent requests.
int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
Example 1:
Input
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output
[null, 1, 2, 3, 3]
Explanation
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3
Constraints:
1 <= t <= 109
Each test case will call ping with strictly increasing values of t.
At most 104 calls will be made to ping.
| class RecentCounter:
# Here we use list to store ping details.
def __init__(self):
self.store = []
def ping(self, t: int) -> int:
# Basically what we need to return is how many pings fall in the range(t-3000, t).
# So here we append every t. Now in loop how many t from left side < t-3000, we just pop them
# and return the length of the list, which'd contain elements in range(t-3000, t).
# And since every t is going to greater than previous, we don't need to think about duplicates.
self.store.append(t)
while self.store[0] < t-3000:
self.store.pop(0)
return len(self.store) | class RecentCounter {
ArrayList<Integer> calls ;
public RecentCounter() {
calls = new ArrayList<Integer>();
}
public int ping(int t) {
calls.add(t);
int count = 0;
for(Integer call:calls){
if( t-call<=3000) count++;
}
return count;
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/ | class RecentCounter {
public:
queue<int> q;
RecentCounter() {
}
int ping(int t) {
q.push(t);
int x = q.front();
while(x < t-3000){
q.pop(); x = q.front();
}
return q.size();
}
}; | var RecentCounter = function() {
this.arr = [];
};
RecentCounter.prototype.ping = function(t) {
this.arr.push(t);
while(t > this.arr[0]+3000){
this.arr.shift();
}
return this.arr.length;
}; | Number of Recent Calls |
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aba", t = "baba"
Output: 6
Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
The underlined portions are the substrings that are chosen from s and t.
ββExample 2:
Input: s = "ab", t = "bb"
Output: 3
Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
("ab", "bb")
("ab", "bb")
("ab", "bb")
ββββThe underlined portions are the substrings that are chosen from s and t.
Constraints:
1 <= s.length, t.length <= 100
s and t consist of lowercase English letters only.
| class Solution:
def countSubstrings(self, s: str, t: str) -> int:
res = 0
for i in range(len(s)):
for j in range(len(t)):
miss, pos = 0, 0
while i + pos < len(s) and j + pos < len(t) and miss < 2:
miss += s[i + pos] != t[j + pos]
res += miss == 1
pos += 1
return res | // version 1 : O(mn) space
class Solution {
public int countSubstrings(String s, String t) {
int m = s.length(), n = t.length();
int[][][] dp = new int[m][n][2];
int res = 0;
// first col s[0:i] match t[0:0]
for (int i = 0; i < m; i++) {
dp[i][0][0] = (s.charAt(i) == t.charAt(0)) ? 1 : 0;
dp[i][0][1] = (s.charAt(i) == t.charAt(0)) ? 0 : 1;
res += dp[i][0][1];
}
// first row s[0:0] match t[0:j]
for (int j = 1; j < n; j++) {
dp[0][j][0] = (s.charAt(0) == t.charAt(j)) ? 1 : 0;
dp[0][j][1] = (s.charAt(0) == t.charAt(j)) ? 0 : 1;
res += dp[0][j][1];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j][0] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][0] + 1 : 0;
dp[i][j][1] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][1] : dp[i-1][j-1][0] + 1;
res += dp[i][j][1];
}
}
return res;
}
} | class Solution {
public:
int countSubstrings(string s, string t)
{
int n=s.size();
int m=t.size();
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int diff=0;
for(int k=0;i+k<n&&j+k<m;k++)
{
if(s[i+k]!=t[j+k])
{
diff++;
}
if(diff>1)
{
break;
}
ans+=diff;
}
}
}
return ans;
}
}; | var countSubstrings = function(s, t) {
const count1 = countAllSubstr(s);
const count2 = countAllSubstr(t);
let res = 0;
for (const [substr1, freq1] of count1) {
for (const [substr2, freq2] of count2) {
if (differByOneChar(substr1, substr2)) {
res += freq1 * freq2;
}
}
}
return res;
function countAllSubstr(str) {
const n = str.length;
const count = new Map();
for (let i = 0; i < n; i++) {
let substr = "";
for (let j = i; j < n; j++) {
substr += str.charAt(j);
if (!count.has(substr)) count.set(substr, 0);
count.set(substr, count.get(substr) + 1);
}
}
return count;
}
function differByOneChar(str1, str2) {
if (str1.length != str2.length) return false;
const n = str1.length;
let missed = 0;
for (let i = 0; i < n; i++) {
const char1 = str1.charAt(i);
const char2 = str2.charAt(i);
if (char1 != char2) missed++;
if (missed > 1) return false;
}
return missed === 1;
}
}; | Count Substrings That Differ by One Character |
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList class:
MyLinkedList() Initializes the MyLinkedList object.
int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
void addAtTail(int val) Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]
Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
Constraints:
0 <= index, val <= 1000
Please do not use the built-in LinkedList library.
At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.
| class Node:
def __init__(self, val: int):
self.val = val
self.next = None
self.prev = None
class MyLinkedList:
def __init__(self):
self.head = Node(0)
self.tail = Node(0)
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
# Distance of index is closer to head
if index + 1 < self.size - index:
curr = self.head
for i in range(index + 1):
curr = curr.next
# Distance of index is closer to tail
else:
curr = self.tail
for i in range(self.size - index):
curr = curr.prev
return curr.val
def addAtHead(self, val: int) -> None:
curr = Node(val)
prevNode = self.head
nextNode = self.head.next
self.size += 1
curr.prev = prevNode
curr.next = nextNode
prevNode.next = curr
nextNode.prev = curr
def addAtTail(self, val: int) -> None:
curr = Node(val)
prevNode = self.tail.prev
nextNode = self.tail
self.size += 1
curr.prev = prevNode
curr.next = nextNode
prevNode.next = curr
nextNode.prev = curr
def addAtIndex(self, index: int, val: int) -> None:
curr = Node(val)
if index > self.size:
return
if index < 0:
index = 0
if index < self.size - index:
prevNode = self.head
for i in range(index):
prevNode = prevNode.next
nextNode = prevNode.next
else:
nextNode = self.tail
for i in range(self.size - index):
nextNode = nextNode.prev
prevNode = nextNode.prev
self.size += 1
curr.prev = prevNode
curr.next = nextNode
prevNode.next = curr
nextNode.prev = curr
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
if index < self.size - index:
prevNode = self.head
for i in range(index):
prevNode = prevNode.next
nextNode = prevNode.next.next
else:
nextNode = self.tail
for i in range(self.size - index - 1):
nextNode = nextNode.prev
prevNode = nextNode.prev.prev
self.size -= 1
prevNode.next = nextNode
nextNode.prev = prevNode
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index) | class MyLinkedList {
public class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
private ListNode head;
private ListNode tail;
private int length;
public MyLinkedList() {
length = 0;
}
public int get(int index) {
if (index > length - 1 || index < 0) return -1;
int thisIndex = 0;
ListNode temp = head;
while (thisIndex != index) {
temp = temp.next;
thisIndex++;
}
return temp.val;
}
public void addAtHead(int val) {
head = new ListNode(val, head);
length++;
if (length == 1) tail = head;
}
public void addAtTail(int val) {
length++;
if (length == 1) {
ListNode onlyNode = new ListNode(val);
head = onlyNode;
tail = head;
return;
}
tail.next = new ListNode(val);
tail = tail.next;
}
public void addAtIndex(int index, int val) {
if (index <= length) {
if (index == 0) {
addAtHead(val);
return;
}
if (index == length) {
addAtTail(val);
return;
}
length++;
ListNode temp = head;
int thisIndex = 0;
while (thisIndex != index - 1) {
temp = temp.next;
thisIndex++;
}
temp.next = new ListNode(val, temp.next);
}
}
public void deleteAtIndex(int index) {
if (index >= length || index < 0) return;
length--;
if (index == 0) {
head = head.next;
return;
}
ListNode temp = head;
int thisIndex = 0;
while (thisIndex != index - 1) {
temp = temp.next;
thisIndex++;
}
if (index == length) {
tail = temp;
temp.next = null;
}
else temp.next = temp.next.next;
}
} | class MyLinkedList {
struct Node{
int val;
Node *next,*prev;
Node(int x){val=x,next=prev=NULL;}
};
Node *head;int size;
public:
MyLinkedList() {
head=NULL;size=0;
}
int get(int index) {
if(index>=size or index<0) return -1;
Node *ptr=head;
for(int i=0;i<index;i++) ptr=ptr->next;
return ptr->val;
}
void addAtHead(int val) {
Node *newNode=new Node(val);
newNode->next=head;
if(head) head->prev=newNode;
head=newNode;
size++;
}
void addAtTail(int val) {
addAtIndex(size,val);
}
void addAtIndex(int index, int val) {
if(index<0 or index>size) return;
if(index==0){
addAtHead(val);return;
}
Node *newNode=new Node(val);
Node *prev=head;
for(int i=0;i<index-1;i++){
prev=prev->next;
}
newNode->next=prev->next;
prev->next=newNode;
newNode->prev=prev;
if(newNode->next) newNode->next->prev=newNode;
size++;
}
void deleteAtIndex(int index) {
if(index>=size or index<0) return;
if(index==0){
Node *temp=head;
head=head->next;
delete temp;size--;
return;
}
Node *del=head;
for(int i=0;i<index;i++){
del=del->next;
}
if(del->prev) del->prev->next=del->next;
if(del->next) del->next->prev=del->prev;
delete del;
size--;
}
}; | var MyLinkedList = function() {
this.linked = [];
};
MyLinkedList.prototype.get = function(index) {
if(index < this.linked.length){
return this.linked[index];
}
return -1;
};
MyLinkedList.prototype.addAtHead = function(val) {
this.linked.unshift(val);
};
MyLinkedList.prototype.addAtTail = function(val) {
this.linked.push(val);
};
MyLinkedList.prototype.addAtIndex = function(index, val) {
if(index <= this.linked.length){
this.linked.splice(index,0,val);
}
};
MyLinkedList.prototype.deleteAtIndex = function(index) {
this.linked.splice(index,1);
}; | Design Linked List |
Given an integer array nums, handle multiple queries of the following types:
Update the value of an element in nums.
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.
void update(int index, int val) Updates the value of nums[index] to be val.
int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
Example 1:
Input
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
Output
[null, 9, null, 8]
Explanation
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
0 <= index < nums.length
-100 <= val <= 100
0 <= left <= right < nums.length
At most 3 * 104 calls will be made to update and sumRange.
| class NumArray:
nums = []
s = 0
l = 0
def __init__(self, nums: List[int]):
self.nums = nums
self.s = sum(nums)
self.l = len(nums)
def update(self, index: int, val: int) -> None:
self.s -= self.nums[index]
self.nums[index] = val
self.s += self.nums[index]
def sumRange(self, left: int, right: int) -> int:
if right - left > self.l // 2:
ans = sum(self.nums[:left]) + sum(self.nums[right + 1:])
return self.s - ans
else:
return sum(self.nums[left: right + 1]) | class NumArray {
SegmentTree s;
public NumArray(int[] nums) {
s = new SegmentTree(nums);
s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built
}
public void update(int index, int val) {
int oldvalue = s.arr[index];//Find old value with traditional array, which is O(1) time complexity
s.arr[index] = val;//Set our array so that there will be no contradictions if we ever rebuild.
//If we are going use build function only once, then we don't need to update our traditional array.
s.update(s.root, val, index, oldvalue);//Call class' function
}
public int sumRange(int left, int right) {
return s.rangeSum(s.root, left, right);
}
}
class Node {
int s;//inclusive label
int e;//inclusive label
int val;
Node left;
Node right;
}
class SegmentTree {
Node root;
int[] arr;
SegmentTree(int [] arr) {
this.arr = arr;
}
public Node build(int start, int end, int[] arr) {
//Start and End integers have nothing to do with building of our SegmentTree, you may ignore them for now
//They are needed for querying and updating, so that we can use binary search.
Node temp = new Node();
if (arr.length == 1) {//which means we are setting a node equal to an element of arr
temp.val = arr[0];
temp.s = start;
temp.e = end-1;//to make it inclusive
} else if (arr.length == 0 || start > end || start < 0 || end < 0) {
return new Node();// may be better
} else {
//left = build(start, mid but add 1 if array's length is not divisible by 2, left half of the passed array)
temp.left = build(start, (start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), Arrays.copyOfRange(arr, 0, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0)));
//right = build(start, mid but add 1 if array's length is not divisible by 2, right half of the passed array)
temp.right = build((start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), end, Arrays.copyOfRange(arr, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0), arr.length));
temp.val = temp.left.val + temp.right.val;
temp.s = start;
temp.e = end-1;//to make it inclusive
}
return temp;//return this Node to one upper call so that this can be a child of it's parent
}
public int rangeSum(Node node, int l, int r) {
if(node == null)
{
//Range is completely outside given range
return 0;
}
if(l <= node.s && node.e <= r)
{
//Range is completely inside given range
return node.val;
}
//Range is partially inside and partially outside the given range
int mid = (node.s + node.e) / 2;
int left = 0;
int right = 0;
if (l <= mid) {
//For example let's say root's borders are 0:3, l,r=1:2
//Then mid will be 1, then we will go into both directions because 1<=1, and 2>=1
//Our next calls will be rS(root.left(which is 0:1), 1, 2) and rS(root.right(which is 2:3), 1, 2)
//Left call's mid will be mid = (0+1)/2 = 0
//Then 1<=0 ? No it's not, this is why left call's variable named left will be 0
//Then 2>=0 ? Yes, we will call rS(root.left.right(which is 1:1), 1, 2)
//Our left call's right call:
//1:1 is completely inside 1:2, return the value it holds(equals to arr[1] if our arr is up to date)
//Our original call's left will be arr[1]
//Let's calculate our first right function
//With same reasoning, our right function will go to left and be root.right.left(which is 2:2)
//Our original call's right will be arr[2]
//Our original/first function will return left + right, which is in fact [1:2] inclusive
left = rangeSum(node.left, l, r);
}
if (r >= mid) {
right = rangeSum(node.right, l, r);
}
return (left + right);
}
//What we are doing is, going downwards in our tree while we update the values we touch upon
//We need to update root always, since it is sum of every element
//After that we find mid which is mid value of our current node's start and end(inclusive)
//At first call this will be (0+arr.length)/2 => mid
//If given idx is bigger than mid, then we need to keep searching at right branch
//That is why we call the function with root.right as our new root
//If given idx is smaller and equals to mid, then we search at left branch
//Why did we include equality too? Because I built my tree this way.(where equal things go left)
//If idx is between our root's borders then we will decrease by the old value, increase by the new value.
//If root equals null, we won't do anything
//We update our traditional array at above.
public void update(Node root, int value, int idx, int oldvalue) {
if (root == null) {
return;
}
int mid = (root.e + root.s) / 2;
if (idx <= root.e && idx >= root.s) {
root.val -= oldvalue;
root.val += value;
} if (idx > mid) {
update(root.right, value, idx, oldvalue);
} else if (idx <= mid) {
update(root.left, value, idx, oldvalue);
}
}
} | class NumArray {
public:
vector<int>v; //vector to store input vector.
int sum; //sum of all element of vector
NumArray(vector<int>& nums) {
v=nums;
sum=0;
for(int i=0;i<nums.size();i++){
sum+=nums[i];
}
}
void update(int index, int val) {
sum-=v[index]; //subtract old element from sum at index and then update by adding new element val.
v[index]=val;
sum+=val;
}
int sumRange(int left, int right) {
int res=sum;
for(int i=0;i<left;i++){ //subtract all element before left and after right
res-=v[i];
}
for(int i=right+1;i<v.size();i++){
res-=v[i];
}
return res;// return res ie. our answer.
}
}; | var NumArray = function(nums) {
this.nums = nums;
this.n = nums.length;
this.fenwickTree = new Array(this.n + 1).fill(0);
nums.forEach((num, index) => this.init(index, num));
};
NumArray.prototype.init = function(index, val) {
let j = index + 1;
while(j <= this.n) {
this.fenwickTree[j] += val;
j += this.lsb(j);
}
};
NumArray.prototype.lsb = function(index) {
return index & ~(index - 1);
};
NumArray.prototype.update = function(index, val) {
const diff = val - this.nums[index];
this.nums[index] = val;
this.init(index, diff);
};
NumArray.prototype.getSum = function(index) {
let j = index + 1;
let sum = 0;
while(j > 0) {
sum += this.fenwickTree[j];
j -= this.lsb(j);
}
return sum;
};
NumArray.prototype.sumRange = function(left, right) {
return this.getSum(right) - this.getSum(left - 1);
}; | Range Sum Query - Mutable |
You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.
Example 3:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr does not have value 9 and it can never be converted to target.
Constraints:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
| class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
target.sort()
arr.sort()
if len(target)==len(arr):
if target==arr:
return True
else:
return False | class Solution {
public boolean canBeEqual(int[] target, int[] arr) {
HashMap<Integer,Integer>hm1=new HashMap();
for(int i: arr){
if(hm1.containsKey(i))
hm1.put(i,hm1.get(i)+1);
else
hm1.put(i,1);
}
for(int i: target){
if(hm1.containsKey(i)){
hm1.put(i,hm1.getOrDefault(i,0)-1);
if(hm1.get(i)==0)
hm1.remove(i);
}
else
return false;
}
if(hm1.size()==0)
return true;
return false;
}
} | class Solution {
public:
bool canBeEqual(vector<int>& target, vector<int>& arr) {
int arr1[1001]={0};
int arr2[1001]={0};
for(int i =0 ; i<target.size(); i++)
{
arr1[arr[i]]++;
arr2[target[i]]++;
}
for(int i =0 ;i<=1000;i++)
{
if(arr1[i]!=arr2[i])
return false;
}
return true;
}
}; | var canBeEqual = function(target, arr) {
if(arr.length==1){
if(arr[0]===target[0]){
return true
}
}
let obj = {}
for(let i =0;i<arr.length; i ++){
if(obj[arr[i]]==undefined){
obj[arr[i]]=1
}else{
obj[arr[i]]++
}
}
for(let i =0;i<target.length; i ++){
if(obj[target[i]]==undefined){
return false
}else{
obj[target[i]]++
}
}
let result = Object.values(obj)
for(let i =0; i <result.length; i ++){
if(result[i]%2!==0){
return false
}
}
return true
}; | Make Two Arrays Equal by Reversing Sub-arrays |
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.
Example 1:
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
Example 2:
Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
Example 3:
Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.
Constraints:
1 <= jobDifficulty.length <= 300
0 <= jobDifficulty[i] <= 1000
1 <= d <= 10
| class Solution:
def solve(self, nums, index, d):
if index == len(nums) or d == 1:
#print(max(nums[index:]))
return max(nums[index:])
ans = float("inf")
for i in range(index, len(nums)-d+1):
curr = max(nums[index:i+1]) + self.solve(nums, i+1, d-1)
ans = min(ans, curr)
return ans
def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:
ans = self.solve(jobDifficulty, 0, d)
if ans == float("inf"):
return -1
else:
return ans | class Solution {
// Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray.
public int minDifficulty(int[] jobDifficulty, int d) {
if(d>jobDifficulty.length){
return -1;
}
int[][] memo = new int[d+1][jobDifficulty.length];
for(int[] m : memo){
Arrays.fill(m, -1);
}
return getMinDays(jobDifficulty, d, memo, 0);
}
private int getMinDays(int[] jobDifficulty, int d, int[][] memo, int idx){
if(d==1){
int max=0;
while(idx < jobDifficulty.length){
max=Math.max(max, jobDifficulty[idx]);
idx++;
}
return max;
}
if(memo[d][idx] != -1) return memo[d][idx];
int max=0;
int res=Integer.MAX_VALUE;
// [6,5,4,3,2,1], d=5 => we don't want the cut at 4th position in the array because we won't be able to divide it into 5 parts
for(int i=idx; i<jobDifficulty.length-d+1; i++){
max = Math.max(max, jobDifficulty[i]);
res = Math.min(res, max + getMinDays(jobDifficulty, d-1, memo, i+1));
}
memo[d][idx]=res;
return memo[d][idx];
}
} | class Solution {
vector<int> v;
int len;
int dp[301][11];
int dfs(int idx, int d){//n*d
if(idx>=len)
return 0;
if(d==1)
return *max_element(v.begin()+idx,v.end());
if(dp[idx][d]!=-1)
return dp[idx][d];
int maxx=INT_MIN;
int res=INT_MAX;
for(int i=idx;i<=len-d;i++){//n
maxx=max(v[i],maxx);
res=min(maxx+dfs(i+1,d-1),res);
}
return dp[idx][d]=res;
}
public:
int minDifficulty(vector<int>& jobDifficulty, int d) {
v=jobDifficulty;
len=v.size();
if(d>len)
return -1;
memset(dp,-1,sizeof(dp));
return dfs(0,d);
}
}; | var minDifficulty = function(jobDifficulty, d) {
// don't have enought jobs to distribute
if (jobDifficulty.length < d) {
return -1;
}
// in dynamic programming top-down approach
// we need to have memoisation to not repeat calculations
let memo = new Array(d+1).fill(-1).map(
() => new Array(jobDifficulty.length+1).fill(-1)
)
const dp = function(D, N) {
// if we calculated this before, just return
if (-1 != memo[D][N]) {
return memo[D][N];
}
// if we have only 1 day, we just need to take all jobs
// and return the highest difficulty
if (1 == D) {
memo[D][N] = 0;
for (let i = 0; i < N; i++) {
if (memo[D][N] < jobDifficulty[i]) {
memo[D][N] = jobDifficulty[i];
}
}
return memo[D][N];
}
// otherwise, we use our recurrence relation to calculate
memo[D][N] = 1000 * D;
let max_job_per_day = N - D + 1;
let max_difficulty = 0;
// iteration for recurrence relation
for (let X = 1; X <= max_job_per_day; X++) {
// count max in the current range
// len - X is the starting point for
// the last day in D days
if (jobDifficulty[N - X] > max_difficulty) {
max_difficulty = jobDifficulty[N - X];
}
// recurrence relation
// we took X jobs,
// so we still have N - X jobs for D - 1 days
let min_sum = max_difficulty + dp(D - 1, N - X);
// pick the min only
if (min_sum < memo[D][N]) {
memo[D][N] = min_sum;
}
}
return memo[D][N];
}
return dp(d, jobDifficulty.length);
} | Minimum Difficulty of a Job Schedule |
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
| class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
di = (0, 1, 0, -1)
dj = (1, 0, -1, 0)
m, n = len(heights), len(heights[0])
visited = [[False] * n for _ in range(m)]
h = [(0, 0, 0)]
while h:
effort, i, j = heappop(h)
if visited[i][j]:
continue
visited[i][j] = True
if i + 1 == m and j + 1 == n:
return effort ## have reached the (m-1, n-1) cell
for k in range(4):
ii, jj = i + di[k], j + dj[k]
if 0 <= ii < m and 0 <= jj < n and not visited[ii][jj]:
neffort = max(effort, abs(heights[i][j] - heights[ii][jj]))
heappush(h, (neffort, ii, jj))
return ## cell (m-1, n-1) not reachable, should never happen | class Tuple {
int distance;
int row;
int col;
Tuple(int distance, int row, int col) {
this.distance = distance;
this.row = row;
this.col = col;
}
}
class Solution {
public int minimumEffortPath(int[][] heights) {
// Create a min heap based on the distance
PriorityQueue<Tuple> minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);
int rows = heights.length;
int cols = heights[0].length;
// Create a 2D array to store the minimum effort to reach each cell
int effort[][] = new int[rows][cols];
// Initialize all efforts to maximum initially
for (int i = 0; i < rows; i++) {
Arrays.fill(effort[i], Integer.MAX_VALUE);
}
effort[0][0] = 0; // Initial effort at the starting cell
// Add the starting cell to the min heap
minHeap.add(new Tuple(0, 0, 0));
// Arrays to represent row and column changes for 4 directions
int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left
int dc[] = {0, 1, 0, -1};
while (!minHeap.isEmpty()) {
Tuple current = minHeap.poll(); // Get the cell with the minimum effort
int distance = current.distance;
int row = current.row;
int col = current.col;
if (row == rows - 1 && col == cols - 1) {
return distance; // If reached the destination, return the effort
}
// Explore each of the 4 possible directions
for (int i = 0; i < 4; i++) {
int newRow = row + dr[i]; // Calculate new row index
int newCol = col + dc[i]; // Calculate new column index
// Check if the new cell is within bounds
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {
// Calculate the new effort based on the maximum of height difference and current effort
int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);
// If the new effort is less than the stored effort for the cell, update and add to heap
if (newEffort < effort[newRow][newCol]) {
effort[newRow][newCol] = newEffort;
minHeap.add(new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration
}
}
}
}
return 0; // This value should be replaced with the actual minimum effort
}
} | #define pii pair<int, pair<int,int>>
class Solution {
public:
//Directions (top, right, bottom, left)
const int d4x[4] = {-1,0,1,0}, d4y[4] = {0,1,0,-1};
int minimumEffortPath(vector<vector<int>>& h) {
int n = h.size(), m = h[0].size();
//min-heap
priority_queue <pii, vector<pii>, greater<pii>> pq;
//to store distances from (0,0)
vector<vector<int>> dis(n, vector<int>(m, INT_MAX));
dis[0][0] = 0;
pq.push({0, {0, 0}});
//Dijstra algorithm
while(!pq.empty()) {
pii curr = pq.top(); pq.pop();
int d = curr.first, r = curr.second.first, c = curr.second.second;
// bottom right position
if(r==n-1 && c==m-1) return d;
for(int i=0; i<4; ++i) {
int nx = r + d4x[i], ny = c + d4y[i];
//check if new position is invalid
if(nx < 0 || nx >= n || ny < 0 || ny >= m)continue;
//nd => new distance: which is max of distance till now(d) and curr distance (difference between heights of current cells)
int nd = max(d, abs(h[nx][ny] - h[r][c]));
if (nd < dis[nx][ny]) {
dis[nx][ny] = nd;
pq.push({nd, {nx, ny}});
}
}
}
return 0;
//please upvote
}
}; | /**
* @param {number[][]} heights
* @return {number}
* T: O((M*N)log(M*N))
* S: O(M*N)
*/
var minimumEffortPath = function(heights) {
const directions = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1],
];
const row = heights.length;
const col = heights[0].length;
const differences = [];
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (!differences[i]) {
differences[i] = [Infinity];
} else {
differences[i].push(Infinity);
}
}
}
differences[0][0] = 0;
const pq = new PriorityQueue();
pq.push([0, 0], 0);
while (pq.data.length > 0) {
const node = pq.shift();
const difference = node.priority;
const [x, y] = node.val;
directions.forEach(([dx, dy]) => {
const newX = x + dx;
const newY = y + dy;
if (newX >= 0 && newX < row && newY >= 0 && newY < col) {
const currentDiff = Math.abs(heights[newX][newY] - heights[x][y]);
const maxDiff = Math.max(currentDiff, differences[x][y]);
if (differences[newX][newY] > maxDiff) {
differences[newX][newY] = maxDiff;
pq.push([newX, newY], maxDiff);
}
}
});
}
return differences[row - 1][col - 1];
};
const swap = (arr, i, j) => {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
function Node(val, priority) {
this.val = val;
this.priority = priority;
}
function PriorityQueue() {
this.data = [];
}
PriorityQueue.prototype.push = function push(val, priority) {
const node = new Node(val, priority);
this.data.push(node);
let index = this.data.length - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.data[parentIndex];
if (parent.priority > node.priority) {
swap(this.data, parentIndex, index);
index = parentIndex;
} else {
break;
}
}
};
PriorityQueue.prototype.shift = function shift() {
const minNode = this.data[0] || {};
const lastNode = this.data.pop();
if (this.data.length < 1) {
return minNode;
}
this.data[0] = lastNode;
let index = 0;
while (index < this.data.length) {
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
const leftNode = this.data[leftIndex] || {};
const rightNode = this.data[rightIndex] || {};
let smallerIndex;
if (leftNode.priority < lastNode.priority) {
smallerIndex = leftIndex;
}
if (!smallerIndex && rightNode.priority < lastNode.priority) {
smallerIndex = rightIndex;
}
if (smallerIndex && rightNode.priority < leftNode.priority) {
smallerIndex = rightIndex;
}
if (!smallerIndex) {
break;
}
swap(this.data, index, smallerIndex);
index = smallerIndex;
}
return minNode;
}; | Path With Minimum Effort |
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer 1 is missing.
Constraints:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
| class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
mn = float('inf')
mx = 0
numsSet = set()
for i in range(len(nums) - 1, -1, -1):
if nums[i] > 0:
if nums[i] < mn:
mn = nums[i]
if nums[i] > mx:
mx = nums[i]
numsSet.add(nums[i])
del nums[i]
if mn >= 2:
return 1
if len(numsSet) == mx:
return mx + 1
for i in range(2, len(numsSet) + 1):
if i not in numsSet:
return i | class Solution {
public int firstMissingPositive(int[] nums) {
//cyclic sort
int i = 0;
while (i<nums.length){
int correct = nums[i]-1;
if(nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[correct]){
swap(nums,i,correct);
}else{
i++;
}
}
//linear search to find the missing number
for(int index=0;index<nums.length;index++){
if (nums[index] != index+1) {
return index+1;
}
}
//if array has all the elements match to its index then 1st missing num will be
//nums.length+1
return nums.length+1;
}
static void swap(int[]arr,int a , int b){
int temp = arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
} | class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i=0; i<n; i++){
if(nums[i]==i+1 || nums[i]<=0 || nums[i]>n) continue;
while(nums[i]!=i+1 && nums[i]>0 && nums[i]<=n && nums[nums[i]-1] != nums[i]){
swap(nums[i],nums[nums[i]-1]);
}
}
int ans = -1;
for(int i=0; i<n; i++){
if(nums[i]!=i+1){
ans = i+1;
break;
}
}
if(ans==-1){
return n+1;
}else{
return ans;
}
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function (nums) {
//first make all negative numbers to zero =>zero means we ignore whis number
for (let index = 0; index < nums.length; index++) {
if (nums[index] < 0)
nums[index] = 0
}
for (let index = 0; index < nums.length; index++) {
const temp = Math.abs(nums[index])
const element = temp - 1
if (element < nums.length && element >= 0)
nums[element] = nums[element] === 0 ? -(nums.length + 1) : Math.abs(nums[element]) * -1
}
for (let index = 0; index < nums.length; index++) {
const element = (nums[index])
if (element >= 0) return index + 1
}
return nums.length+1
}; | First Missing Positive |
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < n and n % x == 0.
Replacing the number n on the chalkboard with n - x.
Also, if a player cannot make a move, they lose the game.
Return true if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: n = 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Constraints:
1 <= n <= 1000
| class Solution:
def divisorGame(self, n: int) -> bool:
"""
let's forget about Alice and Bob for a second and just concentrate on the n and plays
if played optimally :
1 - player at 1 will loose since no factors
2 - player at 2 will win by choosing 1
3 - player at 3 will loose always since he/she has to choose 1. and then next player will always win because they are at 2
4 - player at 4 will win by choosing 1 as a factor as next player will have to play at 3
5 - player at 5 will loose because he has to choose 1, and player at 4 will always win
6 - player at 6 will always win by choosing 3 as a factor
7 - player at 7 will have to choose 1, and hence result 6 will make player at 6 to win
8 - player at 8 can choose 1 and win always
.
.
.
.
Pattern detected
Now, since Alice is the first player we can return bool values accordingly
"""
return n%2 == 0
| class Solution {
public boolean divisorGame(int n) {
return n%2==0;
}
} | class Solution {
public:
bool divisorGame(int n) {
if(n%2==0) return true;
return false;
}
}; | var divisorGame = function(n) {
let count = 0;
while(true){
let flag = true;
for(let i = 1;i<n;i++){
if(n%i==0){
flag = false;
n = n-i;
break;
}
}
if(flag){
if(count %2==0) return false;
else return true;
}
count++;
}
}; | Divisor Game |
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
Choose 2 distinct names from ideas, call them ideaA and ideaB.
Swap the first letters of ideaA and ideaB with each other.
If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
Example 1:
Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
Explanation: The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.
The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
Example 2:
Input: ideas = ["lack","back"]
Output: 0
Explanation: There are no valid selections. Therefore, 0 is returned.
Constraints:
2 <= ideas.length <= 5 * 104
1 <= ideas[i].length <= 10
ideas[i] consists of lowercase English letters.
All the strings in ideas are unique.
| class Solution:
def distinctNames(self, ideas: List[str]) -> int:
names=defaultdict(set)
res=0
#to store first letter as key and followed suffix as val
for i in ideas:
names[i[0]].add(i[1:])
#list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)
arr=list(names.keys())
ans,n=0,len(arr)
for i in range(n):
for j in range(i+1,n):
#a,b => 2 distinct first letters
a,b=arr[i],arr[j]
# adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be "newword1 newword2" or "newword2 newword1"
res+=len(names[a]-names[b])*len(names[b]-names[a])*2
return res
| class Solution {
public long distinctNames(String[] ideas) {
// HashSet + String Manipulation; TC: O(26*26*n); SC: O(26*n)
HashSet<String> [] arr = new HashSet[26];
for(int i=0; i<26; i++) {
arr[i] = new HashSet<>();
}
for(String s: ideas) {
arr[s.charAt(0)-'a'].add(s.substring(1));
}
long ans=0, cnt;
for(int i=0; i<26; i++) {
for(int j=i+1; j<26; j++) {
cnt=0;
for(String str: arr[j]) {
if(arr[i].contains(str)) cnt++;
}
ans+=2*(arr[i].size()-cnt)*(arr[j].size()-cnt);
}
}
return ans;
}
} | class Solution {
public:
long long distinctNames(vector<string>& ideas) {
unordered_map <char,unordered_set<string>> mp;
for(auto u : ideas) mp[u[0]].insert(u.substr(1,u.size()-1));
long long ans = 0;
for(int i = 0; i<26; i++){
for(int j = i+1; j<26; j++){
unordered_set <string> s1 = mp[i+'a'], s2 = mp[j+'a'];
int comm = 0;
for(auto u : s1)
if(s2.find(u)!=s2.end()) comm++;
ans += (long long)(s1.size()-comm)*(long long)(s2.size()-comm)*2;
}
}
return ans;
}
}; | /**
* @param {string[]} ideas
* @return {number}
*/
var distinctNames = function(ideas) {
let res = 0;
let lMap = new Map();
for(let i=0; i<ideas.length; i++){
let idea = ideas[i];
// extract first letter
let l = idea[0].charCodeAt() - 97;
// extract substring
let s = idea.substr(1);
// group substring by first letter
if(lMap.has(l)){
// must use map not array
let m = lMap.get(l);
m.set(s, 1);
lMap.set(l, m);
}else{
let m = new Map();
m.set(s, 1);
lMap.set(l, m);
}
}
for(let i=1; i<26; i++){
for(let j=0; j<i; j++){
// count substring with different first letter
let m = 0;
let m1 = lMap.has(i) ? lMap.get(i) : new Map();
let m2 = lMap.has(j) ? lMap.get(j) : new Map();
// both map must exist
if(m1.size > 0 && m2.size > 0){
let k1 = Array.from(m1.keys());
for(let k=0; k<k1.length; k++){
if(m2.has(k1[k])){
m ++;
}
}
// the rest substring satisfy condition
res += (m1.size - m) * (m2.size-m);
}
}
}
// double for count A + B and B + A
res = res * 2;
return res;
}; | Naming a Company |
You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.
Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.
Example 1:
Input: s = "ilovecodingonleetcode", target = "code"
Output: 2
Explanation:
For the first copy of "code", take the letters at indices 4, 5, 6, and 7.
For the second copy of "code", take the letters at indices 17, 18, 19, and 20.
The strings that are formed are "ecod" and "code" which can both be rearranged into "code".
We can make at most two copies of "code", so we return 2.
Example 2:
Input: s = "abcba", target = "abc"
Output: 1
Explanation:
We can make one copy of "abc" by taking the letters at indices 0, 1, and 2.
We can make at most one copy of "abc", so we return 1.
Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc".
Example 3:
Input: s = "abbaccaddaeea", target = "aaaaa"
Output: 1
Explanation:
We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12.
We can make at most one copy of "aaaaa", so we return 1.
Constraints:
1 <= s.length <= 100
1 <= target.length <= 10
s and target consist of lowercase English letters.
| class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
counter_s = Counter(s)
return min(counter_s[c] // count for c,count in Counter(target).items()) | class Solution
{
public int rearrangeCharacters(String s, String target)
{
int[] freq = new int[26], freq2 = new int[26];
for(char ch : s.toCharArray())
freq[ch-'a']++;
for(char ch : target.toCharArray())
freq2[ch-'a']++;
int min = Integer.MAX_VALUE;
for(char ch : target.toCharArray())
min = Math.min(min,freq[ch-'a']/freq2[ch-'a']);
return min;
}
} | Approach :
=> Take two map, one to store frequency of target, and another for sentence.
=> Traverse over the mp(frequency of target ) and calculate the minimum frequency ratio
mn = min(mn , frequency of a char in sentance / frequency of same char in target) ;
Space : O(n)
Time : O(n)
class Solution {
public:
int rearrangeCharacters(string s, string target) {
unordered_map<char,int> targetFreq ;
for(auto a : target) {
targetFreq[a] ++;
}
unordered_map<char , int> sentFreq ;
for(auto a : s) {
sentFreq[a] ++ ;
}
int mn = INT_MAX ;
for(auto a : targetFreq ) {
mn = min(mn , sentFreq[a.first]/a.second);
}
return mn ;
}
}; | /**
* @param {string} s
* @param {string} target
* @return {number}
*/
var rearrangeCharacters = function(s, target) {
let cnt = Number.MAX_VALUE;
let m1 = new Map();
for(const x of target) m1.set(x , m1.get(x)+1 || 1);
let m2 = new Map();
for(const x of s) m2.set(x , m2.get(x)+1 || 1);
for(let it of m1){
let ch = it[0];
let x = it[1];
let y = m2.get(ch);
if(y === undefined) y=0;
cnt = Math.min(cnt,Math.floor(y/x));
}
return cnt;
}; | Rearrange Characters to Make Target String |
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
| # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return head
cur=head.next
prev=head
while cur is not None:
if cur.val==prev.val:
prev.next=cur.next
else:
prev=cur
cur=cur.next
return head | class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode result = head;
while (result != null) {
if (result.next == null) {
break;
}
if (result.val == result.next.val) {
result.next = result.next.next;
} else {
result = result.next;
}
}
return head;
}
} | class Solution {
public:
// Recursive Approach
ListNode* deleteDuplicates(ListNode* head){
// base case
if(head==NULL || head->next==NULL)
return head;
// 1-1-2-3-3
//we are giving next pointer to recursion and telling it to get it done for me
ListNode* newNode=deleteDuplicates(head->next); // 1-2-3-3
// after recursion we will get-- 1-2-3
//now we will compare the head node with the newNode
// if both are same then return the newNode
//else return the current head
if(head->val==newNode->val)
return newNode;
else{
head->next=newNode;
return head;
}
}
};
class Solution {
public:
// Iterative Approach
ListNode* deleteDuplicates(ListNode* head){
if(head==NULL || head->next==NULL) return head;
ListNode* temp =head;
while(temp->next!=NULL){
// if the 2 consecutive nodes are equal then just delete the in between
if(temp->val==temp->next->val){
temp->next=temp->next->next;
//dont need to update the temp variable as there can be more than 2 duplicates
// 1-1-1-1-2-3-4-4-NULL
}
else{
temp=temp->next; //update the temp variable
}
}
return head;
}
}; | var deleteDuplicates = function(head) {
// Special case...
if(head == null || head.next == null)
return head;
// Initialize a pointer curr with the address of head node...
let curr = head;
// Traverse all element through a while loop if curr node and the next node of curr node are present...
while( curr != null && curr.next != null){
// If the value of curr is equal to the value of prev...
// It means the value is present in the linked list...
if(curr.val == curr.next.val){
// Hence we do not need to include curr again in the linked list...
// So we increment the value of curr...
curr.next = curr.next.next;
}
// Otherwise, we increment the curr pointer...
else{
curr = curr.next;
}
}
return head; // Return the sorted linked list without any duplicate element...
}; | Remove Duplicates from Sorted List |
On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:
The north direction is the positive direction of the y-axis.
The south direction is the negative direction of the y-axis.
The east direction is the positive direction of the x-axis.
The west direction is the negative direction of the x-axis.
The robot can receive one of three instructions:
"G": go straight 1 unit.
"L": turn 90 degrees to the left (i.e., anti-clockwise direction).
"R": turn 90 degrees to the right (i.e., clockwise direction).
The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: instructions = "GGLLGG"
Output: true
Explanation: The robot is initially at (0, 0) facing the north direction.
"G": move one step. Position: (0, 1). Direction: North.
"G": move one step. Position: (0, 2). Direction: North.
"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.
"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.
"G": move one step. Position: (0, 1). Direction: South.
"G": move one step. Position: (0, 0). Direction: South.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).
Based on that, we return true.
Example 2:
Input: instructions = "GG"
Output: false
Explanation: The robot is initially at (0, 0) facing the north direction.
"G": move one step. Position: (0, 1). Direction: North.
"G": move one step. Position: (0, 2). Direction: North.
Repeating the instructions, keeps advancing in the north direction and does not go into cycles.
Based on that, we return false.
Example 3:
Input: instructions = "GL"
Output: true
Explanation: The robot is initially at (0, 0) facing the north direction.
"G": move one step. Position: (0, 1). Direction: North.
"L": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.
"G": move one step. Position: (-1, 1). Direction: West.
"L": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.
"G": move one step. Position: (-1, 0). Direction: South.
"L": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.
"G": move one step. Position: (0, 0). Direction: East.
"L": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).
Based on that, we return true.
Constraints:
1 <= instructions.length <= 100
instructions[i] is 'G', 'L' or, 'R'.
| class Solution:
def isRobotBounded(self, instructions: str) -> bool:
pos, d = [0,0], "N"
def move(d, pos, instructions):
for i in instructions:
if i == "G":
if d == "N": pos[1] += 1
elif d == "S": pos[1] -= 1
elif d == "W": pos[0] -= 1
else: pos[0] += 1
elif i == "L":
if d == "N": d = "W"
elif d == "W": d = "S"
elif d == "S": d = "E"
else: d = "N"
else:
if d == "N": d = "E"
elif d == "W": d = "N"
elif d == "S": d = "W"
else: d = "S"
return (d, pos)
for i in range(4):
d, pos = (move(d, pos, instructions))
return True if pos == [0,0] else False | class Solution {
public boolean isRobotBounded(String instructions) {
if (instructions.length() == 0) {
return true;
}
Robot bender = new Robot();
int[] start = new int[]{0, 0};
// 4 represents the max 90 degree turns that can restart initial orientation.
for (int i = 0; i < 4; i++) {
boolean orientationChanged = bender.performSet(instructions);
int[] location = bender.location;
if (location[0] == start[0] && location[1] == start[1]) {
return true;
}
// If robot never turns and the first instruction isn't at start, exit.
else if (!orientationChanged) {
return false;
}
}
return false;
}
}
class Robot {
int[] location;
int[] orientation;
int[][] orientations;
int orientationPos;
boolean orientationChangeCheck;
Robot() {
// Start in center
location = new int[]{0, 0};
// N, E, S, W
orientations = new int[][]{{1,0}, {0, 1}, {-1, 0}, {0, -1}};
// Start pointing north
orientationPos = 0;
orientation = orientations[orientationPos];
// Track if robot has turned
orientationChangeCheck = false;
}
public boolean performSet(String orders) {
this.orientationChangeCheck = false;
for (int i = 0; i < orders.length(); i++) {
this.perform(orders.charAt(i));
}
return this.orientationChangeCheck;
}
public void perform(char order) {
if (order == 'G') {
this.go();
} else if (order == 'L' || order == 'R') {
this.turn(order);
} else {
// do nothing
}
}
public void turn(char direction) {
if (direction == 'L') {
this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;
} else if (direction == 'R') {
this.orientationPos = (this.orientationPos + 1) % 4;
}
this.orientation = this.orientations[this.orientationPos];
this.orientationChangeCheck = true;
}
public int[] go() {
this.location[0] += this.orientation[0];
this.location[1] += this.orientation[1];
return this.location;
}
} | class Solution {
public:
bool isRobotBounded(string instructions) {
char direction = 'N';
int x = 0, y = 0;
for (char &instruction: instructions) {
if (instruction == 'G') {
if (direction == 'N') y++;
else if (direction == 'S') y--;
else if (direction == 'W') x--;
else x++;
} else if (instruction == 'L') {
if (direction == 'N') direction = 'W';
else if (direction == 'S') direction = 'E';
else if (direction == 'W') direction = 'S';
else direction = 'N';
} else {
if (direction == 'N') direction = 'E';
else if (direction == 'S') direction = 'W';
else if (direction == 'W') direction = 'N';
else direction = 'S';
}
}
return (x == 0 && y == 0) || direction != 'N';
}
}; | var isRobotBounded = function(instructions) {
// north = 0, east = 1, south = 2, west = 3
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
// Initial position is in the center
let x = 0, y = 0;
// facing north
let idx = 0;
let movements = [...instructions];
for (let move of movements) {
if (move == 'L')
idx = (idx + 3) % 4;
else if (move == 'R')
idx = (idx + 1) % 4;
else {
x += directions[idx][0];
y += directions[idx][1];
}
}
// after one cycle:
// robot returns into initial position
// or robot doesn't face north
return (x == 0 && y == 0) || (idx != 0);
}; | Robot Bounded In Circle |
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) | class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1])
return true;
}
return false;
}
} | class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i=0; i<n-1; i++){
if (nums[i]==nums[i+1])
return true;
}
return false;
}
}; | var containsDuplicate = function(nums) {
if(nums.length <= 1) return false;
let cache = {};
let mid = Math.floor(nums.length /2)
let left = mid -1;
let right = mid;
while(left >= 0 || right < nums.length) {
if(nums[left] === nums[right]) {
return true;
};
if(cache[nums[left]]){
return true
} else {
cache[nums[left]] = true;
}
if(cache[nums[right]]){
return true;
} else{
cache[nums[right]] = true;
}
left--;
right++;
}
return false;
}; | Contains Duplicate |
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.
Return the total area. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.
Example 2:
Input: rectangles = [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 1018 modulo (109 + 7), which is 49.
Constraints:
1 <= rectangles.length <= 200
rectanges[i].length == 4
0 <= xi1, yi1, xi2, yi2 <= 109
| class SegmentTree:
def __init__(self, xs):
#cnts[v] means that the node's interval is active
self.cnts = defaultdict(int)
#total[v] length of active intervals that are contained the node's interval
self.total = defaultdict(int)
self.xs = xs
def update(self, v, tl, tr, l, r, h):
#node interval [tl,tr] does not overlap with query interval [l,r]
if r < tl or tr < l: return
#node interval is included in the query interval
if l <= tl and tr <= r:
self.cnts[v] += h
else:
tm = (tl + tr)//2
self.update(v*2, tl, tm, l, r, h)
self.update(v*2+1, tm+1, tr, l, r, h)
#node interval is included in the active interval
if self.cnts[v] > 0:
self.total[v] = self.xs[tr + 1] - self.xs[tl]
else:
self.total[v] = self.total[v*2] + self.total[v*2+1]
return self.total[v]
class Solution:
def rectangleArea(self, rectangles):
#index i means the interval from xs[i] to xs[i+1]
xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))
xs_i = {x:i for i, x in enumerate(xs)}
st = SegmentTree(xs)
L = []
for x1, y1, x2, y2 in rectangles:
L.append([y1, 1, x1, x2])
L.append([y2, -1, x1, x2])
L.sort()
cur_y = cur_x_sum = area = 0
for y, open_close, x1, x2 in L:
area += (y - cur_y) * cur_x_sum
cur_y = y
#one index corresponds to one interval, that's why we use xs_i[x2]-1 instead of xs_i[x2]
st.update(1, 0, len(xs) - 1, xs_i[x1], xs_i[x2]-1, open_close)
cur_x_sum = st.total[1]
return area % (10 ** 9 + 7) | class Solution {
public int rectangleArea(int[][] rectangles) {
int n = rectangles.length;
Set<Integer> coorx = new HashSet<>();
Set<Integer> coory = new HashSet<>();
for (int[] rec : rectangles) {
coorx.add(rec[0]); coorx.add(rec[2]);
coory.add(rec[1]); coory.add(rec[3]);
}
Integer[] compressx = coorx.toArray(new Integer[0]);
Arrays.sort(compressx);
Integer[] compressy = coory.toArray(new Integer[0]);
Arrays.sort(compressy);
Map<Integer, Integer> mapx = new HashMap<>();
for(int i = 0; i < compressx.length; i++) {
mapx.put(compressx[i], i);
}
Map<Integer, Integer> mapy = new HashMap<>();
for(int i = 0; i < compressy.length; i++) {
mapy.put(compressy[i], i);
}
boolean[][] grid = new boolean[compressx.length][compressy.length];
for (int[] rec: rectangles) {
for (int x = mapx.get(rec[0]); x < mapx.get(rec[2]); x++) {
for (int y = mapy.get(rec[1]); y < mapy.get(rec[3]); y++) {
grid[x][y] = true;
}
}
}
long res = 0L;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j]) {
res += (long)(compressx[i + 1] - compressx[i]) * (compressy[j + 1] - compressy[j]);
}
}
}
res %= 1000000007;
return (int)res;
}
} | struct Point
{
int X;
int delta;
};
class Solution
{
public:
int rectangleArea(vector<vector<int>>& rectangles)
{
map<int, vector<Point>> lines; // y -> array of Points
for (auto&r : rectangles)
{
auto x1 = r[0];
auto y1 = r[1];
auto x2 = r[2];
auto y2 = r[3];
lines[y1].push_back(Point {x1, +1});
lines[y1].push_back(Point {x2, -1});
lines[y2].push_back(Point {x1, -1});
lines[y2].push_back(Point {x2, +1});
}
long area = 0;
int prevy = 0;
int length = 0;
map<int, int> scanline; // x -> delta
for (const auto& [y, points] : lines)
{
area += (y - prevy) * (long)length;
// Update scanline for new y: add new rectanhgles,
// remove old
for (auto point : points)
{
auto xdelta = scanline.find(point.X);
if (xdelta != end(scanline))
{
xdelta->second += point.delta;
if (xdelta->second == 0)
scanline.erase(xdelta);
}
else
scanline[point.X] = point.delta;
}
// For current y-line calc the length of
// intersection with rectangles
int startX = -1;
int rectCount = 0;
length = 0;
for (const auto& [x, delta] : scanline)
{
int oldcount = rectCount;
rectCount += delta;
if (oldcount == 0)
startX = x;
else if (rectCount == 0)
length += x - startX;
}
if (rectCount > 0)
length += scanline.rbegin()->first - startX;
prevy = y;
}
return area % (1000000007);
}
}; | var rectangleArea = function(rectangles) {
let events = [], active = [], area = 0n;
let mod = BigInt(1000000007);
for (var rec of rectangles) {
events.push([rec[1], 'open', rec[0], rec[2]]);
events.push([rec[3], 'close', rec[0], rec[2]]);
}
events = events.sort((a, b) => a[0] - b[0]);
let y = events[0][0];
for (var event of events) {
let currY = event[0], type = event[1], x1 = event[2], x2 = event[3];
let maxLength = 0, curr = -1;
for (var ev of active) {
curr = Math.max(curr, ev[0]);
maxLength += Math.max(0, ev[1] - curr);
curr = Math.max(curr, ev[1]);
}
area += (BigInt(maxLength) * BigInt(currY - y));
area %= mod;
if (type === 'open') {
active.push([x1, x2]);
active = active.sort((a, b) => a[0] - b[0]);
} else {
for (var i = 0; i < active.length; i++) {
let e = active[i];
if (e[0] === x1 && e[1] === x2) {
active.splice(i, 1);
break;
}
}
}
y = currY;
}
return area % mod;
}; | Rectangle Area II |
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.
Example 2:
Input: root = [4,3,null,1,2]
Output: 2
Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.
Example 3:
Input: root = [-4,-2,-5]
Output: 0
Explanation: All values are negatives. Return an empty BST.
Constraints:
The number of nodes in the tree is in the range [1, 4 * 104].
-4 * 104 <= Node.val <= 4 * 104
| # 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 maxSumBST(self, root: Optional[TreeNode]) -> int:
# declaire a variable maxSum to hold the max path sum
self.maxSum=0
def getMax(root):
# return max,min,val - if root is null, valid BST
if not root : return (float("-inf"),float("inf"),0)
# traverse left and right part
leftMax,leftMin,leftMaxSum=getMax(root.left)
rightMax,rightMin,rightMaxSum=getMax(root.right)
# if a valid BST
if root.val>leftMax and root.val<rightMin:
# update maxSum
self.maxSum=max(self.maxSum,root.val+leftMaxSum+rightMaxSum)
# return maximum and minimum node values starting from that node and pathSum
return max(root.val,rightMax),min(root.val,leftMin),root.val+leftMaxSum+rightMaxSum
# if not a BST - set an impossible condition such than the root is also returned as non-BST
return (float("inf"),float("-inf"),0)
getMax(root)
return self.maxSum
| class Solution {
int ans = 0;
public int maxSumBST(TreeNode root) {
solve(root);
return ans;
}
// int[] = { min, max, sum };
private int[] solve(TreeNode root) {
if(root == null)
return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 };
int[] left = solve(root.left);
int[] right = solve(root.right);
if(root.val > left[1] && root.val < right[0]) {
int sum = left[2] + right[2] + root.val;
ans = Math.max(ans, sum);
return new int[] { Math.min(left[0], root.val), Math.max(root.val, right[1]), sum };
}
return new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };
}
} | class Solution {
public:
int ans = 0 ;
array<int,4> solve(TreeNode * root){
if(!root) return {1,0,INT_MIN,INT_MAX} ;
array<int,4> l = solve(root->left) ;
array<int,4> r = solve(root->right) ;
if(l[0] and r[0]){
if(root->val > l[2] and root->val < r[3]){
ans = max({ans,l[1],r[1]}) ;
return {1,l[1] + r[1] + root->val,max({root->val,l[2],r[2]}),min({root->val,l[3],r[3]})} ;
}
}
return {0,max(l[1],r[1]),INT_MIN,INT_MAX} ;
}
int maxSumBST(TreeNode* root) {
auto arr = solve(root) ;
return max(ans,arr[1]) ;
}
}; | var maxSumBST = function(root) {
let max = 0;
const dfs = (node) => {
// NoNode
if(!node) return [true, 0, Infinity, -Infinity];
// LeafNode
if(node && !node.left && !node.right) {
max = Math.max(max, node.val);
return [true, node.val, node.val, node.val]
};
const [isLeftValid, leftVal, leftMin, leftMax] = dfs(node.left);
const [isRightValid, rightVal, rightMin, rightMax] = dfs(node.right);
/**
* To establish that the current node is also a valid BST, we need to verify the following:
* 1. Left sub tree is a valid BST
* 2. Right sub tree is a valid BST
* 3. The values in the left BST are smaller than current node's value
* 4. The values in the right BST are greater than current node's value
**/
if(isLeftValid && isRightValid && node.val > leftMax && node.val < rightMin) {
max = Math.max(max, leftVal + rightVal + node.val);
return [
true,
leftVal + rightVal + node.val,
/**
* 12
* / \
* 8 16
* \ /
* 9 15
* \ /
* 10 14
* \ /
* Infinity -Infinity
* [Infinity and -Infinity are to depict NoNode cases]
**/
Math.min(node.val, leftMin),
Math.max(node.val, rightMax)
];
}
return [false, 0, leftMax, rightMin];
}
dfs(root);
return max;
}; | Maximum Sum BST in Binary Tree |
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
| class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
ans = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
if len(ans) == 0 or nums1[i] != ans[-1]:
ans.append(nums1[i])
i += 1
j += 1
return ans | class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] dp = new int[1000];
for(int i:nums1){
dp[i]++;
}
int[] ans = new int[1000];
//declaring ptr to track ans array index
int ptr = 0;
for(int i:nums2){
if(dp[i] != 0){
dp[i] = 0;
ans[ptr] = i;
ptr++;
}
}
return Arrays.copyOfRange(ans, 0, ptr);
}
} | class Solution {
public:
//what i think is we have to return the intersection elements from both nums
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//result vector which will store those values which will be intersecting in both nums
vector<int> result;
//map intersection, which will store values of all the elements in num1
unordered_map<int,int> intersection;
//map will store all the values of num1(as key),with corresponding value 1
for(auto character : nums1)
{
intersection[character] = 1;
}
//this loop will check if any element of num1 is there in num2? if yes, insert it in result
//after inserting it once, make its corresponding value to 0
//so that if you find any elements, that is repeating in num2, as well as present in num1
//so you dont enter it twice in result, you should enter it once only
for(auto character : nums2)
{
//if found once, it's value would be 1, so entered in result
//after it is entered in result, its value we change to 0
//so agin if that same element repeats, due to 0 as its value, we avoid pushing it to result
if(intersection[character])
{
result.push_back(character);
intersection[character] = 0;
}
}
//after getting all the intersecting elements,we return result
return result;
}
}; | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
let set = new Set(nums1);
let set2 = new Set(nums2);
let result = [];
for (const val of set) {
if (set2.has(val)) {
result.push(val);
}
}
return result;
}; | Intersection of Two Arrays |
Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.
Example 1:
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
Example 2:
Input: tree = [7], target = 7
Output: 7
Example 3:
Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4
Constraints:
The number of nodes in the tree is in the range [1, 104].
The values of the nodes of the tree are unique.
target node is a node from the original tree and is not null.
Follow up: Could you solve the problem if repeated values on the tree are allowed?
| class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def DFS(node1,node2):
if node1==target:
return node2
if node1 and node1.left is None and node1.right is None:
return
res1 = DFS(node1.left,node2.left) if node1 else None
if res1 is not None:
return res1
res2 = DFS(node1.right,node2.right) if node1 else None
if res2 is not None:
return res2
res=DFS(original,cloned)
return res | class Solution {
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
TreeNode[] ref = new TreeNode[]{null};
dfs(cloned, target, ref);
return ref[0];
}
public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) {
if (root == null) return;
if (root.val == target.val) {
ref[0] = root;
return;
} else {
dfs(root.left, target, ref);
dfs(root.right, target, ref);
}
}
} | class Solution {
public:
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
if(original == target || original == NULL)
return cloned;
TreeNode* found_left = getTargetCopy(original->left, cloned->left, target);
TreeNode* found_right = getTargetCopy(original->right, cloned->right, target);
if(found_left)
return found_left;
else
return found_right;
}
}; | var getTargetCopy = function(original, cloned, target) {
if( original == null ){
// Base case aka stop condition
// empty tree or empty node
return null;
}
// General cases
if( original == target ){
// current original node is target, so is cloned
return cloned;
}
// Either left subtree has target, or right subtree has target
return getTargetCopy(original.left, cloned.left, target) ||
getTargetCopy(original.right, cloned.right, target);
}; | Find a Corresponding Node of a Binary Tree in a Clone of That Tree |
You are given an array of unique integers salary where salary[i] is the salary of the ith employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
Constraints:
3 <= salary.length <= 100
1000 <= salary[i] <= 106
All the integers of salary are unique.
| class Solution:
def average(self, salary: List[int]) -> float:
return (sum(salary)-min(salary)-max(salary))/(len(salary)-2) | class Solution {
public double average(int[] salary) {
int n = salary.length-2;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int sum = 0;
for(int i=0;i<n+2;i++){
sum += salary[i];
max = Math.max(max,salary[i]);
min = Math.min(min,salary[i]);
}
return (double)(sum-max-min)/n;
}
} | class Solution {
public:
double average(vector<int>& salary) {
int n = salary.size();
double ans=0;
sort(salary.begin(),salary.end());
for(int i=1;i<n-1;i++){
ans+=salary[i];
}
return ans/(n-2);
}
}; | var average = function(salary) {
let max = salary[0], min = salary[salary.length-1], sum = 0;
for(let i = 0; i < salary.length; i++) {
if(salary[i] > max) {
max = salary[i];
}
else if(salary[i] < min) {
min = salary[i];
}
sum += salary[i];
}
return (sum-min-max)/(salary.length-2);
}; | Average Salary Excluding the Minimum and Maximum Salary |
Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares ' '.
The first player always places 'X' characters, while the second player always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O "," "," "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX"," X "," "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XOX","O O","XOX"]
Output: true
Constraints:
board.length == 3
board[i].length == 3
board[i][j] is either 'X', 'O', or ' '.
| class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
# The two criteria for a valid board are:
# 1) num of Xs - num of Os is 0 or 1
# 2) X is not a winner if the # of moves is even, and
# O is not a winner if the # of moves is odd.
d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array
s = [d[ch] for ch in ''.join(board)] # Ex: ["XOX"," X "," "] --> [1,-1,1,0,1,0,0,0,0]
sm = sum(s)
if sm>>1: return False # <-- criterion 1
n = -3 if sm == 1 else 3 # <-- criterion 2.
if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8],
s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are
s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags
return True # <-- both criteria are true | class Solution {
public boolean validTicTacToe(String[] board) {
//cnt number of X and O
int x = cntNumber('X', board);
//this check can be omitted, it can be covered in the second number check.
if(x >5){
return false;
}
int o = cntNumber('O', board);
if(x < o || x > o + 1){
return false;
}
//if(x <3 ) true, no need to see winning
if(o >= 3){
//if x has won, but game doesnt stop
if(x == o && hasWon('X', board)){
return false;
}
//if o has won, but game doesnt stop
if( x > o && hasWon('O', board) ){
return false;
}
}
return true;
}
private int cntNumber(char target, String[] board){
int res = 0;
for(int i = 0; i<3; i++) {
for(int j = 0; j<3; j++) {
if(target == board[i].charAt(j)){
res++;
}
}
}
return res;
}
private boolean hasWon(char target, String[] board){
String toWin = Character.toString(target).repeat(3);
for(int i = 0; i<3; i++) {
if(board[i].equals(toWin)){
return true;
}
}
for(int j = 0; j<3; j++) {
boolean col = true;
for(int i = 0; i<3; i++) {
col = col && target == board[i].charAt(j);
if(!col){
break;
}
}
if(col){
return true;
}
}
//check diagonal. If center is not target, not possible to form diag win.
if(target != board[1].charAt(1)){
return false;
}
boolean diagonal1 = target == board[0].charAt(0);
//only proceed if the first letter match. Otherwise might get false positive
if(diagonal1){
if(target == board[2].charAt(2)){
return true;
}
}
boolean diagonal2 = target == board[0].charAt(2);
if(diagonal2){
if(target == board[2].charAt(0)){
return true;
}
}
return false;
}
} | class Solution {
public:
bool win(vector<string> board, char player, int size){
int row_win=0, col_win=0, diagonal_win=0, rev_diagonal_win=0;
for(int i=0;i<3;i++){
row_win=0;
col_win=0;
for(int j=0;j<3;j++){
if(player == board[i][j]){
row_win++;
if(row_win == 3)
return 1;
}
if(player == board[j][i]){
col_win++;
if(col_win == 3)
return 1;
}
if(i==j && player==board[i][j]){
diagonal_win++;
}
if(i+j == size-1 && player==board[i][j]){
rev_diagonal_win++;
}
}
}
if(diagonal_win==3 || rev_diagonal_win==3)
return 1;
return 0;
}
bool validTicTacToe(vector<string>& board) {
int count_x=0, count_o=0, size = board.size();
for(auto i:board){
for(auto j:i){
if(j=='X') count_x++;
else if(j=='O') count_o++;
}
}
if(count_o>count_x || count_x-count_o>=2)
return false;
if(count_x>=3 && count_x==count_o && win(board, 'X', size))
return false;
if(count_o>=3 && count_x>count_o && win(board, 'O', size))
return false;
return true;
}
}; | var validTicTacToe = function(board) {
let playerX = 0 , playerO = 0;
let horizontal = [0,0,0];
let vertical = [0,0,0];
let diagnol = [0, 0];
const transformConfig=(row,col,val)=>{
horizontal[row] +=val;
vertical[col]+=val;
if(row ===col ){
diagnol[0]+=val;
if(row+col == board.length-1){
diagnol[1]+=val;
}
}else if(row+col == board.length-1){
diagnol[1]+=val;
}
}
board.forEach((data,row)=>{
data.split("").forEach((turn,col)=>{
if(turn == 'X'){
playerX++
transformConfig(row,col,1)
}else if(turn == 'O'){
playerO++;
transformConfig(row,col,-1);
}
});
});
if(playerX<playerO ||playerX-playerO>1 ) return false;
if(horizontal.includes(3)&&playerX<= playerO)return false;
if(vertical.includes(3)&&playerX <= playerO)return false;
if(diagnol.includes(3)&&playerX <=playerO)return false;
if(horizontal.includes(-3)&&playerX> playerO)return false;
if(vertical.includes(-3)&&playerX> playerO)return false;
if(diagnol.includes(-3)&&playerX>playerO)return false;
return true;
}; | Valid Tic-Tac-Toe State |
There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).
Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.
Example 1:
Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation:
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
Example 2:
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
Constraints:
n == heights.length
1 <= n <= 105
1 <= heights[i] <= 105
All the values of heights are unique.
| class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
ans=[]
stack=[]
n=len(heights)
for i in range(n-1,-1,-1):
if len(stack)==0:
ans.append(0)
stack.append(heights[i])
else:
if heights[i]<stack[-1]:
ans.append(1)
stack.append(heights[i])
else:
ctr=0
while(len(stack)>0 and stack[-1]<heights[i]):
ctr+=1
stack.pop()
if len(stack)==0:
ans.append(ctr)
else:
ans.append(ctr+1)
stack.append(heights[i])
return ans[::-1] | class Solution {
public int[] canSeePersonsCount(int[] heights) {
Stack<Integer> stack = new Stack<>();
int result[] = new int[heights.length];
for(int i = heights.length - 1; i >= 0; i--) {
int visibility = 0;
while(!stack.isEmpty() && heights[i] > stack.peek()) {
stack.pop();
visibility++;
}
if(!stack.isEmpty()) visibility++;
stack.push(heights[i]);
result[i] = visibility;
}
return result;
}
} | class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& h) {
vector<int>ans ;
stack<int>s ;
int a = 0;
for(int i = h.size()-1 ; i >= 0 ; i--){
if(s.empty()){
ans.push_back(a);
s.push(h[i]);a++;
}
else{
if(s.top() > h[i]){
ans.push_back(1);
s.push(h[i]);a++;
}
else{
int b = 0;
while(!s.empty() && s.top() < h[i]){
s.pop() ; a--;b++;
}
if(!s.empty())b++;
ans.push_back(b);
s.push(h[i]); a++;
}
}
}
reverse(ans.begin() , ans.end());
return ans;
}
}; | var visibleToRight = function(heights){
const result = new Array(heights.length).fill(0)
const stack = []
let i = heights.length-1
// loop from right to left
while(i >= 0){
let popCount = 0
// Keep Popping untill top ele is smaller
while(stack.length > 0 && stack[stack.length-1][0] < heights[i]){
stack.pop()
popCount+=1
}
/////////////////////
/// After Popping ///
////////////////////
// Case1: if ALL elements got popped
if(stack.length === 0)
result[i] = popCount // mark
// Case2: if NO elements were popped
else if(popCount === 0)
result[i] = 1 // mark
// Case3: if SOME elements were popped
else
result[i] = popCount+1 // mark
// store
stack.push([heights[i],popCount])
i-=1
}
return result
}
var canSeePersonsCount = function(heights) {
return visibleToRight(heights)
}; | Number of Visible People in a Queue |
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].
You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).
Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8]
Output: "832"
Explanation: Replace the substring "1":
- 1 maps to change[1] = 8.
Thus, "132" becomes "832".
"832" is the largest number that can be created, so return it.
Example 2:
Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6]
Output: "934"
Explanation: Replace the substring "021":
- 0 maps to change[0] = 9.
- 2 maps to change[2] = 3.
- 1 maps to change[1] = 4.
Thus, "021" becomes "934".
"934" is the largest number that can be created, so return it.
Example 3:
Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4]
Output: "5"
Explanation: "5" is already the largest number that can be created, so return it.
Constraints:
1 <= num.length <= 105
num consists of only digits 0-9.
change.length == 10
0 <= change[d] <= 9
| class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
flag=0
ls=list(num)
for i in range(len(ls)):
k=int(ls[i])
if change[k]>k:
ls[i]=str(change[k])
flag=1
elif flag==1 and change[k]<k:
break
return "".join(ls) | class Solution {
public String maximumNumber(String num, int[] change) {
int i=0, n=num.length(), startIndex=-1, substringLength=0;
// traverse through each digit in the input string
while(i<n) {
int digit=num.charAt(i)-48;
// when we encounter a digit which has greater change
if(change[digit] > digit) {
startIndex = i;
// keep on replacing subsequent characters with with the change if they also have greater change
while(i<n) {
digit=num.charAt(i)-48;
if(change[digit] < digit) {
break;
}
i+=1;
}
substringLength = i-startIndex;
break;
}
i+=1;
}
// Note: Using String Builder to ensure linear time complexity as java strings are immutable
StringBuilder result=new StringBuilder("");
for(int j=0; j<n; j++) {
int digit=num.charAt(j)-48;
if(j>=startIndex && j<startIndex+substringLength) {
result.append(change[digit]);
} else {
result.append(digit);
}
}
return result.toString();
}
} | //change first longest encountered substring from left which can make string greater in value
class Solution {
public:
string maximumNumber(string num, vector<int>& change){
int n=num.size();
for(int i=0;i<n;i++){
int x=num[i]-'0';
if(x < change[x]){//checking whether mutating this char will increment the value or not
//the mutation continues till mutating the char will increase the value
while(i<n and num[i]-'0'<=change[num[i]-'0']){
num[i++]=change[num[i]-'0']+'0';
}
//break the loop when substring ends
break;
}
}
return num;
}
}; | var maximumNumber = function(num, change) {
const digits = num.split("");
let started = false;
for (let i = 0; i < digits.length; ++i) {
const origDig = digits[i];
const changeDig = change[origDig];
if (changeDig > origDig) {
started = true;
digits[i] = changeDig;
}
else if (changeDig < origDig && started) {
break;
}
}
return digits.join("");
}; | Largest Number After Mutating Substring |
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl", and
the third row consists of the characters "zxcvbnm".
Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Example 2:
Input: words = ["omk"]
Output: []
Example 3:
Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]
Constraints:
1 <= words.length <= 20
1 <= words[i].length <= 100
words[i] consists of English letters (both lowercase and uppercase).
| class Solution:
def findWords(self, words: List[str]) -> List[str]:
first_row = "qwertyuiopQWERTYUIOP"
second_row = "asdfghjklASDFGHIJKL"
third_row = "zxcvbnmZXCVBNM"
first_list = []
second_list = []
third_list = []
one_line_words = []
for word in words:
if set(word).issubset(first_row):
one_line_words.append(word)
if set(word).issubset(second_row):
one_line_words.append(word)
if set(word).issubset(third_row):
one_line_words.append(word)
return one_line_words | class Solution {
public String[] findWords(String[] words) {
String row1 = "qwertyuiop";
String row2 = "asdfghjkl";
String row3 = "zxcvbnm";
String res = "";
for(int i=0; i<words.length; i++) {
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for(int j=0; j<words[i].length(); j++) {
if(row1.contains("" + words[i].toLowerCase().charAt(j))) {
sum1++;
}
else if(row2.contains("" + words[i].toLowerCase().charAt(j))) {
sum2++;
}
else if(row3.contains("" + words[i].toLowerCase().charAt(j))) {
sum3++;
}
}
if(words[i].length()==sum1) {
res += i;
}
else if(words[i].length()==sum2) {
res += i;
}
else if(words[i].length()==sum3) {
res += i;
}
}
String[] resArr = new String[res.length()];
for(int i=0; i<resArr.length; i++) {
resArr[i] = words[Integer.parseInt("" + res.charAt(i))];
System.out.println(resArr[i]);
}
return resArr;
}
} | class DSU {
vector<int> parent, size;
vector<int> Q{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};
vector<int> A{'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};
vector<int> Z{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};
public:
DSU(){
for(int i= 0;i<123;i++) parent.push_back(i),size.push_back(1);
for(int i = 0; i<Q.size()-1;i++) findUnion(Q[i],Q[i+1]);
for(int i = 0; i<A.size()-1;i++) findUnion(A[i],A[i+1]);
for(int i = 0; i<Z.size()-1;i++) findUnion(Z[i],Z[i+1]);
}
int findParent(int x){
if(x==parent[x]) return x;
return parent[x] = findParent(parent[x]);
}
void findUnion(int a, int b){
a = findParent(a);
b = findParent(b);
if(a!=b) if(size[b]>size[a]) swap(a,b);parent[b] = a,size[a]+=size[b];
}
};
class Solution {
public:
vector<string> findWords(vector<string>& words) {
int n = words.size();
DSU dsu;
vector<string> ans;
for(int i = 0;i<n;i++){
int ss = words[i].size();
string s = words[i];
if(ss==1) {ans.push_back(s);continue;}
bool sameSet = true;
for(int j = 0;j<ss-1;j++)
if(dsu.findParent(s[j])!=dsu.findParent(s[j+1])){
sameSet = false;break;
}
if(sameSet)ans.push_back(s);
}return ans;
}
}; | var findWords = function(words) {
const firstRow = {"q":true,"w":true,"e":true,"r":true,"t":true,"y":true,"u":true,"i":true,"o":true,"p":true }
const secondRow = {"a":true,"s":true,"d":true,"f":true,"g":true,"h":true,"j":true,"k":true,"l":true }
const thirdRow = {"z":true,"x":true,"c":true,"v":true,"b":true,"n":true,"m":true }
let result = [];
const helperFunc= (word)=>{
let targetRow;
//Determine in which row the word should be;
if(firstRow[word[0].toLowerCase()]) targetRow = firstRow;
if(secondRow[word[0].toLowerCase()]) targetRow = secondRow;
if(thirdRow[word[0].toLowerCase()]) targetRow = thirdRow;
for(let i = 1;i<word.length;i++) {
if(!targetRow[word[i].toLowerCase()]) {
return false;
}
}
return true;
}
for(let i =0;i<words.length;i++) {
if(helperFunc(words[i])) {
result.push(words[i])
}
}
return result;
}; | Keyboard Row |
You are given a 0-indexed integer array nums and an integer k.
You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.
You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.
Return the maximum score you can get.
Example 1:
Input: nums = [1,-1,-2,4,-7,3], k = 2
Output: 7
Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
Example 2:
Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
Example 3:
Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
Output: 0
Constraints:
1 <= nums.length, k <= 105
-104 <= nums[i] <= 104
| class Solution:
def maxResult(self, nums, k):
deq, n = deque([0]), len(nums)
for i in range(1, n):
while deq and deq[0] < i - k: deq.popleft()
nums[i] += nums[deq[0]]
while deq and nums[i] >= nums[deq[-1]]: deq.pop()
deq.append(i)
return nums[-1] | class Solution {
public int maxResult(int[] nums, int k) {
int n = nums.length, a = 0, b = 0;
int[] deq = new int[n];
deq[0] = n - 1;
for (int i = n - 2; i >= 0; i--) {
if (deq[a] - i > k) a++;
nums[i] += nums[deq[a]];
while (b >= a && nums[deq[b]] <= nums[i]) b--;
deq[++b] = i;
}
return nums[0];
}
} | #define pii pair<int, int>
class Solution {
public:
int maxResult(vector<int>& nums, int k)
{
int n=nums.size();
int score[n];
priority_queue<pii> pq;
for(int i=n-1 ; i>=0 ; i--)
{
while(pq.size() && pq.top().second>i+k)
pq.pop();
score[i]=nums[i];
score[i]+=(pq.size() ? pq.top().first : 0);
pq.push({score[i], i});
}
return score[0];
}
}; | var maxResult = function(nums, k) {
let n = nums.length, deq = [n-1]
for (let i = n - 2; ~i; i--) {
if (deq[0] - i > k) deq.shift()
nums[i] += nums[deq[0]]
while (deq.length && nums[deq[deq.length-1]] <= nums[i]) deq.pop()
deq.push(i)
}
return nums[0]
}; | Jump Game VI |
Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.
Example 1:
Input: s1 = "abc", s2 = "xya"
Output: true
Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
Example 2:
Input: s1 = "abe", s2 = "acd"
Output: false
Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
Example 3:
Input: s1 = "leetcodee", s2 = "interview"
Output: true
Constraints:
s1.length == n
s2.length == n
1 <= n <= 10^5
All strings consist of lowercase English letters.
| class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1, s2 = sorted(s1), sorted(s2)
return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2)) | class Solution {
public boolean checkIfCanBreak(String s1, String s2) {
int n = s1.length();
char[] one = s1.toCharArray();
char[] two = s2.toCharArray();
Arrays.sort(one);
Arrays.sort(two);
if(check(one,two,n) || check(two,one,n)){
return true;
}
return false;
}
public boolean check(char[] one,char[] two,int n){
for(int i=0;i<n;i++){
if(one[i]-'a'>two[i]-'a'){
return false;
}
}
return true;
}
} | class Solution {
public:
bool checkIfCanBreak(string s1, string s2)
{
vector<int>freq1(26,0),freq2(26,0);
for(int i=0;i<s1.size();i++)
{
freq1[s1[i]-'a']++;
}
for(int i=0;i<s2.size();i++)
{
freq2[s2[i]-'a']++;
}
int count1 =0,count2=0;
bool check1 = true,check2=true;
for(int i=0;i<25;i++)
{
count1 += freq1[i]-freq2[i];
count2 += freq2[i] - freq1[i];
if(count1<0)
{
check1 = false;
}
if(count2<0)
{
check2 = false;
}
if(count1<0 && count2<0)
{
break;
}
}
return check1 || check2;
}
}; | const canAbreakB = (s1, s2) => {
const s1Heap = new MinPriorityQueue();
const s2Heap = new MinPriorityQueue();
for(let c of s1) {
s1Heap.enqueue(c.charCodeAt(0));
}
for(let c of s2) {
s2Heap.enqueue(c.charCodeAt(0));
}
while(s2Heap.size()) {
const s1Least = s1Heap.dequeue().element;
const s2Least = s2Heap.dequeue().element;
if(s1Least > s2Least) {
return false;
}
}
return true;
}
var checkIfCanBreak = function(s1, s2) {
return canAbreakB(s1, s2) || canAbreakB(s2, s1);
}; | Check If a String Can Break Another String |
There is a function signFunc(x) that returns:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
Example 1:
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Example 2:
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3:
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints:
1 <= nums.length <= 1000
-100 <= nums[i] <= 100
| class Solution:
def arraySign(self, nums: List[int]) -> int:
return 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1 | class Solution {
public int arraySign(int[] nums) {
int prod=1;
for(int i=0;i<nums.length;i++){
int val=signFunc(nums[i]);
prod*=val;
}
return prod;
}
private int signFunc(int x){
if(x<0) return -1;
else if(x>0) return 1;
return 0;
}
} | class Solution {
public:
int arraySign(vector<int>& nums) {
int res = 1;
for(auto x : nums)
{
if(x < 0) res *= -1;
else if(x == 0) return 0;
}
return res;
}
}; | var arraySign = function(nums) {
// use filter to find total negative numbers in the array
let negativeCount = nums.filter(n => n<0).length;
// check if the nums array has zero. If it does, then return 0
if(nums.includes(0)) return 0;
// If negativeCount variable is even answer is 1 else -1
return negativeCount % 2 === 0 ? 1 : -1
}; | Sign of the Product of an Array |
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.
Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].
Example 1:
Input: root = [1,2], voyage = [2,1]
Output: [-1]
Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.
Example 2:
Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]
Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
Example 3:
Input: root = [1,2,3], voyage = [1,2,3]
Output: []
Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
Constraints:
The number of nodes in the tree is n.
n == voyage.length
1 <= n <= 100
1 <= Node.val, voyage[i] <= n
All the values in the tree are unique.
All the values in voyage are unique.
| class Solution:
def flipMatchVoyage(self, root, voyage):
# ------------------------------
def dfs(root):
if not root:
# base case aka stop condition
# empty node or empty tree
return True
## general cases
if root.val != voyage[dfs.idx]:
# current node mismatch, no chance to make correction by flip
return False
# voyage index moves forward
dfs.idx += 1
if root.left and (root.left.val != voyage[dfs.idx]):
# left child mismatch, flip with right child if right child exists
root.right and result.append( root.val )
# check subtree in preorder DFS with child node flip
return dfs(root.right) and dfs(root.left)
else:
# left child match, check subtree in preorder DFS
return dfs(root.left) and dfs(root.right)
# --------------------------
# flip sequence
result = []
# voyage index during dfs
dfs.idx = 0
# start checking from root node
good = dfs(root)
return result if good else [-1] | class Solution {
private int i = 0;
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
List<Integer> list = new ArrayList<>();
flipMatchVoyage(root,voyage,list);
return list;
}
private void flipMatchVoyage(TreeNode root, int[] voyage,List<Integer> list) {
if(root == null || list.contains(-1)){
return;
}
if(root.val != voyage[i++]){
list.clear();
list.add(-1);
return;
}
if(root.left != null && root.right != null && root.left.val != voyage[i]){
list.add(root.val);
flipMatchVoyage(root.right,voyage,list);
flipMatchVoyage(root.left,voyage,list);
return;
}
flipMatchVoyage(root.left,voyage,list);
flipMatchVoyage(root.right,voyage,list);
}
} | class Solution {
public:
bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){
if(root == NULL || ind == voyage.size()){
ind--;
return true;
}
// Not possible to create
if(root->val != voyage[ind]){
ans.clear();
ans.push_back(-1);
return false;
}
// If voyage value not equal to its left child, then swap both childs and check
if(root->left && root->left->val != voyage[ind+1]){
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
// Pusing root into ans
ans.push_back(root->val);
}
return helper(++ind, root->left, voyage, ans) &&
helper(++ind, root->right, voyage, ans);
}
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
int ind = 0;
vector<int> ans;
helper(ind, root, voyage, ans);
return ans;
}
}; | var flipMatchVoyage = function(root, voyage) {
const output = []
let idx = 0;
function run(node) {
if(!node) return true;
if(voyage[idx] !== node.val) return false;
idx++;
if(node.left && node.left.val !== voyage[idx]) {
output.push(node.val);
return run(node.right) && run(node.left);
}
return run(node.left) && run(node.right);
}
return run(root) ? output : [-1];
}; | Flip Binary Tree To Match Preorder Traversal |
You are given the head of a linked list with n nodes.
For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.
Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.
Example 1:
Input: head = [2,1,5]
Output: [5,5,0]
Example 2:
Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]
Constraints:
The number of nodes in the list is n.
1 <= n <= 104
1 <= Node.val <= 109
| class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
stack = []
ans = []
node = head
i = 0
while node is not None:
while stack and stack[-1][0] < node.val:
ans[stack[-1][1]] = node.val
stack.pop()
stack.append((node.val, i))
ans.append(0)
i += 1
node = node.next
return ans | class Solution {
public int[] nextLargerNodes(ListNode head) {
ListNode length=head;
int l=0;
while(length!=null)
{
length=length.next;
l++;
}
int[] res=new int[l];
int i=0;
ListNode temp=head;
while(temp!=null)
{
ListNode temp1=temp.next;
int max=temp.val;
while(temp1!=null)
{
if(temp1.val>max)
{
max=temp1.val;
res[i]=max;
break;
}
temp1=temp1.next;
}
temp=temp.next;
i++;
}
return res;
}
} | class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> ans;
ListNode* curr = head;
if(head->next == NULL){
ans.push_back(0);
return ans;
}
while(curr != NULL){
ListNode* next = curr->next;
while(next != NULL){
if(next->val > curr->val){
ans.push_back(next->val);
break;
}
next = next->next;
}
if(next == NULL){
ans.push_back(0);
}
curr = curr->next;
}
return ans;
}
}; | var nextLargerNodes = function(head) {
let arr = [];
while(head){
arr.push(head.val);
head = head.next
}
return nextGreaterElement(arr)
};
function nextGreaterElement(arr){
let temp = [];
let n = arr.length;
let stack = [];
for(let i=n-1; i>=0; i--){
while(stack.length != 0 && arr[stack[stack.length-1]] <= arr[i]){
stack.pop()
}
if(stack.length == 0){
temp[i] = 0
}else{
temp[i] = arr[stack[stack.length-1]]
}
stack.push(i)
}
return temp
} | Next Greater Node In Linked List |
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Return the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
Follow up:
Could you solve this problem in less than O(n) complexity?
| class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
arr = set(arr)
i = 0
missed = 0
while missed != k:
i += 1
if i not in arr:
missed += 1
return i | class Solution {
public int findKthPositive(int[] arr, int k) {
if(arr[0] > k) {
return k;
}
for(int i=0; i<arr.length; i++) {
if(arr[i] <= k) {
k++;
}else {
break;
}
}
return k;
}
} | class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int n=arr.size();
if(arr[n-1]==n)
return n+k;
else
{
int start=0;
int end=n-1;
int ans;
while(start<=end)
{
int mid=start+(end-start)/2;
if((arr[mid]-(mid+1))<k)
start=mid+1;
else
end=mid-1;
}
return start+k;
}
}
}; | var findKthPositive = function(arr, k) {
let newArr = [];
for(let i=0,j=1; j<=arr.length+k; j++){
arr[i]!=j?newArr.push(j):i++;
}
return newArr[k-1];
}; | Kth Missing Positive Number |
Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
You may assume the input array always has a valid answer.
Example 1:
Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
Example 2:
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
Constraints:
1 <= nums.length <= 5 * 104
0 <= nums[i] <= 5000
It is guaranteed that there will be an answer for the given input nums.
Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? | class Heap:
def __init__(self):
self.q = []
def push(self,data):
i = len(self.q)
self.q.append(data)
while i>0:
if self.q[i] > self.q[(i-1)//2]:
self.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i]
i = (i-1)//2
else: return
def pop(self):
if len(self.q)==0:return
self.q[0] = self.q[-1]
self.q.pop()
def heapify(i):
ind = i
l = 2*i+1
r = 2*i+2
if r<len(self.q) and self.q[ind] < self.q[r]: ind = r
if l<len(self.q) and self.q[ind] < self.q[l]: ind = l
if ind != i:
self.q[i], self.q[ind] = self.q[ind], self.q[i]
heapify(ind)
heapify(0)
def top(self):
return self.q[0]
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
n = len(nums)
h = Heap()
for i in nums: h.push(i)
for i in range(1,n,2):
nums[i] = h.top()
h.pop()
for i in range(0,n,2):
nums[i] = h.top()
h.pop() | class Solution {
public void wiggleSort(int[] nums) {
int a[]=nums.clone();
Arrays.sort(a);
int left=(nums.length-1)/2;
int right=nums.length-1;
for(int i=0;i<nums.length;i++){
if(i%2==0){
nums[i]=a[left];
left--;
}
else{
nums[i]=a[right];
right--;
}
}
}
} | class Solution {
public:
void wiggleSort(vector<int>& nums) {
priority_queue<int> pq;
for(auto &i : nums)
pq.push(i);
for(int i = 1; i < nums.size(); i += 2)
nums[i] = pq.top(), pq.pop();
for(int i = 0; i < nums.size(); i += 2)
nums[i] = pq.top(), pq.pop();
}
}; | var wiggleSort = function(nums) {
nums.sort((a,b) => a - b);
let temp = [...nums];
let low = Math.floor((nums.length-1)/2), high = nums.length-1;
for(let i=0; i < nums.length; i++){
if(i % 2 === 0){
nums[i] = temp[low];
low--;
}else{
nums[i] = temp[high];
high--;
}
}
return nums;
}; | Wiggle Sort II |
Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
Each vowel 'a' may only be followed by an 'e'.
Each vowel 'e' may only be followed by an 'a' or an 'i'.
Each vowel 'i' may not be followed by another 'i'.
Each vowel 'o' may only be followed by an 'i' or a 'u'.
Each vowel 'u' may only be followed by an 'a'.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
Example 2:
Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
Example 3:
Input: n = 5
Output: 68
Constraints:
1 <= n <= 2 * 10^4
| class Solution:
def countVowelPermutation(self, n: int) -> int:
# dp[i][j] means the number of strings of length i that ends with the j-th vowel.
dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]
moduler = math.pow(10, 9) + 7
for i in range(1, n):
# For vowel a
dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler
# For vowel e
dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler
# For vowel i
dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler
# For vowel o
dp[i][3] = (dp[i - 1][2]) % moduler
# For vowel u
dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler
return int(sum(dp[-1]) % moduler) | class Solution {
private long[][] dp;
private int mod = (int)1e9 + 7;
public int countVowelPermutation(int n) {
dp = new long[6][n+1];
if(n == 1) return 5;
for(int i = 0; i < 5; i++)
dp[i][0] = 1;
helper(n,'z');
return (int)dp[5][n];
}
private long helper(int n, char vowel)
{
long ans = 0;
if(n == 0) return 1;
if(vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels
{
ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'i') + helper(n-1,'o') + helper(n-1,'u'))%mod;
dp[5][n] = ans;
}
// from here as per our assumptions of Vowels we will make calls & store results
else if(vowel == 'a') // for Nth number we would store Result for "a" in dp[0][n]
{
if(dp[0][n] != 0) return dp[0][n];
ans = (ans + helper(n-1,'e'))%mod;
dp[0][n] = ans;
}
else if(vowel == 'e') // for Nth number we would store Result for "e" in dp[1][n]
{
if(dp[1][n] != 0) return dp[1][n];
ans = (ans + helper(n-1,'a') + helper(n-1,'i'))%mod;
dp[1][n] = ans;
}
else if(vowel == 'i') // for Nth number we would store Result for "i" in dp[2][n]
{
if(dp[2][n] != 0) return dp[2][n];
ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'o') + helper(n-1,'u'))%mod;
dp[2][n] = ans;
}
else if(vowel == 'o') // for Nth number we would store Result for "o" in dp[3][n]
{
if(dp[3][n] != 0) return dp[3][n];
ans = (ans + helper(n-1,'i') + helper(n-1,'u'))%mod;
dp[3][n] = ans;
}
else // for Nth number we would store Result for "u" in dp[4][n]
{
if(dp[4][n] != 0) return dp[4][n];
ans = (ans + helper(n-1,'a'))%mod;
dp[4][n] = ans;
}
return ans;
}
} | class Solution {
public:
int countVowelPermutation(int n) {
long a = 1, e = 1, i = 1, o = 1, u = 1, mod = pow(10, 9)+7;
long a2, e2, i2, o2, u2;
for (int j = 2; j <= n; j++) {
a2 = (e + i + u) % mod;
e2 = (a + i) % mod;
i2 = (e + o) % mod;
o2 = i;
u2 = (o + i) % mod;
a = a2, e = e2, i = i2, o = o2, u = u2;
}
return (a + e + i + o + u) % mod;
}
}; | var countVowelPermutation = function(n) {
let a = 1, e = 1, i = 1, o = 1, u = 1, mod = 1000000007
while(n-- > 1){
let new_a = a % mod, new_e = e % mod, new_i = i % mod, new_o = o % mod, new_u = u % mod
a = new_e + new_i + new_u
e = new_a + new_i
i = new_e + new_o
o = new_i
u = new_i + new_o
}
return (a + e + i + o + u) % mod
}; | Count Vowels Permutation |
We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i] and target consist of lowercase English letters.
| from functools import lru_cache
from collections import Counter
class Solution(object):
def minStickers(self, stickers, target):
counter = [Counter(sticker) for sticker in stickers]
n = len(counter)
@lru_cache(None)
def dfs(target):
if not target: return 0
targ_counter = Counter(target)
res = float('inf')
#using sticker[i] if it contains the first letter of target
for i in range(n):
if counter[i][target[0]] == 0:
continue
s = ''
for j in 'abcdefghijklmnopqrstuvwxyz':
s += j*max(targ_counter[j] - counter[i][j], 0)
res = min(res, 1 + dfs(s)) if dfs(s) != -1 else res
return -1 if res == float('inf') else res
return dfs(target) | class Solution {
HashMap<String,HashMap<Character,Integer>>map;
public int minStickers(String[] stickers, String target) {
map = new HashMap<>();
for(String sticker:stickers){
HashMap<Character,Integer> temp = new HashMap<>();
for(char ch:sticker.toCharArray())
temp.put(ch,temp.getOrDefault(ch,0)+1);
map.put(sticker,temp);
}
int count = memoization(target,new HashMap<>());
return count<1||count>=Integer.MAX_VALUE?-1:count;
}
public int memoization(String target, HashMap<String, Integer>dpmap){
if(target.length()==0)return 0;
if(dpmap.containsKey(target)) return dpmap.get(target);
int count = Integer.MAX_VALUE;
for(String str: map.keySet()){
HashMap<Character,Integer> xd = new HashMap(map.get(str));
String temp = target;
char ch = temp.charAt(0);
if(xd.containsKey(ch)){
for(int i =0;i<temp.length();i++){
ch = temp.charAt(i);
if(xd.containsKey(ch) && xd.get(ch)>0){
xd.put(ch,xd.get(ch)-1);
temp = temp.substring(0,i)+temp.substring(i+1);
i--;
}
}
if(temp.length()!=target.length()){
count = Math.min(count,1+memoization(temp,dpmap));
dpmap.put(target,count);
}
}
}
return count;
}
} | class Solution {
public:
int dp[50][1<<15] ;
int solve(int ind, int mask, vector<string>& stickers, string& target)
{
if (mask == 0)
return 0 ;
if (ind == stickers.size())
return 1e8 ;
if (dp[ind][mask] != -1)
return dp[ind][mask] ;
vector<int> mp(26, 0);
bool flag = false ;
int ans = 1e8 ;
for(int i = 0; i < stickers[ind].size(); i++)
mp[stickers[ind][i]-'a'] ++ ;
for(int i= 0; i < target.size(); i++)
{
if (mp[target[i]-'a'] > 0 && (mask & (1<<i)))
{
flag = true ;
break ;
}
}
if (flag) // Check if we can use any of the characters in sticker[ind]
{
int tempMask = mask ;
for(int i = 0; i < target.size(); i++)
{
if (mp[target[i]-'a'] > 0 && (tempMask & (1<<i)))
{
tempMask = tempMask ^ (1<<i) ;
mp[target[i]-'a'] -- ;
}
}
ans = min(ans, 1+solve(ind, tempMask, stickers, target)) ; // Take those characters, and make call on same index
}
ans = min(ans, solve(ind+1, mask, stickers, target)) ; // Skip sticker[ind] and proceed
return dp[ind][mask] = ans;
}
int minStickers(vector<string>& stickers, string target) {
int n = target.size();
memset(dp, -1, sizeof(dp)) ;
int ans = solve(0, (1<<n)-1, stickers, target) ;
if (ans == 1e8)
return -1 ;
return ans ;
}
}; | /**
* @param {string[]} stickers
* @param {string} target
* @return {number}
*/
// Backtracking
var minStickers = function(stickers, target) {
//* Inits *//
let dp = new Map();
//* Helpers *//
const getStringDiff = (str1, str2) => {
for(let c of str2) {
if(str1.includes(c)) str1 = str1.replace(c, '');
}
return str1;
}
dp.set('', 0);
//* Main *//
function calcStickers(restStr) {
// if(restStr === "") return 0; <-- without memoization
if (dp.has(restStr)) return dp.get(restStr);
let res = Infinity;
for (let s of stickers.filter(s => s.includes(restStr[0]))) { // if current sticker does not contain the FIRST char, continue
let str = getStringDiff(restStr, s); //aabbc - bc = aab
res = Math.min(res, 1 + calcStickers(str)); // RECURSE.... calculate min stickers for the remaining letters.. try combination for all strings and get min
}
dp.set(restStr, res === Infinity || res === 0 ? -1 : res); //Memoize the result in dp;
return dp.get(restStr);
// return res; <-- without memoization
}
return calcStickers(target)
} | Stickers to Spell Word |
You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 104
num consists of only digits and does not contain leading zeros.
1 <= k <= 109
| from sortedcontainers import SortedList
class Solution:
def minInteger(self, num: str, k: int) -> str:
sz, window = len(num), SortedList()
remainedIndices, poppedIndices = SortedList(range(sz)), []
while k > 0:
while len(window) < k + 1 and len(window) < len(remainedIndices):
idx = remainedIndices[len(window)]
window.add((num[idx], idx))
if not window:
break
index = window.pop(0)[1]
k -= remainedIndices.bisect_left(index)
remainedIndices.remove(index)
poppedIndices.append(index)
for idx in remainedIndices[k + 1: len(window)]:
window.remove((num[idx], idx))
poppedSet = set(poppedIndices)
return "".join(num[idx] for idx in poppedIndices) + "".join(num[idx] for idx in range(sz) if idx not in poppedSet) | class Solution {
public String minInteger(String num, int k) {
//pqs stores the location of each digit.
List<Queue<Integer>> pqs = new ArrayList<>();
for (int i = 0; i <= 9; ++i) {
pqs.add(new LinkedList<>());
}
for (int i = 0; i < num.length(); ++i) {
pqs.get(num.charAt(i) - '0').add(i);
}
String ans = "";
SegmentTree seg = new SegmentTree(num.length());
for (int i = 0; i < num.length(); ++i) {
// At each location, try to place 0....9
for (int digit = 0; digit <= 9; ++digit) {
// is there any occurrence of digit left?
if (pqs.get(digit).size() != 0) {
// yes, there is a occurrence of digit at pos
Integer pos = pqs.get(digit).peek();
// Since few numbers already shifted to left, this `pos` might be outdated.
// we try to find how many number already got shifted that were to the left of pos.
int shift = seg.getCountLessThan(pos);
// (pos - shift) is number of steps to make digit move from pos to i.
if (pos - shift <= k) {
k -= pos - shift;
seg.add(pos); // Add pos to our segment tree.
pqs.get(digit).remove();
ans += digit;
break;
}
}
}
}
return ans;
}
class SegmentTree {
int[] nodes;
int n;
public SegmentTree(int max) {
nodes = new int[4 * (max)];
n = max;
}
public void add(int num) {
addUtil(num, 0, n, 0);
}
private void addUtil(int num, int l, int r, int node) {
if (num < l || num > r) {
return;
}
if (l == r) {
nodes[node]++;
return;
}
int mid = (l + r) / 2;
addUtil(num, l, mid, 2 * node + 1);
addUtil(num, mid + 1, r, 2 * node + 2);
nodes[node] = nodes[2 * node + 1] + nodes[2 * node + 2];
}
// Essentialy it tells count of numbers < num.
public int getCountLessThan(int num) {
return getUtil(0, num, 0, n, 0);
}
private int getUtil(int ql, int qr, int l, int r, int node) {
if (qr < l || ql > r) return 0;
if (ql <= l && qr >= r) {
return nodes[node];
}
int mid = (l + r) / 2;
return getUtil(ql, qr, l, mid, 2 * node + 1) + getUtil(ql, qr, mid + 1, r, 2 * node + 2);
}
}
} | /*
Time: O(nlogn)
Space: O(n)
Tag: Segment Tree, Greedy (put the possible feasible smallest index in place of cur index), Queue
Difficulty: H (Both Logic and Implementation)
*/
class SegmentTree {
vector<int> tree;
public:
SegmentTree(int size) {
tree.resize(4 * size + 1, 0);
}
void printTree() {
for (int num : tree) cout << num << "";
cout << endl;
}
void updateTree(int lo, int hi, int index, int upd) {
if (upd < lo || upd > hi) return;
if (lo == hi) {
tree[index]++;
return;
}
int mid = lo + (hi - lo) / 2;
updateTree(lo, mid, 2 * index, upd);
updateTree(mid + 1, hi, 2 * index + 1, upd);
tree[index] = tree[2 * index] + tree[2 * index + 1];
}
int queryTree(int lo, int hi, int index, int qs, int qe) {
if (qe < lo || qs > hi) return 0;
if (qe >= hi && qs <= lo) return tree[index];
int mid = lo + (hi - lo) / 2;
int left = queryTree(lo, mid, 2 * index, qs, qe);
int right = queryTree(mid + 1, hi, 2 * index + 1, qs, qe);
return left + right;
}
};
class Solution {
public:
string minInteger(string num, int k) {
queue<int> pos[10];
for (int i = 0; i < num.length(); i++) {
pos[num[i] - '0'].push(i);
}
string res = "";
SegmentTree *seg = new SegmentTree((int)num.length());
for (int i = 0; i < num.length(); i++) {
if (num[i] == '-') continue;
int digit = num[i] - '0';
bool swapped = false;
for (int j = 0; j < digit; j++) {
if (pos[j].size() > 0) {
int curNumIndex = pos[j].front();
int shifts = seg->queryTree(0, num.length() - 1, 1, i, pos[j].front());
if (curNumIndex - i - shifts <= k) {
seg->updateTree(0, num.length() - 1, 1, curNumIndex);
k -= curNumIndex - i - shifts;
pos[j].pop();
res += num[curNumIndex];
num[curNumIndex] = '-';
swapped = true;
i--;
break;
}
}
}
if (!swapped) {
res += num[i];
pos[digit].pop();
}
}
return res;
}
}; | /**
* @param {string} num
* @param {number} k
* @return {string}
Idea is based on bubble sorting with limited steps k
*/
var minInteger = function(num, k) {
if (num.length == 1)
return num;
let nums = num.split('');
let i = 0, j = 0;
while (k && i < num.length-1) {
// step 0: if leading zero, check the next digit
if (nums[i] == '0') {
i++;
j++;
continue;
}
// step 1: find the min digit
let p = j, steps = 0;
while (nums[p] !== '0' && j < nums.length && steps <= k) {
if (nums[j] < nums[p])
p = j;
j++;
steps++;
}
// step 2: nums[i] is the current minimum digit --> check next digit
if (p == i) {
i++;
j = i;
continue;
}
// step 3: move the min digit to i
for (; p > i; p--) {
[nums[p], nums[p-1]] = [nums[p-1], nums[p]];
k--;
}
i++;
j = i;
}
return nums.join('');
}; | Minimum Possible Integer After at Most K Adjacent Swaps On Digits |
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
Constraints:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret and guess consist of digits only.
| class Solution:
def getHint(self, secret: str, guess: str) -> str:
# Setup counts for bulls and cows
bulls = cows = 0
# Copy secret and guess into lists that are easier to work with
secretCopy = list(secret)
guessCopy = list(guess)
# In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls
for i in range(len(secret)):
# If they match, bulls += 1 and pop() the letters from the copy lists via their .index()
if secret[i] == guess[i]:
bulls += 1
secretCopy.pop(secretCopy.index(secret[i]))
guessCopy.pop(guessCopy.index(guess[i]))
# Count() the letters remaining in secret and guess lists
secretCounter = Counter(secretCopy)
guessCounter = Counter(guessCopy)
# Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed
# secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters
# Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters
dif = secretCounter - (secretCounter - guessCounter)
# The .total() of the dif Counter is the number of cows
cows = dif.total()
# return the formatted string with req. info
return f'{bulls}A{cows}B' | class Solution {
public String getHint(String secret, String guess) {
int arr[] = new int[10], bulls = 0, cows = 0;
for (int i = 0; i < secret.length(); i++) {
char sec = secret.charAt(i);
char gue = guess.charAt(i);
if (sec == gue) bulls++;
else {
if (arr[sec - '0'] < 0) cows++;
if (arr[gue - '0'] > 0) cows++;
arr[sec - '0']++;
arr[gue - '0']--;
}
}
return new StringBuilder(String.valueOf(bulls)).append("A").append(cows).append("B").toString();
}
} | class Solution
{
public:
string getHint(string secret, string guess)
{
int bulls = 0;
vector<int> v1(10, 0);
vector<int> v2(10, 0);
for (int i = 0; i < secret.size(); ++i)
{
if (secret[i] == guess[i])
{
++bulls;
}
else
{
++v1[secret[i] - '0'];
++v2[guess[i] - '0'];
}
}
int cows = 0;
for (int i = 0; i < 10; ++i)
{
cows += min(v1[i], v2[i]);
}
return to_string(bulls) + "A" + to_string(cows) + "B";
}
}; | var getHint = function(secret, guess) {
let ACount = 0, BCount = 0;
const secretMap = new Map(), guessMap = new Map();
for(let i = 0; i < secret.length; i++) {
if(secret[i] == guess[i]) {
ACount++;
}
else {
if(secretMap.has(secret[i])) {
secretMap.set(secret[i], secretMap.get(secret[i])+1);
}
else {
secretMap.set(secret[i], 1);
}
}
}
for(let i = 0; i < guess.length; i++) {
if(secret[i] !== guess[i]) {
if(secretMap.get(guess[i]) > 0) {
secretMap.set(guess[i], secretMap.get(guess[i])-1);
BCount++;
}
}
}
return ACount+'A'+BCount+'B';
}; | Bulls and Cows |
Given a string s and an array of strings words, determine whether s is a prefix string of words.
A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.
Return true if s is a prefix string of words, or false otherwise.
Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.
Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i] and s consist of only lowercase English letters.
| class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
a = ''
for i in words:
a += i
if a == s:
return True
if not s.startswith(a):
break
return False | class Solution {
public boolean isPrefixString(String s, String[] words) {
StringBuilder res = new StringBuilder ("");
for (String word : words) {
res.append (word);
if (s.equals (res.toString()))
return true;
if (s.indexOf (res.toString()) == -1)
return false;
}
return false;
}
} | class Solution {
public:
bool isPrefixString(string s, vector<string>& words) {
string n="";
for(string str:words){
for(char ch:str){
n+=ch;
}
if(n==s){
return true;
}
}
return false;
}
}; | var isPrefixString = function(s, words) {
let str = words[0];
if(s === words[0]){
return true;
}
for(let i=1; i < words.length; i++){
if(s === str){
return true;
}
if( s.startsWith(str)){
str += words[i];
continue;
}else{
return false;
}
}
if(s !== str){
return false;
}
return true;
}; | Check If String Is a Prefix of Array |
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".
Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.
Example 1:
Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Example 2:
Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Constraints:
2 <= s.length <= 200
s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
The number of words in s is between 1 and 9.
The words in s are separated by a single space.
s contains no leading or trailing spaces.
| class Solution:
def sortSentence(self, s: str) -> str:
x = s.split()
dic = {}
for i in x :
dic[i[-1]] = i[:-1]
return ' '.join([dic[j] for j in sorted(dic)]) | class Solution {
public String sortSentence(String s) {
String []res=new String[s.split(" ").length];
for(String st:s.split(" ")){
res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1);
}
return String.join(" ",res);
}
} | class Solution {
public:
string sortSentence(string s)
{
stringstream words(s);
string word;
pair<int, string> m;
vector<pair<int, string> > sent;
//SECTION 1
while(words>>word)
{
int len = word.size();
int i = int(word[len-1]) - 48;
sent.push_back(make_pair(i, word.substr(0, len-1)));
}
//SECTION 2
sort(sent.begin(), sent.end());
//SECTION 3
string ans = "";
int len = sent.size();
for(int i=0; i<len; i++)
{
ans += sent[i].second;
if(i!= len-1)
ans += " ";
}
return ans;
}
}; | var sortSentence = function(s) {
let sortingS = s.split(' ').sort((a,b) => a.substr(-1) - b.substr(-1));
slicingS = sortingS.map(word => word.slice(0, -1));
return slicingS.join(' ');
}; | Sorting the Sentence |
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
The number of nodes in the tree is in the range [0, 5 * 104].
0 <= Node.val <= 5 * 104
The tree is guaranteed to be complete.
| class Solution:
# @param {TreeNode} root
# @return {integer}
def countNodes(self, root):
if not root:
return 0
leftDepth = self.getDepth(root.left)
rightDepth = self.getDepth(root.right)
if leftDepth == rightDepth:
return pow(2, leftDepth) + self.countNodes(root.right)
else:
return pow(2, rightDepth) + self.countNodes(root.left)
def getDepth(self, root):
if not root:
return 0
return 1 + self.getDepth(root.left) | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
static int count = 0;
static void Postorder(TreeNode root){
if(root == null){
return;
}
Postorder(root.left);
Postorder(root.right);
count++;
}
public int countNodes(TreeNode root) {
count = 0;
Postorder(root);
return count;
}
} | class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr) return 0;
int left = countNodes(root->left);
int right = countNodes(root->right);
return 1+left+right;
}
}; | var countNodes = function(root) {
return root === null ? 0 : countNodes(root.left) + countNodes(root.right) + 1;
} | Count Complete Tree Nodes |
There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
Input: s = "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
| class Solution(object):
def strangePrinter(self, s):
"""
:type s: str
:rtype: int
"""
# remove duplicate letters from s.
tmp = []
for c in s:
if len(tmp) == 0 or tmp[-1] != c:
tmp.append(c)
s = "".join(tmp)
_m = {}
def _dp(i, j, background):
if j < i:
return 0
elif i == j:
return 1 if background != s[i] else 0
elif (i, j, background) in _m:
return _m[(i, j, background)]
ans = len(s)
# shrink s[i:j+1] to s[i_:j_+1] according to the background letter
i_ = i + 1 if s[i] == background else i
j_ = j - 1 if s[j] == background else j
if s[i_] == s[j_]:
# case "AxxxA" => best strategy is printing A first
ans = _dp(i_ + 1, j_ - 1, s[i_]) + 1
else:
# otherwise, print first letter, try every possible print length
for p in range(i_, j_ + 1):
# searching is needed only if s[p] == s[i_]
# e.g. s="ABCDEA"print 'A' on s[0:1] is equivalent to s[0:5]
if s[p] != s[i_]:
continue
l = _dp(i_, p, s[i_])
r = _dp(p + 1, j_, background)
ans = min(ans, l + r + 1)
_m[(i, j, background)] = ans
return ans
return _dp(0, len(s) - 1, '') | class Solution {
public int strangePrinter(String s) {
if (s.equals("")) return 0;
int len = s.length();
int[][] dp = new int[len][len];
for (int i = 0; i < len; i++)
dp[i][i] = 1;
for (int l = 2; l <= len; l++) {
for (int i = 0; i < len && l + i - 1 < len; i++) {
int j = l + i - 1;
dp[i][j] = dp[i][j - 1] + (s.charAt(i) == s.charAt(j) ? 0 : 1);
for (int k = i + 1; k < j; k++) {
if (s.charAt(k) == s.charAt(j)) {
dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k][j - 1]);
}
}
}
}
return dp[0][len - 1];
}
} | class Solution {
public:
int dp[101][101];
int solve(string s,int i,int j)
{
if(i>j)
return 0;
if(dp[i][j]!=-1)
return dp[i][j];
int ans=0;
while(i<j && s[i+1]==s[i])
i++;
while(i<j && s[j]==s[j-1])
{
j--;
}
ans=1+solve(s,i+1,j);
for(int k=i+1;k<=j;k++)
{
if(s[k]==s[i])
{
int cnt=solve(s,i+1,k-1)+solve(s,k,j);
ans=min(ans,cnt);
}
}
return dp[i][j]=ans;
}
int strangePrinter(string s)
{
memset(dp,-1,sizeof(dp));
return solve(s,0,s.size()-1);
}
};
// if you like the solution plz upvote. | var strangePrinter = function(s) {
if(!s) return 0;
const N = s.length;
const state = Array.from({length:N}, () => Array.from({length:N}));
for(let i = 0; i < N; i++) {
// Printing one character always takes one attempt
state[i][i] = 1;
}
const search = (i,j) => {
if(state[i][j]) return state[i][j];
state[i][j] = Infinity;
for(let k = i; k < j; k++) {
state[i][j] = Math.min(state[i][j], search(i,k) + search(k+1,j));
}
if(s[i] === s[j]) state[i][j]--;
return state[i][j];
}
return search(0, N-1);
} | Strange Printer |
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
Example 2:
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
Output: 0
Constraints:
n == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 104
1 <= difficulty[i], profit[i], worker[i] <= 105
| class Solution:
#Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)
#Space-Complexity: O(n)
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
#Approach: First of all, linearly traverse each and every corresponding index
#position of first two input arrays: difficulty and profit to group each
#item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array
#by increasing difficulty of the job! Then, for each worker, perform binary
#search and consistently update the max profit the current worker can work and
#earn! Add this value to answer variable, which is cumulative for all workers!
#this will be the result returned at the end!
arr = []
for i in range(len(difficulty)):
arr.append([difficulty[i], profit[i]])
#sort by difficulty!
arr.sort(key = lambda x: x[0])
#then, I need to update the maximum profit up to each and every item!
maximum = float(-inf)
for j in range(len(arr)):
maximum = max(maximum, arr[j][1])
arr[j][1] = maximum
ans = 0
#iterate through each and every worker!
for w in worker:
bestProfit = 0
#define search space to perform binary search!
L, R = 0, len(arr) - 1
#as long as search space has at least one element to consider or one job,
#continue iterations of binary search!
while L <= R:
mid = (L + R) // 2
mid_e = arr[mid]
#check if current job has difficulty that is manageable!
if(mid_e[0] <= w):
bestProfit = max(bestProfit, mid_e[1])
#we still need to search right and try higher difficulty
#jobs that might yield higher profit!
L = mid + 1
continue
else:
R = mid - 1
continue
#once we break from while loop and end binary search, we should have
#found bestProfit for current worker performing task that is manageable!
ans += bestProfit
return ans | class Solution {
public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->(b[1]-a[1]));
for(int i=0;i<profit.length;i++)
{
pq.add(new int[]{difficulty[i],profit[i]});
}
Arrays.sort(worker);
int p=0;
for(int i=worker.length-1;i>=0 && !pq.isEmpty();i--)
{
if(worker[i]>=pq.peek()[0])
p=p+pq.peek()[1];
else
{
while(!pq.isEmpty() && worker[i]<pq.peek()[0])
pq.poll();
if(!pq.isEmpty())
p=p+pq.peek()[1];
}
}
return p;
}
} | class Solution {
public:
static bool cmp(pair<int,int>a, pair<int,int>b){
if(a.first == b.first){
return a.second<b.second;
}
return a.first>b.first;
}
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
int ans = 0;
vector<pair<int,int>>vp;
for(int i = 0; i<profit.size(); i++){
vp.push_back({profit[i], difficulty[i]});
}
sort(vp.begin(), vp.end(), cmp);
sort(worker.begin(), worker.end(), greater<int>());
//i is for traversing the vp and j is for traversing the worker
int i = 0, j = 0;
while(i<vp.size() and j<worker.size()){
if(worker[j]>=vp[i].second){
ans+=vp[i].first;
j++;
}
else{
i++;
}
}
return ans;
}
}; | var maxProfitAssignment = function(difficulty, profit, worker) {
const data = [];
for (let i = 0; i < difficulty.length; i++) {
data.push({ difficulty: difficulty[i], profit: profit[i] });
}
data.sort((a, b) => a.difficulty - b.difficulty);
let maxProfit = 0;
for (let i = 0; i < data.length; i++) {
data[i].profit = maxProfit = Math.max(maxProfit, data[i].profit);
}
// worker.sort((a, b) => a - b);
let ans = 0;
let min = 0;
for (const skill of worker) {
let left = 0; // min;
let right = data.length - 1;
while (left < right) {
const mid = Math.floor((left + right + 1) / 2);
if (data[mid].difficulty > skill) {
right = mid - 1;
} else {
left = mid;
}
}
if (data[left].difficulty > skill) {
continue;
}
// min = left;
ans += data[left].profit;
}
return ans;
}; | Most Profit Assigning Work |
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
Constraints:
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.
| class Solution(object):
def mergeAlternately(self, word1, word2):
i=0
j=0
st=[]
while i<len(word1) and j<len(word2):
st.append(word1[i])
st.append(word2[j])
i+=1
j+=1
while j<len(word2):
st.append(word2[j])
j+=1
while i<len(word1):
st.append(word1[i])
i+=1
return "".join(st) | class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder sb = new StringBuilder();
int lenmax = Math.max(word1.length(),word2.length());
for(int i=0;i<=lenmax-1;i++)
{
if(i<word1.length()) sb.append(word1.charAt(i));
if(i<word2.length()) sb.append(word2.charAt(i));
}
return sb.toString();
}
} | class Solution {
public:
string mergeAlternately(string word1, string word2) {
string final="";
int p=word1.size();
int q=word2.size();
int n=max(p,q);
for(int i=0;i<n;i++){
if(p){
final=final+word1[i];
p--;
}
if(q){
final=final+word2[i];
q--;
}
}
return final;
}
}; | /**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function(word1, word2) {
let length = Math.max(word1.length, word2.length), s = '';
for(let i = 0; i < length; i++){
s+= word1[i] || '';
s+= word2[i] || '';
}
return s;
}; | Merge Strings Alternately |
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).
We view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.
Example 1:
Input: grid = [[1,2],[3,4]]
Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
Example 2:
Input: grid = [[2]]
Output: 5
Example 3:
Input: grid = [[1,0],[0,2]]
Output: 8
Constraints:
n == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
| class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
total = 0
# top
total += sum([1 for i in grid for j in i if j > 0])
# front
total += sum([max(col) for col in zip(*grid)])
# side
total += sum([max(row) for row in grid])
return total | class Solution {
public int projectionArea(int[][] grid) {
int totalArea = 0;
for(int[] row : grid){
int max = row[0];
for(int c : row){
if(max < c){
max = c;
}if(c != 0){
totalArea += 1;
}
}
totalArea += max;
}
for(int c = 0; c < grid[0].length; c++){
int max = grid[0][c];
for(int row = 0; row < grid.length; row++){
if(max < grid[row][c]){
max = grid[row][c];
}
}
totalArea += max;
}
return totalArea;
}
} | class Solution {
public:
int projectionArea(vector<vector<int>>& grid) {
int res=0;
// X-Y ( top )
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]) // if some cubes are present it is seen as of area 1 from top
res++;
}
}
// Z-X ( front )
for(int i=0;i<grid.size();i++)
{
int m=grid[i][0];
for(int j=1;j<grid[0].size();j++)
{
m=max(m,grid[i][j]);// from front, the tower with heightest height can only be seen in column
}
res+=m;
}
// Z-Y ( side )
for(int j=0;j<grid[0].size();j++)
{
int m=grid[0][j];
for(int i=1;i<grid.size();i++)
{
m=max(m,grid[i][j]);// // from side, the tower with heightest height can only be seen in row
}
res+=m;
}
return res;
}
}; | var projectionArea = function(grid) {
let maxs = new Array(grid.length).fill(0);
grid.forEach(row => row.forEach((val, idx) => {
if (maxs[idx] < val) maxs[idx] = val;
}))
const z = grid.reduce((prev, curr) => prev + curr.filter(val => val !== 0).length, 0);
const y = grid.reduce((prev, curr) => prev + Math.max(...curr), 0);
const x = maxs.reduce((prev, curr) => prev + curr, 0)
return x + y + z;
}; | Projection Area of 3D Shapes |
You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example 1:
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input: grid = [[1]]
Output: 4
Example 3:
Input: grid = [[1,0]]
Output: 4
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j] is 0 or 1.
There is exactly one island in grid.
| class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
perimeter = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
perimeter += 4
if i != 0 and grid[i-1][j] == 1:
perimeter -= 2
if j != 0 and grid[i][j-1] == 1:
perimeter -= 2
return perimeter | class Solution {
public int islandPerimeter(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int row=grid.length,col=grid[0].length;
int perimeter=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]==1){
perimeter+=4;
if(i>0 && grid[i-1][j]==1){
perimeter-=2;
}
if(j>0 && grid[i][j-1]==1){
perimeter-=2;
}
}
}
}
return perimeter;
}
} | ////** hindi me samjho ab//
// agar mje left or right or bottom or top me 1 mila to me aaga badunga agar nahi
//mila mtlb ya to wo boundary hai uske baad 0 ara hai agar esa hai to cnt+=1
//kardo kuki wo hi to meri boundary banegi . note : agar boundary hai mtlb
//i <0 or j<0 or i>=n or j>=m to cnt+=1 kardo or agar box ke side walo me 0 hai to wahan bhi cnt+=1 .
// hope it make sense
// please upvote if you like my post
class Solution {
public:
int cnt =0 ;
bool vis[101][101] ;
bool valid( int i , int j, int n , int m){
if(i>=n or j>=m or i<0 or j<0 )
return false;
return true ;
}
int islandPerimeter(vector<vector<int>>& grid) {
memset(vis,false , sizeof(vis)) ;
for(int i = 0 ; i <grid.size() ; i ++){
for(int j=0 ; j<grid[0].size() ; j++) {
if(grid[i][j]==1){
solve(grid, i,j) ;
return cnt ;
}
}
}
return 69;
}
void solve(vector<vector<int>>&grid, int i , int j ){
int n = grid.size() ;
int m = grid[0].size() ;
vis[i][j]=true ;
if(!valid(i-1,j,n,m) or (valid(i-1,j,n,m) and grid[i-1][j]==0)){
cnt++ ;
}
else if(valid(i-1,j,n,m)and !vis[i-1][j])
solve(grid, i-1,j) ;
if(!valid(i+1,j,n,m) or (valid(i+1,j,n,m) and grid[i+1][j]==0)){
cnt++ ;
}
else if(valid(i+1,j,n,m)and !vis[i+1][j])
solve(grid,i+1,j) ;
if(!valid(i,j-1,n,m) or (valid(i,j-1,n,m) and grid[i][j-1]==0)){
cnt++ ;
}
else if(valid(i,j-1,n,m)and !vis[i][j-1])
solve(grid,i,j-1) ;
if(!valid(i,j+1,n,m) or (valid(i,j+1,n,m) and grid[i][j+1]==0)){
cnt++ ;
}
else if(valid(i,j+1,n,m)and !vis[i][j+1])
solve(grid,i,j+1) ;
}
}; | var islandPerimeter = function(grid) {
let perimeter = 0
let row = grid.length
let col = grid[0].length
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === 1) {
if (i === 0 || i > 0 && grid[i-1][j] === 0) perimeter++
if (i === row-1 || i < row-1 && grid[i+1][j] === 0) perimeter++
if (j === 0 || j > 0 && grid[i][j-1] === 0) perimeter++
if (j === col - 1 || j < col && grid[i][j+1] === 0) perimeter++
}
}
}
return perimeter
}; | Island Perimeter |
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).
The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.
If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].
If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].
Return the minimum total cost for this robot to return home.
Example 1:
Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
Output: 18
Explanation: One optimal path is that:
Starting from (1, 0)
-> It goes down to (2, 0). This move costs rowCosts[2] = 3.
-> It goes right to (2, 1). This move costs colCosts[1] = 2.
-> It goes right to (2, 2). This move costs colCosts[2] = 6.
-> It goes right to (2, 3). This move costs colCosts[3] = 7.
The total cost is 3 + 2 + 6 + 7 = 18
Example 2:
Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
Output: 0
Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.
Constraints:
m == rowCosts.length
n == colCosts.length
1 <= m, n <= 105
0 <= rowCosts[r], colCosts[c] <= 104
startPos.length == 2
homePos.length == 2
0 <= startrow, homerow < m
0 <= startcol, homecol < n
| class Solution:
def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:
def getRange(left, right, array):
if left > right:
right, left = left, right
return sum((array[i] for i in range(left,right+1)))
totalRowCost = getRange(startPos[0], homePos[0], rowCosts)
totalColCost = getRange(startPos[1], homePos[1], colCosts)
#Don't pay for the position you start out on
return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]] | class Solution {
public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
int total = 0;
// if home is to the down of start move, down till there
if(homePos[0]>startPos[0]){
int i = startPos[0]+1;
while(i<=homePos[0]){
total += rowCosts[i]; // adding cost while moving corresponding to the cell
i++;
}
}
// else if home is up from the start, move up till there
else if(homePos[0]<startPos[0]){
int i = startPos[0]-1;
while(i>=homePos[0]){
total += rowCosts[i]; // adding cost while moving corresponding to the cell
i--;
}
}
// if home is right to the start, move right till there
if(homePos[1]>startPos[1]){
int i = startPos[1]+1;
while(i<=homePos[1]){
total += colCosts[i]; // adding cost while moving corresponding to the cell
i++;
}
}
// else if home is left to the start, move left till there
else if(homePos[1]<startPos[1]){
int i = startPos[1]-1;
while(i>=homePos[1]){
total += colCosts[i]; // adding cost while moving corresponding to the cell
i--;
}
}
return total;
}
} | // This is Straightforward Question becuase you need to travel at least one time the incoming rows and column in path.
// So why you need to complicate the path just traverse staright and to homePos Row and homePos column and you will get the ans...
// This Question would have become really tough when negative values also possible in the row and column vectors because that negative values could have decresed the results...but here its simple and concise.
class Solution {
public:
int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
int ans = 0;
if(startPos[0] < homePos[0])
{
for(int i = startPos[0]+1 ; i <=homePos[0] ; i++)
{
ans+=rowCosts[i];
}
}
if(startPos[0] > homePos[0])
{
for(int i = startPos[0]-1 ; i >=homePos[0] ; i--)
{
ans+=rowCosts[i];
}
}
if(startPos[1] < homePos[1])
{
for(int i = startPos[1]+1 ; i <=homePos[1] ; i++)
{
ans+=colCosts[i];
}
}
if(startPos[1] > homePos[1])
{
for(int i = startPos[1]-1 ; i >=homePos[1] ; i--)
{
ans+=colCosts[i];
}
}
return ans;
}
}; | var minCost = function(startPos, homePos, rowCosts, colCosts) {
let totCosts = 0;
let rowDir = startPos[0] <= homePos[0] ? 1 : -1;
let colDir = startPos[1] <= homePos[1] ? 1 : -1;
let row = startPos[0];
while (row != homePos[0]) {
row += rowDir;
totCosts += rowCosts[row];
}
let col = startPos[1];
while (col != homePos[1]) {
col += colDir;
totCosts += colCosts[col];
}
return totCosts;
}; | Minimum Cost Homecoming of a Robot in a Grid |
No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.
Given an integer n, return a list of two integers [A, B] where:
A and B are No-Zero integers.
A + B = n
The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them.
Example 1:
Input: n = 2
Output: [1,1]
Explanation: A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.
Example 2:
Input: n = 11
Output: [2,9]
Constraints:
2 <= n <= 104
| class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
for i in range(1,n//2+1):
first = str(i)
second = str(n-i)
if "0" not in first and "0" not in second:
return [i, n-i] | class Solution {
public int[] getNoZeroIntegers(int n) {
int B;
for (int A = 1; A < n; ++A) {
B = n - A;
if (!(A + "").contains("0") && !(B + "").contains("0"))
return new int[] {A, B};
}
return new int[]{};
}
} | class Solution {
public:
int has0(int x)
{
while (x){
if (x % 10 == 0)
return 1;
x /= 10;
}
return 0;
}
vector<int> getNoZeroIntegers(int n) {
for(int i=1;i<=n;i++){
if(has0(i)==false && has0(n-i)==false){
return {i,n-i};
}
}
return {1,1};
}
}; | var getNoZeroIntegers = function(n) {
for(let i=1;i<=n;i++){
if(!haveZero(i) && !haveZero(n-i)){
return [i,n-i]
}
}
};
const haveZero = (n) =>{
let copy = n;
while(copy>0){
if(copy%10===0){
return true
}
copy=Math.floor(copy/10)
}
return false
} | Convert Integer to the Sum of Two No-Zero Integers |
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
1 <= heights.length <= 105
0 <= heights[i] <= 104
| class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
maxArea = 0
stack = [] # (index, height)
for i, h in enumerate(heights):
startIndex = i
while stack and stack[-1][1] > h:
index, height = stack.pop()
maxArea = max(maxArea, height * (i - index))
startIndex = index
stack.append((startIndex, h))
for index, height in stack:
maxArea = max(maxArea, height * (len(heights) - index))
return maxArea | class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
int n = heights.length;
int[] left = new int[n];
int[] right = new int[n];
int[] width = new int[n];
for(int i=0; i<n; i++){
while(!stack1.isEmpty() && heights[stack1.peek()] >= heights[i])
stack1.pop();
if(!stack1.isEmpty())
left[i] = stack1.peek();
else
left[i] = -1;
stack1.push(i);
}
for(int i=n-1; i>=0; i--){
while(!stack2.isEmpty() && heights[stack2.peek()] >= heights[i])
stack2.pop();
if(!stack2.isEmpty())
right[i] = stack2.peek();
else
right[i] = n;
stack2.push(i);
}
for(int i=0; i<n; i++){
width[i] = right[i] - left[i] - 1;
}
int mxArea = 0;
for(int i=0; i<n; i++){
mxArea = Math.max(mxArea, width[i] * heights[i]);
}
return mxArea;
}
} | class Solution {
private:
vector<int> nextSmallerElement(vector<int>& arr, int n){
stack<int> s;
s.push(-1);
vector<int> ans(n);
for(int i = n-1; i>=0 ; i--){
int curr = arr[i];
while(s.top()!=-1 && arr[s.top()]>=curr){
s.pop();
}
ans[i] = s.top();
s.push(i);
}
return ans;
}
vector<int> prevSmallerElement(vector<int>& arr, int n){
stack<int> s;
s.push(-1);
vector<int> ans(n);
for(int i = 0; i<n ; i++){
int curr = arr[i];
while(s.top()!=-1 && arr[s.top()]>=curr){
s.pop();
}
ans[i] = s.top();
s.push(i);
}
return ans;
}
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
int area = 1, ans = INT_MIN;
vector<int> next(n);
next = nextSmallerElement(heights, n);
vector<int> prev(n);
prev = prevSmallerElement(heights, n);
for(int i = 0; i<n ; i++){
int l = heights[i];
if(next[i] == -1){
next[i] = n;
}
int b = next[i] - prev[i] - 1;
area = l*b;
ans = max(ans,area);
}
return ans;
}
}; | var largestRectangleArea = function (heights) {
let maxArea = 0;
let stack = []; // [[index, height]]
for (let i = 0; i < heights.length; i++) {
let start = i;
while (stack.length != 0 && stack[stack.length - 1][1] > heights[i]) {
let [index, height] = stack.pop();
maxArea = Math.max(maxArea, height * (i - index));
start = index;
}
stack.push([start, heights[i]]);
}
for (let i = 0; i < stack.length; i++) {
maxArea = Math.max(
maxArea,
stack[i][1] * (heights.length - stack[i][0])
);
}
return maxArea;
}; | Largest Rectangle in Histogram |
You are given a string s consisting only of characters 'a' and 'b'ββββ.
You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.
Return the minimum number of deletions needed to make s balanced.
Example 1:
Input: s = "aababbab"
Output: 2
Explanation: You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
Example 2:
Input: s = "bbaaaaabb"
Output: 2
Explanation: The only solution is to delete the first two characters.
Constraints:
1 <= s.length <= 105
s[i] is 'a' or 'b'ββ.
| class Solution:
def minimumDeletions(self, s: str) -> int:
preSum = [0] * (len(s) + 1)
sufSum = [0] * (len(s) + 1)
for i in range(len(s)):
if s[i] == "a":
preSum[i] += 1 + preSum[i-1]
else:
preSum[i] = preSum[i-1]
if s[len(s)-i-1] == "b":
sufSum[len(s)-i-1] += 1 + sufSum[len(s)-i]
else:
sufSum[len(s)-i-1] += sufSum[len(s)-i]
maxStringLength = 0
for i in range(len(s)):
if preSum[i] + sufSum[i] > maxStringLength:
maxStringLength = preSum[i] + sufSum[i]
return len(s) - maxStringLength | class Solution {
public int minimumDeletions(String s) {
//ideal case : bbbbbbbbb
int[] dp = new int[s.length()+1];
int idx =1;
int bCount=0;
for(int i =0 ;i<s.length();i++)
{
if(s.charAt(i)=='a')
{
dp[idx] = Math.min(dp[idx-1]+1,bCount);
}
else
{
dp[idx]=dp[idx-1];
bCount++;
}
idx++;
}
return dp[s.length()];
}
} | class Solution {
public:
int minimumDeletions(string s){
vector<int> deletions(s.size()+1, 0);
int b_count = 0;
for(int i = 0; i<s.size(); i++){
if(s[i]=='a'){
// Either Delete this 'a' or Delete all previous 'b's.
deletions[i+1] = min(deletions[i]+1, b_count);
} else{
deletions[i+1] = deletions[i];
b_count++;
}
}
return deletions[s.size()];
// The code is contributed by Mufaddal Saifuddin
}
}; | var minimumDeletions = function(s) {
const dpA = [];
let counter = 0;
for (let i = 0; i < s.length; i++) {
dpA[i] = counter;
if (s[i] === 'b') {
counter++;
}
}
counter = 0;
const dpB = [];
for (let i = s.length - 1; i >= 0; i--) {
dpB[i] = counter;
if (s[i] === 'a') {
counter++;
}
}
let minDelete = s.length;
for (let i = 0; i < s.length; i++) {
minDelete = Math.min(minDelete, dpA[i] + dpB[i]);
}
return minDelete;
}; | Minimum Deletions to Make String Balanced |
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
Example 2:
Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
Output: 4
Example 3:
Input: m = 3, n = 3, ops = []
Output: 9
Constraints:
1 <= m, n <= 4 * 104
0 <= ops.length <= 104
ops[i].length == 2
1 <= ai <= m
1 <= bi <= n
| class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
if not ops:
return m*n
else:
x,y = zip(*ops)
return min(x) * min(y) | class Solution {
public int maxCount(int m, int n, int[][] ops) {
int minRow=m,minCol=n;
for(int[] op:ops){
minRow=Math.min(minRow,op[0]);
minCol=Math.min(minCol,op[1]);
}
return minRow*minCol;
}
} | class Solution {
public:
int maxCount(int m, int n, vector<vector<int>>& ops) {
int mn_i = m, mn_j = n;
for(auto &i : ops)
mn_i = min(mn_i, i[0]), mn_j = min(mn_j, i[1]);
return mn_i * mn_j;
}
}; | var maxCount = function(m, n, ops) {
if( ops.length === 0 )
return m*n
let min_a = m , min_b = n
for( let [x,y] of ops ){
if( x < min_a )
min_a = x
if( y < min_b )
min_b = y
}
return min_a * min_b
}; | Range Addition II |
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.
Return the maximum number of events you can attend.
Example 1:
Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
Example 2:
Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4
Constraints:
1 <= events.length <= 105
events[i].length == 2
1 <= startDayi <= endDayi <= 105
| class Solution(object):
def maxEvents(self, events):
"""
:type events: List[List[int]]
:rtype: int
"""
events = sorted(events, key=lambda x: x[0])
current_day = 0
min_heap = []
event_id = 0
total_number_of_days = max(end for start, end in events)
total_events_attended = 0
#total_number_of_days+1 because I want to include the last day
for day in range(1, total_number_of_days+1):
#Add all the events that can be started on that day
while event_id < len(events) and events[event_id][0] == day:
heapq.heappush(min_heap, events[event_id][1])
event_id+=1
#while there is something in heap and the event should have been completed before the current day
#remove those evenets and consider them not attended
while min_heap and min_heap[0] < day :
heapq.heappop(min_heap)
#if theere is an event present in heap
#lets mark 1 of those events as complted today and add it to
#total_events_attended
if min_heap:
heapq.heappop(min_heap)
total_events_attended+=1
return total_events_attended | class Solution {
public int maxEvents(int[][] events) {
Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]);
// here sorting the array on ths basis of last day because we want to finish the events which happens first,fist.
TreeSet<Integer> set =new TreeSet<>();
for(int i =1;i<=100000;i++){
set.add(i);
}
//initliasing a tree set to check available days ;
// a day can go maximum to 100000;
int ans =0;
for(int i =0;i<events.length;i++){
Integer temp = set.ceiling(events[i][0]);
if(temp==null || temp >events[i][1])
continue;
else{
set.remove(temp);
ans +=1;
}
}
return ans;
}
} | class Solution {
public:
int maxEvents(vector<vector<int>>& events) {
int res=0;
int m=0;
for(auto x:events)
m=max(m,x[1]);
sort(events.begin(),events.end());
int j=0;
priority_queue<int,vector<int>,greater<int>> pq;
for(int i=1;i<=m;i++)
{
while(!pq.empty() && pq.top()<i)// end day is less than the current day
pq.pop();
while(j<events.size() && events[j][0]==i)// put all events start at day i
pq.push(events[j++][1]);
if(!pq.empty())// we can attend an event today
{
pq.pop();// remove the event
res++;// count that event
}
}
return res;
}
}; | /**
* O(nlogn)
*/
var maxEvents = function(events) {
// sort events by their start time
events.sort((a,b) => a[0]-b[0]);
// create priority queue to sort events by end time, the events that have saem start time
let minHeap = new PriorityQueue((a, b) => a - b);
let i = 0, len = events.length, res = 0, d = 0;
while(i < len || !minHeap.isEmpty()){
if (minHeap.isEmpty())
d = events[i][0]; // start with event from events list
while (i < len && events[i][0] <= d) // Add all events that have start time <= day `d` into PQ
minHeap.add(events[i++][1]); // add ending time to the minHeap, so when we pull we get event that is ending first
minHeap.poll(); // make sure we have some event attent
++res;
++d;
// we finished task of day 'd' Remove events that are already closed ie endTime < d as we cant attend it
while (!minHeap.isEmpty() && minHeap.peek() < d)
minHeap.poll();
}
return res;
};
/*******************standard priority queue implementation used in all leetcode javascript solutions****************/
class PriorityQueue {
/**
* 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;
}
peek() {
return this.store[0];
}
size() {
return this.store.length;
}
isEmpty() {
return this.store.length === 0;
}
poll() {
if (this.size() < 2) {
return this.store.pop();
}
const result = this.store[0];
this.store[0] = this.store.pop();
this.heapifyDown(0);
return result;
}
add(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;
}
} | Maximum Number of Events That Can Be Attended |
Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.
Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Constraints:
The given dates are valid dates between the years 1971 and 2100.
| class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5
DAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR), (day, month, year))
return DAYS[(difference + DAY) % 7]
def daysBetweenDates(self, date1: tuple, date2: tuple) -> int:
LOWEST_YEAR = 1971
def daysSinceLowest(date: tuple) -> int:
day, month, year = date
isLeapYear = lambda x: 1 if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else 0
days: int = 0
# days between the LOWEST_YEAR and year
days += 365 * (year - LOWEST_YEAR) + sum(map(isLeapYear, range(LOWEST_YEAR, year)))
# days between year and exact date
daysInMonth = (31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days += sum(daysInMonth[:month - 1]) + day
return days
return abs(daysSinceLowest(date1) - daysSinceLowest(date2)) | class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
year--;
int total = (year/4)*366+(year-year/4)*365;
int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
year++;
if(year%4==0 && year!=2100){
months[1]++;
}
for(int i=0;i<month-1;i++){
total+= months[i];
}
total +=day;
// for(int i:months){
// System.out.print(i+" ");
// }
// System.out.println();
return week[(total-1)%7];
}
} | class Solution {
public:
int daysOfMonth[2][12] = {
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
string weekName[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
bool isleapyear(int year)
{
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
int daystill1971(int year, int month, int day)
{
int count = 0;
int year1 = 1970, month1 = 1, day1 = 1;
while (year1 != year)
{
bool b = isleapyear(year1);
if (b) count += 366;
else count += 365;
year1++;
}
int b = isleapyear(year1) ? 0 : 1;
for (int i = 0; i < month - 1; i++) count += daysOfMonth[b][i];
count += day - 1;
return count;
}
string dayOfTheWeek(int day, int month, int year) {
int days1 = daystill1971(2019, 9, 8);//today(2019,9,8) is Sunday
int days2 = daystill1971(year, month, day);
int days = (((days2 - days1) % 7) + 7) % 7;//Number of days off
return weekName[days];
}
}; | /**
* @param {number} day
* @param {number} month
* @param {number} year
* @return {string}
*/
var dayOfTheWeek = function(day, month, year) {
var map = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
};
var date = new Date(`${month}/${day}/${year}`);
return map[date.getDay()];
}; | Day of the Week |
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this 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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
if head == None:
return None
slow = head
fast = head
for i in range(n):
fast = fast.next
if fast == None:
return head.next
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return head | class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = head;
int len=0;
if(head==null || head.next==null)
return null;
while(temp!=null){
temp=temp.next;
len++;
}
if(len==n)
return head.next;
int frontlen = len-n-1;
ListNode first=head.next;
ListNode second = head;
int count=0;
while(first!=null){
if(count==frontlen){
second.next=first.next;
break;
}else{
first=first.next;
second=second.next;
count++;
}
}
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* removeNthFromEnd(ListNode* head, int n) {
ListNode* n1 = new ListNode();
ListNode *temp=head;
ListNode *p=head;
ListNode *q=n1;
n1->next=head;
int count;
while(temp)
{
if(n>0){
n--;
}
else if(n==0){
cout<val;
p=p->next;
q=q->next;
}
temp=temp->next;
}
q->next=p->next;
delete p;
return n1->next;
}
}; | var removeNthFromEnd = function(head, n) {
let start = new ListNode(0, head);
let slow = start, fast = start;
for (let i =1; i <= n; i++) {
fast = fast.next;
}
while(fast && fast.next) {
slow = slow.next;
fast = fast.next;
}
let nthNode = slow.next
slow.next = nthNode.next;
return start.next;
}; | Remove Nth Node From End of List |
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2:
Input: nums = [1,1,2]
Output: [1]
Example 3:
Input: nums = [1]
Output: []
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Each element in nums appears once or twice.
| class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
res = []
hm = {}
# adding entries in hashmap to check frequency
for i, v in enumerate(nums):
if v not in hm:
hm[v] = 1
else:
hm[v] += 1
# checking frequency of item and adding output to an array
for key, value in hm.items():
if value > 1:
res.append(key)
return res | class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for(int i=0;i<nums.length;i++){
int ind = Math.abs(nums[i])-1;
if(nums[ind]<0){
ans.add(Math.abs(nums[i]));
}
else{
nums[ind] = -1*nums[ind];
}
}
return ans;
}
} | class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n=nums.size();
vector<int> a;
vector<int> arr(n+1,0);
for(int i=0;i<nums.size();i++)
arr[nums[i]]++;
for(int j=0;j<=n;j++)
if(arr[j]==2) a.push_back(j);
return a;
}
}; | // Approach : Mark Visited Elements in the Input Array itself
var findDuplicates = function(nums) {
let result = [];
for(let i = 0; i < nums.length; i++) {
let id = Math.abs(nums[i]) - 1;
if(nums[id] < 0) result.push(id + 1);
else nums[id] = - Math.abs(nums[id]);
}
return result;
}; | Find All Duplicates in an Array |
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Input: piles = [3,6,7,11], h = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Constraints:
1 <= piles.length <= 104
piles.length <= h <= 109
1 <= piles[i] <= 109
| class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def check(x):
return sum(ceil(ele/x) for ele in piles) <= h
l = 1
r = max(piles)
while l < r:
mid = (l+r) >> 1
if not check(mid):
l=mid+1
else:
r=mid
return l | class Solution {
public int minEatingSpeed(int[] piles, int h) {
int max=0;
int ans=0;
for(int i=0;i<piles.length;i++)
{
max=Math.max(piles[i],max);
}
if(piles.length==h)
return max;
int left=1;
int right=max;
while(left<=right)
{
int mid=left+(right-left)/2;
double num=0;
int time=0;
for(int i=0;i<piles.length;i++)
{
num=(double)piles[i]/(mid);
if(num>piles[i]/mid)
time+=num+1;
else
time+=num;
}
if(time<=h)
{
ans=mid;
right=mid-1;
}
else
left=mid+1;
}
return ans;
}
} | class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int mx=1000000001;
int st=1;
while(mx>st)
{
int k = ((mx+st)/2);
int sum=0;
for(int i =0 ;i < piles.size() ; i++)
{
sum+=ceil(1.0 *piles[i]/k);
}
if(sum>h)
{
st=k+1;
}
else
{
mx=k;
}
}
return st;
}
}; | var minEatingSpeed = function(piles, h) {
/*The range of bananas that Koko can eat is k = 1 to Max(piles)*/
let startk = 1;
let endk = Math.max(...piles);
while(startk <= endk){
let midk = Math.floor(startk + (endk - startk)/2);
/*midk are the count of bananas that koko decide to eat.
So how many hours she will take to finish the piles?*/
let hrs = 0;
for(let pile of piles){
/*pile is the num of bananas in piles*/
hrs += Math.ceil(pile/midk);
}
if(hrs > h){
/*Now if hrs > h she will not be to finish the pile so we have
to increase the bananas by moving start.*/
startk = midk + 1;
}else{
/*If hrs <= h she will be eating too fast so we can reduce the bananas
so she eats slowly. So decrement end.*/
endk = midk - 1;
}
}
return startk;
}; | Koko Eating Bananas |
You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.
Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.
The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.
You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.
Return the array answer as described above.
Example 1:
Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
Output: [0,2,0,0,0]
Explanation:
The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.
Example 2:
Input: logs = [[1,1],[2,2],[2,3]], k = 4
Output: [1,1,0,0]
Explanation:
The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
There is one user with a UAM of 1 and one with a UAM of 2.
Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.
Constraints:
1 <= logs.length <= 104
0 <= IDi <= 109
1 <= timei <= 105
k is in the range [The maximum UAM for a user, 105].
| class Solution:
def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:
ret = [0] * k # UAM store
user_acts = {} # User minutes store
# Adding user minutes to hash table
for log in logs:
if user_acts.get(log[0], 0):
user_acts[log[0]].append(log[1])
else:
user_acts[log[0]] = [log[1]]
# Calculating UAM
for k, v in user_acts.items():
l = len(set(v))
ret[l-1] += 1
return ret | class Solution {
public int[] findingUsersActiveMinutes(int[][] logs, int k) {
HashMap<Integer, HashSet<Integer>> usersMap = new HashMap();
for(int[] log : logs){
int user = log[0];
int min = log[1];
//add current user mapping, if not exist
usersMap.putIfAbsent(user, new HashSet<Integer>());
//add unique new minute
usersMap.get(user).add(min);
}
int[] result = new int[k];
for(int user : usersMap.keySet()){
int uam = usersMap.get(user).size();
//increment users count
result[uam - 1]++;
}
return result;
}
} | class Solution {
public:
vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k)
{
vector<int>ans(k,0);
unordered_map<int,unordered_set<int>>m;
for(int i = 0; i<logs.size(); i++)
{
m[logs[i][0]].insert(logs[i][1]);
}
for(auto x : m)
{
int t = x.second.size();
ans[t-1]++;
}
return ans;
}
}; | var findingUsersActiveMinutes = function(logs, k) {
const map = new Map();
for (const [userID, minute] of logs) {
if (!map.has(userID)) map.set(userID, new Set());
map.get(userID).add(minute);
}
const count = new Array(k).fill(0);
for (const actions of map.values()) {
count[actions.size - 1]++;
}
return count;
}; | Finding the Users Active Minutes |
You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:
0 represents an empty cell,
1 represents an obstacle that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).
Example 1:
Input: grid = [[0,1,1],[1,1,0],[1,1,0]]
Output: 2
Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).
It can be shown that we need to remove at least 2 obstacles, so we return 2.
Note that there may be other ways to remove 2 obstacles to create a path.
Example 2:
Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]
Output: 0
Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
2 <= m * n <= 105
grid[i][j] is either 0 or 1.
grid[0][0] == grid[m - 1][n - 1] == 0
| class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = [(0, 0, 0)]
dist = [[float('inf') for _ in range(n)] for _ in range(m)]
while q:
size = len(q)
for _ in range(size):
obs, x, y = heapq.heappop(q)
if dist[x][y] < float('inf'): continue
obs += grid[x][y]
dist[x][y] = obs
if x + 1 < m: heapq.heappush(q, (obs, x + 1, y))
if x > 0: heapq.heappush(q, (obs, x - 1, y))
if y + 1 < n: heapq.heappush(q, (obs, x, y + 1))
if y > 0: heapq.heappush(q, (obs, x, y - 1))
return dist[m - 1][n - 1] | class Solution {
int [][]grid;
int n,m;
boolean [][]seen;
int []dx = new int[]{0,0,1,-1};
int []dy = new int[]{1,-1,0,0};
int [][]dp;
int finalres;
private boolean isValid(int i, int j) {
return Math.min(i,j)>=0 && i<n && j<m && !seen[i][j];
}
private int solve(int i, int j, int cnt) {
if(cnt>=finalres) return finalres;
if(i == n-1 && j == m-1) {
return cnt;
}
if(dp[i][j]!=Integer.MAX_VALUE) return dp[i][j];
int res = n*m+1;
seen[i][j]=true;
for(int k=0;k<4;k++) {
int newI = i+dx[k], newJ = j+dy[k];
if(isValid(newI, newJ)) {
res = Math.min(res, solve(newI, newJ, cnt+grid[i][j]));
}
}
seen[i][j]=false;
return dp[i][j]=Math.min(dp[i][j], res);
}
public int minimumObstacles(int[][] grid) {
this.grid = grid;
this.n = grid.length;
this.m = grid[0].length;
this.seen = new boolean[n][m];
dp = new int[n][m];
finalres = n*m+1;
for(int []row:dp) Arrays.fill(row, Integer.MAX_VALUE);
return solve(0,0,0);
}
} | class Solution {
public:
int minimumObstacles(vector<vector<int>>& grid) {
int m=grid.size(), n=grid[0].size();
vector<int> dir={0,1,0,-1,0};
vector<vector<int>> dist(m, vector<int> (n,INT_MAX));
vector<vector<bool>> vis(m, vector<bool>(n,0));
deque<pair<int,int>>q;
dist[0][0]=0;
q.push_front({0,0});
while(!q.empty())
{
auto cur=q.front();
q.pop_front();
int x=cur.first;
int y=cur.second;
for(int i=0;i<4;i++)
{
int cx=x+dir[i];
int cy=y+dir[i+1];
if(cx>=0 and cy>=0 and cx<m and cy<n)
{
if(!vis[cx][cy])
{
dist[cx][cy]=dist[x][y]+(grid[cx][cy]==1);
if(grid[cx][cy]==1)
q.push_back({cx,cy});//obstacle cell pushed at the end
else
q.push_front({cx,cy}); //empty cell pushed on top
vis[cx][cy] = true;
}
}
}
}
return dist[m-1][n-1];
}
}; | /**
* @param {number[][]} grid
* @return {number}
*/
var minimumObstacles = function(grid) {
let dx=[[0,1],[0,-1],[1,0],[-1,0]];
let distance=[];
for(let i=0;i<grid.length;i++){
distance[i]=[];
for(let j=0;j<grid[i].length;j++){
distance[i][j]=Number.MAX_SAFE_INTEGER;
}
}
return bfs(0,0);
function bfs(row,col){
let queue=[];
distance[row][col]=0;
queue.push([row,col]);
while(queue.length>0){
let element = queue.shift();
let row = element[0];
let col = element[1];
let originalDist = distance[row][col];
for(let d=0;d<dx.length;d++){
let i = row + dx[d][0];
let j = col + dx[d][1];
if(i>=0 && i<=grid.length-1 && j>=0 && j<=grid[i].length-1){
let dist = originalDist;
if(grid[i][j]===1){
dist++;
}
if(distance[i][j]>dist){//Update distance for this neighbour node if the new distance is smaller than the previous distance
queue.push([i,j]);
distance[i][j]=dist;
}
}
}
}
//return the minimum distance for last cell after completing the process
return distance[(grid.length-1)][(grid[row].length-1)];
}
}; | Minimum Obstacle Removal to Reach Corner |
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.
Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Example 1:
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
Constraints:
The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 104
| class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
hashMap = {}
def helper(root: Optional[TreeNode]) -> int:
if not root:
return 0
if root in hashMap:
return hashMap[root]
ansOption1 = root.val
if root.left is not None:
ansOption1 += (helper(root.left.left) + helper(root.left.right))
if root.right is not None:
ansOption1 += (helper(root.right.left) + helper(root.right.right))
ansOption2 = helper(root.left) + helper(root.right)
ansFinal = max(ansOption1, ansOption2)
hashMap[root] = ansFinal
return ansFinal
return helper(root)
| /**
* 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 {
static class Pair{
int withRob=0;
int withoutRob=0;
}
public int rob(TreeNode root) {
Pair nodeRob=rob_(root);
return Math.max(nodeRob.withRob,nodeRob.withoutRob);
}
public Pair rob_(TreeNode root){
if(root==null){
return new Pair();
}
Pair l=rob_(root.left);
Pair r=rob_(root.right);
Pair nodeRob=new Pair();
nodeRob.withRob=root.val+l.withoutRob+r.withoutRob;
nodeRob.withoutRob=Math.max(l.withRob,l.withoutRob)+Math.max(r.withRob,r.withoutRob);
return nodeRob;
}
} | class Solution {
public:
vector<int> dp(TreeNode* root)
{
vector<int> ans(2,0); //dp[0]: maximal money you can get by robbing current node. dp[1]: maximal money you can get when not rob this node
if(root==NULL) return ans;
vector<int> left=dp(root->left);
vector<int> right=dp(root->right);
ans[0]=root->val+left[1]+right[1];
ans[1]=max(left[0],left[1])+max(right[0],right[1]);
return ans;
}
int rob(TreeNode* root) {
vector<int> ans=dp(root);
return max(ans[0],ans[1]);
}
}; | var rob = function(root) {
const dfs = (node = root) => {
if (!node || node.val === null) return [0, 0];
const { val, left, right } = node;
const [robL, notRobL] = dfs(left);
const [robR, notRobR] = dfs(right);
const rob = val + notRobL + notRobR;
const notRob = Math.max(robL, notRobL) + Math.max(robR, notRobR);
return [rob, notRob];
};
return Math.max(...dfs());
}; | House Robber III |
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Constraints:
1 <= num1.length, num2.length <= 104
num1 and num2 consist of only digits.
num1 and num2 don't have any leading zeros except for the zero itself.
| class Solution:
def addStrings(self, num1: str, num2: str) -> str:
def func(n):
value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
result = 0
for digit in n:
result = 10 * result + value[digit]
return result
ans = func(num1) + func(num2)
return str(ans) | import java.math.BigInteger;
class Solution {
public String addStrings(String num1, String num2) {
return new BigInteger(num1).add(new BigInteger(num2)).toString();
}
} | class Solution {
public:
string ans="";
int carry=0;
string addStrings(string num1, string num2) {
while(num1.size() && num2.size()){
int sum= (num1.back() -'0' + num2.back() -'0' + carry) ;
ans = (char)((sum%10) + '0') + ans;
carry= sum/10;
num1.pop_back();num2.pop_back();
}
while(num1.size()){
int sum= (num1.back() -'0' + carry) ;
ans = (char)((sum%10) + '0') + ans ;
carry= sum/10;
num1.pop_back();
}
while(num2.size()){
int sum= (num2.back() -'0' + carry) ;
ans = (char)((sum%10) + '0') + ans ;
carry= sum/10;
num2.pop_back();
}
if(carry) ans = (char)(carry+'0') + ans;
return ans;
}
}; | var addStrings = function(num1, num2) {
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
let sum = '';
for (;i >= 0 || j >= 0 || carry > 0;i--, j--) {
const digit1 = i < 0 ? 0 : num1.charAt(i) - '0';
const digit2 = j < 0 ? 0 : num2.charAt(j) - '0';
const digitsSum = digit1 + digit2 + carry;
sum = `${digitsSum % 10}${sum}`;
carry = Math.floor(digitsSum / 10);
}
return sum;
}; | Add Strings |
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.
Constraints:
1 <= n <= 20
1 <= k <= n
| class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
return itertools.combinations(range(1, n+1), k) | class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> subsets=new ArrayList<>();
generatesubsets(1,n,new ArrayList(),subsets,k);
return subsets;
}
void generatesubsets(int start,int n,List<Integer> current,List<List<Integer>> subsets,int k){
if(current.size()==k){
subsets.add(new ArrayList(current));
}
for(int i=start;i<=n;i++){
current.add(i);
generatesubsets(i+1,n,current,subsets,k);
current.remove(current.size()-1);
}
}
} | class Solution {
public:
void solve(vector<int> arr,vector<vector<int>> &ans,vector<int> &temp,int k,int x){
if(temp.size()==k){
ans.push_back(temp);
return;
}
if(x>=arr.size()) return ;
for(int i = x;i<arr.size();i++){
temp.push_back(arr[i]);
solve(arr,ans,temp,k,i+1);
temp.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> temp;
vector<int> arr;
for(int i = 1;i<=n;i++) arr.push_back(i);
solve(arr,ans,temp,k,0);
return ans;
}
}; | var combine = function(n, k) {
function helper (start, end, combo, subset, answer) {
if (combo==0) {
answer.push([...subset])
return;
}
if (end - start + 1 < combo) {
return;
}
if (start > end) {
return;
}
subset.push(start)
helper(start+1, end, combo - 1, subset, answer)
subset.pop()
helper(start+1, end, combo, subset, answer)
}
const answer = []
helper(1, n, k, [], answer)
return answer
}; | Combinations |
You are given an array of strings words. Each element of words consists of two lowercase English letters.
Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.
Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.
A palindrome is a string that reads the same forward and backward.
Example 1:
Input: words = ["lc","cl","gg"]
Output: 6
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.
Example 2:
Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.
Example 3:
Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".
Constraints:
1 <= words.length <= 105
words[i].length == 2
words[i] consists of lowercase English letters.
| class Solution(object):
def longestPalindrome(self, words):
wc = collections.Counter(words)
aa = 0 # count how many words contain only two identical letters like 'aa'
center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2
abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively
for w, c in wc.items():
if w[0] == w[1]: # like 'aa', 'bb', ...
aa += c // 2 * 2 # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively
# if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2
if c % 2 == 1: center = 2
else:
abba += min(wc[w], wc[w[::-1]]) * 0.5 # will definitely double counting
return aa * 2 + int(abba) * 4 + center | class Solution {
public int longestPalindrome(String[] words) {
int[][] freq = new int[26][26];//array for all alphabet combinations
for (String word : words)
freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word
int left = 0;//to store freq counts
boolean odd = false;
for (int i = 0; i != 26; i++) {//iterate over our array
odd |= (freq[i][i] & 1) == 1;//means odd number of freq for similar words are there
left += freq[i][i] / 2;
for (int j = i + 1; j != 26; j++)//nested iteration to find non similar pairs
left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present
}
int res = left * 2 * 2;//res from total freq found!!
if (odd){
res+=2;// if odd then adding 2
}
return res;
}
} | class Solution {
public:
int longestPalindrome(vector<string>& words) {
int count[26][26] = {};
int ans =0;
for(auto w : words){
int a = w[0] - 'a';
int b = w[1] - 'a';
if(count[b][a]){
ans+= 4;
count[b][a]--; // decrement the count as we found mirror word
}else
count[a][b]++; //increment the current word count if we not find any mirror word
}
for(int i=0;i<26;i++){
if(count[i][i]){
ans+=2;
break;
}
}
return ans;
}
}; | var longestPalindrome = function(words) {
const n = words.length;
const map = new Map();
let len = 0;
for (const word of words) {
const backward = word.split("").reverse().join("");
if (map.has(backward)) {
len += (word.length * 2);
map.set(backward, map.get(backward) - 1);
if (map.get(backward) === 0) map.delete(backward);
}
else {
if (!map.has(word)) map.set(word, 0);
map.set(word, map.get(word) + 1);
}
}
let maxLenSelfPalindrome = 0;
for (const word of map.keys()) {
if (isPalindrome(word)) {
maxLenSelfPalindrome = Math.max(maxLenSelfPalindrome, word.length);
}
}
return len + maxLenSelfPalindrome;
function isPalindrome(word) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left] != word[right]) return false;
left++;
--right;
}
return true;
}
}; | Longest Palindrome by Concatenating Two Letter Words |